def events(subreddit): import praw new = [] r = praw.Reddit(user_agent='Kodi Castaway') r = login(r) r.config.api_request_delay = 0 filtering = control.setting('enable_subreddit_filters') == 'true' okay = True try: for submission in r.get_subreddit(subreddit).get_hot(limit=30): if filtering: words = control.setting('subreddit_filters').split(',') if any(word in submission.title.lower() for word in words): okay = True else: okay = False if okay: url = submission.id title = submission.title title = title.encode('utf-8') new.append((url,title)) return new except: return []
def library(self): self.addDirectoryItem(32557, 'openSettings&query=5.0', 'tools.png', 'DefaultAddonProgram.png') self.addDirectoryItem(32558, 'updateLibrary&query=tool', 'library_update.png', 'DefaultAddonProgram.png') self.addDirectoryItem(32559, control.setting('library.movie'), 'movies.png', 'DefaultMovies.png', isAction=False) self.addDirectoryItem(32560, control.setting('library.tv'), 'tvshows.png', 'DefaultTVShows.png', isAction=False) if trakt.getTraktCredentialsInfo(): self.addDirectoryItem(32561, 'moviesToLibrary&url=traktcollection', 'trakt.png', 'DefaultMovies.png') self.addDirectoryItem(32562, 'moviesToLibrary&url=traktwatchlist', 'trakt.png', 'DefaultMovies.png') self.addDirectoryItem(32563, 'tvshowsToLibrary&url=traktcollection', 'trakt.png', 'DefaultTVShows.png') self.addDirectoryItem(32564, 'tvshowsToLibrary&url=traktwatchlist', 'trakt.png', 'DefaultTVShows.png') self.endDirectory()
def log(msg, level=LOGNOTICE): debug_enabled = control.setting('trakt_debug') debug_log = control.setting('debug.location') print DEBUGPREFIX + ' Debug Enabled?: ' + str(debug_enabled) print DEBUGPREFIX + ' Debug Log?: ' + str(debug_log) if not control.setting('trakt_debug') == 'true': return try: if isinstance(msg, unicode): msg = '%s (ENCODED)' % (msg.encode('utf-8')) if not control.setting('debug.location') == '0': log_file = os.path.join(LOGPATH, 'wraith.log') if not os.path.exists(log_file): f = open(log_file, 'w') f.close() with open(log_file, 'a') as f: line = '[%s %s] %s: %s' % (datetime.now().date(), str(datetime.now().time())[:8], DEBUGPREFIX, msg) f.write(line.rstrip('\r\n') + '\n') else: print '%s: %s' % (DEBUGPREFIX, msg) except Exception as e: try: xbmc.log('Logging Failure: %s' % (e), level) except: pass
def events(subreddit): import praw new = [] r = praw.Reddit(user_agent='Kodi Castaway', disable_update_check=True) r = login(r) r.config.api_request_delay = 0 filtering = control.setting('enable_subreddit_filters') == 'true' okay = True try: for submission in r.get_subreddit(subreddit).get_hot(limit=30): if filtering: words = control.setting('subreddit_filters').split(',') if any(word in submission.title.lower() for word in words): okay = True else: okay = False if okay: url = submission.id title = submission.title title = title.encode('utf-8') new.append((url, title)) return new except: return []
def __init__(self): self.library_folder = os.path.join(control.transPath(control.setting('library.movie')), '') self.check_setting = control.setting('library.check_movie') or 'false' self.library_setting = control.setting('library.update') or 'true' self.dupe_setting = control.setting('library.check') or 'true' self.fredy = 10 self.infoDialog = False self.silentDialog = False self.war1 = True
def login(r): user = control.setting('reddit_user') passw = control.setting('reddit_pass') login = user!='' and passw!='' if login: try: r.login(user, passw) except: control.infoDialog('Please check your Reddit username and password.') return r
def get(name, imdb, season, episode): try: langs = [] try: langs.append(langDict[control.setting('sublang1')]) except: pass try: langs.append(langDict[control.setting('sublang2')]) except: pass try: subLang = xbmc.Player().getSubtitles() except: subLang = '' if subLang == langs[0]: raise Exception() server = xmlrpclib.Server('http://api.opensubtitles.org/xml-rpc', verbose=0) token = server.LogIn('', '', 'en', 'XBMC_Subtitles_v1')['token'] sublanguageid = ','.join(langs) ; imdbid = re.sub('[^0-9]', '', imdb) if not (season == '' or episode == ''): result = server.SearchSubtitles(token, [{'sublanguageid': sublanguageid, 'imdbid': imdbid, 'season': season, 'episode': episode}])['data'] fmt = ['hdtv'] else: result = server.SearchSubtitles(token, [{'sublanguageid': sublanguageid, 'imdbid': imdbid}])['data'] try: vidPath = xbmc.Player().getPlayingFile() except: vidPath = '' fmt = re.split('\.|\(|\)|\[|\]|\s|\-', vidPath) fmt = [i.lower() for i in fmt] fmt = [i for i in fmt if i in quality] filter = [] result = [i for i in result if i['SubSumCD'] == '1'] for lang in langs: filter += [i for i in result if i['SubLanguageID'] == lang and any(x in i['MovieReleaseName'].lower() for x in fmt)] filter += [i for i in result if i['SubLanguageID'] == lang and any(x in i['MovieReleaseName'].lower() for x in quality)] filter += [i for i in result if i['SubLanguageID'] == lang] try: lang = xbmc.convertLanguage(filter[0]['SubLanguageID'], xbmc.ISO_639_1) except: lang = filter[0]['SubLanguageID'] content = [filter[0]['IDSubtitleFile'],] content = server.DownloadSubtitles(token, content) content = base64.b64decode(content['data'][0]['data']) content = zlib.decompressobj(16+zlib.MAX_WBITS).decompress(content) subtitle = xbmc.translatePath('special://temp/') subtitle = os.path.join(subtitle, 'TemporarySubs.%s.srt' % lang) file = control.openFile(subtitle, 'w') file.write(str(content)) file.close() xbmc.sleep(1000) xbmc.Player().setSubtitles(subtitle) except: pass
def login(r): user = control.setting('reddit_user') passw = control.setting('reddit_pass') login = user != '' and passw != '' if login: try: r.login(user, passw) except: control.infoDialog( 'Please check your Reddit username and password.') return r
def downloads(self): movie_downloads = control.setting('movie.download.path') tv_downloads = control.setting('tv.download.path') if len(control.listDir(movie_downloads)[0]) > 0: self.addDirectoryItem(32001, movie_downloads, 'movies.png', 'DefaultMovies.png', isAction=False) if len(control.listDir(tv_downloads)[0]) > 0: self.addDirectoryItem(32002, tv_downloads, 'tvshows.png', 'DefaultTVShows.png', isAction=False) self.endDirectory()
def __init__(self, key=''): self.base_link = 'http://www.youtube.com' self.key_link = control.setting('api_key') or key self.key_link = '&key=%s' % base64.urlsafe_b64decode(self.key_link) self.search_link = 'https://www.googleapis.com/youtube/v3/search?part=snippet&type=video&maxResults=5&q=%s' self.youtube_search = 'https://www.googleapis.com/youtube/v3/search?q=' self.youtube_watch = 'http://www.youtube.com/watch?v=%s'
def run(self, meta): loop_vid = control.setting("loop_vid") == 'true' self.getVideoInfo(meta) if meta["thumb"] is None: meta["thumb"] = "DefaultVideo.png" item = control.item(path=meta["url"], iconImage=meta["thumb"], thumbnailImage=meta["thumb"]) item.setInfo(type='Video', infoLabels={"Title": self.title}) item.setProperty('Video', 'true') # item.setProperty('IsPlayable', 'true') item.setProperty("ListItem.IsResumable", "true") item.setProperty("ListItem.EndTime", meta["endTime"]) item.setProperty("totaltime", meta["endTime"]) playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO) playlist.clear() playlist.add(meta["url"], item) control.player.play(playlist) if loop_vid: xbmc.executebuiltin("PlayerControl(RepeatAll)") for i in range(0, 240): if self.isPlayingVideo(): break xbmc.sleep(1000) while self.isPlayingVideo(): try: self.totalTime = self.getTotalTime() except Exception, e: print str(e) pass try: self.currentTime = self.getTime() except Exception, e: print str(e) pass
def CheckLinksInLibrary(self): import thread_pool import time self.t_link_delay = int(control.setting('library.service.testlink.delay') or 0) if self.t_link_delay == 0: printuj_linka('[CheckLink]: START and STOP - Do not check library sources') return dirs,files = control.listDir(self.library_folder) self.progressDialogBG = control.progressDialogBG self.progressDialogBG.create('Sprawdzam \xc5\xbar\xc3\xb3d\xc5\x82a biblioteki cda.pl','Ilo\xc5\x9b\xc4\x87 pozycji: %d'%len(dirs)) printuj_linka('[CheckLink]: START Library Folders = %d'%len(dirs)) if not control.condVisibility('Window.IsVisible(infodialog)') and not control.condVisibility('Player.HasVideo'): try: control.infoDialog('Sprawdzam \xc5\xbar\xc3\xb3dla biblioteki cda.pl', time=3) self.infoDialog = True except: self.infoDialog = False pool = thread_pool.ThreadPool(self.fredy) self.res={'checked':0,'skipped':0,'removed':0,'updated':0} N = len(dirs) for idx,folder_ in enumerate(dirs): pool.add_task(self.check_remove, *(folder_,idx,N)) time.sleep(0.1) pool.wait_completion() printuj_linka('[CheckLink]: END Status checked:%d, skipped:%d, removed:%d, updated:%d'%(self.res['checked'],self.res['skipped'],self.res['removed'],self.res['updated'])) self.progressDialogBG.close() if self.infoDialog == True: control.infoDialog('Usuni\xc4\x99to :%d, Zaktualizowano :%d '%(self.res['removed'],self.res['updated']), time=30)
def onPlayBackStarted(self): if control.setting('playback_info') == 'true': elapsedTime = '%s %s seconds' % (control.lang(30309).encode('utf-8'), int((time.time() - self.loadingTime))) control.infoDialog(elapsedTime, heading=self.name) try: if self.offset == '0': raise Exception() self.seekTime(float(self.offset)) except: pass try: if not control.setting('subtitles') == 'true': raise Exception() try: subtitle = subtitles.get(self.name, self.imdb, self.season, self.episode) except: subtitle = subtitles.get(self.name, self.imdb, '', '') except: pass
def add_gallery_item(item): api = imgur.Api() allow_nsfw = control.setting("enable_nsfw") == 'true' if "cover" in item: thumb = api.url_image_medium % item["cover"] icon = api.url_image_thumb % item["cover"] add_directory(item["title"], icon, thumb, "%s?action=album&id=%s" % (sys.argv[0], item["id"])) else: is_nsfw = "nsfw" in item and item["nsfw"] if is_nsfw and not allow_nsfw: return text_dec = text_red if is_nsfw else text_blue if item["type"] not in api.video_types or not item["animated"]: image = item["link"] thumb = api.url_image_thumb % item["id"] add_image(text_dec % item["title"], thumb, image) else: # not all have mp4 if "mp4" in item: url = item["mp4"] elif "gifv" in item: url = item["gifv"] else: url = item["link"] thumb = api.url_image_thumb % item["id"] add_video(text_dec % item["title"], thumb, url) return
def __init__(self): utils.set_no_sort() utils.add_directory(utils.text_green % control.lang(30502), utils.icon_settings, None, "%s?action=settings" % (sys.argv[0])) boards = utils.get_boards()["boards"] nsfw = control.setting("enable_nsfw") == 'true' for b in boards: is_nsfw = b["ws_board"] == 0 if not nsfw and is_nsfw: continue if is_nsfw: title = utils.text_board_nsfw % (b["board"], b["title"]) else: title = utils.text_board % (b["board"], b["title"]) utils.add_directory( title, utils.icon_board, utils.icon_board, "%s?action=board&board=%s&total_pages=%s" % (sys.argv[0], urllib.quote_plus(b["board"]), b["pages"])) control.directory_end(force_thumb=False) return
def error(msg, caller=None): if control.setting('debug') == 'true': func = inspect.currentframe().f_back.f_code if caller is not None: caller = "%s.%s()" % (caller, func.co_name) log('%s\n%s' % (str(msg) , traceback.format_exc()), caller, level=LOGERROR)
def printException(function): try: debug = True if control.setting('debug') == 'true' else False except: debug = True if debug: print 'Exception in %s' % (function) traceback.print_exc()
def __init__(self, key=''): self.list = [] ; self.data = [] self.base_link = 'http://www.youtube.com' self.key_link = '&key={0}'.format(control.setting('api_key') or key) self.playlists_link = 'https://www.googleapis.com/youtube/v3/playlists?part=snippet&maxResults=50&channelId=%s' self.playlist_link = 'https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=%s' self.videos_link = 'https://www.googleapis.com/youtube/v3/search?part=snippet&order=date&maxResults=50&channelId=%s' self.content_link = 'https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id=%s' self.play_link = 'plugin://plugin.video.youtube/play/?video_id=%s'
def tvshows(self, lite=False): if self.getMenuEnabled('navi.tvGenres') == True: self.addDirectoryItem(32011, 'tvGenres', 'genres.png', 'DefaultTVShows.png') if self.getMenuEnabled('navi.tvNetworks') == True: self.addDirectoryItem(32016, 'tvNetworks', 'networks.png', 'DefaultTVShows.png') if self.getMenuEnabled('navi.tvLanguages') == True: self.addDirectoryItem(32014, 'tvLanguages', 'languages.png', 'DefaultTVShows.png') if self.getMenuEnabled('navi.tvCertificates') == True: self.addDirectoryItem(32015, 'tvCertificates', 'certificates.png', 'DefaultTVShows.png') if self.getMenuEnabled('navi.tvTrending') == True: self.addDirectoryItem(32017, 'tvshows&url=trending', 'people-watching.png', 'DefaultRecentlyAddedEpisodes.png') if self.getMenuEnabled('navi.tvPopular') == True: self.addDirectoryItem(32018, 'tvshows&url=popular', 'most-popular.png', 'DefaultTVShows.png') if self.getMenuEnabled('navi.tvRating') == True: self.addDirectoryItem(32023, 'tvshows&url=rating', 'highly-rated.png', 'DefaultTVShows.png') if self.getMenuEnabled('navi.tvViews') == True: self.addDirectoryItem(32019, 'tvshows&url=views', 'most-voted.png', 'DefaultTVShows.png') if self.getMenuEnabled('navi.tvAiring') == True: self.addDirectoryItem(32024, 'tvshows&url=airing', 'airing-today.png', 'DefaultTVShows.png') if self.getMenuEnabled('navi.tvActive') == True: self.addDirectoryItem(32025, 'tvshows&url=active', 'returning-tvshows.png', 'DefaultTVShows.png') if self.getMenuEnabled('navi.tvPremier') == True: self.addDirectoryItem(32026, 'tvshows&url=premiere', 'new-tvshows.png', 'DefaultTVShows.png') if self.getMenuEnabled('navi.tvAdded') == True: self.addDirectoryItem(32006, 'calendar&url=added', 'latest-episodes.png', 'DefaultRecentlyAddedEpisodes.png', queue=True) if self.getMenuEnabled('navi.tvCalendar') == True: self.addDirectoryItem(32027, 'calendars', 'calendar.png', 'DefaultRecentlyAddedEpisodes.png') if lite == False: if not control.setting('lists.widget') == '0': self.addDirectoryItem(32004, 'mytvliteNavigator', 'mytvshows.png', 'DefaultVideoPlaylists.png') self.addDirectoryItem(32028, 'tvPerson', 'people-search.png', 'DefaultTVShows.png') self.addDirectoryItem(32010, 'tvSearch', 'search.png', 'DefaultTVShows.png') self.endDirectory()
def getVideoInfo(self, content, name, imdb, tvdb): try: self.loadingTime = time.time() self.totalTime = 0 self.currentTime = 0 self.folderPath = control.infoLabel('Container.FolderPath') self.name = name self.content = content self.file = self.name + '.strm' self.file = self.file.translate(None, '\/:*?"<>|').strip('.') self.imdb = 'tt' + imdb if imdb.isdigit() else imdb self.tvdb = tvdb if not tvdb == None else '0' except: pass try: if self.content == 'movie': self.title, self.year = re.compile( '(.+?) [(](\d{4})[)]$').findall(self.name)[0] elif self.content == 'episode': self.show, self.season, self.episode = re.compile( '(.+?) S(\d*)E(\d*)$').findall(self.name)[0] self.season, self.episode = '%01d' % int( self.season), '%01d' % int(self.episode) except: pass try: if control.setting('resume_playback') == 'true': self.offset = bookmarks.getBookmark(self.name, self.imdb) if self.offset == '0': raise Exception() minutes, seconds = divmod(float(self.offset), 60) hours, minutes = divmod(minutes, 60) yes = control.yesnoDialog( '%s %02d:%02d:%02d' % (control.lang(30342).encode('utf-8'), hours, minutes, seconds), '', '', self.name, control.lang(30343).encode('utf-8'), control.lang(30344).encode('utf-8')) if yes: self.offset = '0' except: pass try: if self.content == 'movie': control.window.setProperty('script.trakt.ids', json.dumps({'imdb': self.imdb})) elif self.content == 'episode': control.window.setProperty('script.trakt.ids', json.dumps({'tvdb': self.tvdb})) except: pass
def selected_languages(): langs = "" setting_lang_items = control.lang(30602).split(",") for lang_item in setting_lang_items: lang_enabled = control.setting(lang_item) if lang_enabled == "true": langs += "lang=%s&" % lang_item if langs == "" or langs is None: return "lang=en" return langs[:-1]
def log(msg, caller, level=LOGDEBUG): # override message level to force logging when addon logging turned on if control.setting('debug') == 'true' and level == LOGDEBUG: level = LOGNOTICE try: if isinstance(msg, unicode): msg = '%s (ENCODED)' % (msg.encode('utf-8')) xbmc.log('[%s (%s)]: [%s] %s' % (name, version, caller, msg), level) except Exception as e: try: xbmc.log('Logging Failure: %s' % (e), level) except: pass # just give up
def language_filter(): # {SelectOnField: "LCID", SelectTerm: "1045", SelectMatchOption: 2} result = [] setting_lang_items = control.lang(30600).split(",") for lang_item in setting_lang_items: lang_enabled = control.setting(lang_item) if lang_enabled == "true": result.append({"SelectOnField": "LCID", "SelectTerm": "%s" % lang_item, "SelectMatchOption": 2}) if not result: return default_lanugage return result
def get_session(self): session = requests.Session() cookies = self.load_cookies() session.headers.update({'X-CSRF-Token': control.setting('tvm_token')}) if not cookies: self.login() session.cookies = self.load_cookies() session.headers.update( {'X-CSRF-Token': control.setting('tvm_token')}) return session session.cookies = cookies not_logged = 'Login | Keep track of your favorite shows' in session.get( 'http://www.tvmaze.com/dashboard').text if not_logged: self.login() session.headers.update( {'X-CSRF-Token': control.setting('tvm_token')}) session.cookies = self.load_cookies() return session return session
def get_token(self, pin=None): url = "/oauth/token" data = {"client_id": V2_API_KEY, "client_secret": CLIENT_SECRET, "redirect_uri": REDIRECT_URI} if pin: data["code"] = pin data["grant_type"] = "authorization_code" else: refresh_token = control.setting("trakt_refresh_token") if refresh_token: data["refresh_token"] = refresh_token data["grant_type"] = "refresh_token" else: raise TraktError("Can not refresh trakt token. Trakt reauthorizion required.") return self.__call_trakt(url, data=data, auth=False, cached=False)
def __init__(self, username, password): self.username = username self.password = password self.followed_num = 0 self.updated_watched = 0 self.already_watched = 0 self.failed = 0 self.headers = {} self.base_url = 'http://www.tvmaze.com/site/login' self.token = control.setting('tvm_token') self.headers['X-CSRF-Token'] = self.token self.session = self.get_session() self.headers['User-agent'] = 'TVMaze Kodi add-on'
def get_token(self, pin=None): url = '/oauth/token' data = {'client_id': V2_API_KEY, 'client_secret': CLIENT_SECRET, 'redirect_uri': REDIRECT_URI} if pin: data['code'] = pin data['grant_type'] = 'authorization_code' else: refresh_token = control.setting('trakt_refresh_token') if refresh_token: data['refresh_token'] = refresh_token data['grant_type'] = 'refresh_token' else: raise TraktError('Can not refresh trakt token. Trakt reauthorizion required.') return self.__call_trakt(url, data=data, auth=False, cached=False)
def movies(self, lite=False): if self.getMenuEnabled('navi.moviegenre') == True: self.addDirectoryItem(32011, 'movieGenres', 'genres.png', 'DefaultMovies.png') if self.getMenuEnabled('navi.movieyears') == True: self.addDirectoryItem(32012, 'movieYears', 'years.png', 'DefaultMovies.png') if self.getMenuEnabled('navi.moviepersons') == True: self.addDirectoryItem(32013, 'moviePersons', 'people.png', 'DefaultMovies.png') if self.getMenuEnabled('navi.movielanguages') == True: self.addDirectoryItem(32014, 'movieLanguages', 'languages.png', 'DefaultMovies.png') if self.getMenuEnabled('navi.moviecerts') == True: self.addDirectoryItem(32015, 'movieCertificates', 'certificates.png', 'DefaultMovies.png') if self.getMenuEnabled('navi.movietrending') == True: self.addDirectoryItem(32017, 'movies&url=trending', 'people-watching.png', 'DefaultMovies.png') if self.getMenuEnabled('navi.moviepopular') == True: self.addDirectoryItem(32018, 'movies&url=popular', 'most-popular.png', 'DefaultMovies.png') if self.getMenuEnabled('navi.movieviews') == True: self.addDirectoryItem(32019, 'movies&url=views', 'most-voted.png', 'DefaultMovies.png') if self.getMenuEnabled('navi.movieboxoffice') == True: self.addDirectoryItem(32020, 'movies&url=boxoffice', 'box-office.png', 'DefaultMovies.png') if self.getMenuEnabled('navi.movieoscars') == True: self.addDirectoryItem(32021, 'movies&url=oscars', 'oscar-winners.png', 'DefaultMovies.png') if self.getMenuEnabled('navi.movietheaters') == True: self.addDirectoryItem(32022, 'movies&url=theaters', 'in-theaters.png', 'DefaultMovies.png') if self.getMenuEnabled('navi.moviewidget') == True: self.addDirectoryItem(32005, 'movieWidget', 'latest-movies.png', 'DefaultMovies.png') if lite == False: if not control.setting('lists.widget') == '0': self.addDirectoryItem(32003, 'mymovieliteNavigator', 'mymovies.png', 'DefaultVideoPlaylists.png') self.addDirectoryItem(32028, 'moviePerson', 'people-search.png', 'DefaultMovies.png') self.addDirectoryItem(32010, 'movieSearch', 'search.png', 'DefaultMovies.png') self.endDirectory()
def root(self): self.addDirectoryItem(32001, 'movieNavigator', 'movies.png', 'DefaultMovies.png') self.addDirectoryItem(32002, 'tvNavigator', 'tvshows.png', 'DefaultTVShows.png') if self.getMenuEnabled('navi.channels') == True: self.addDirectoryItem(32007, 'channels', 'channels.png', 'DefaultMovies.png') if not control.setting('lists.widget') == '0': self.addDirectoryItem(32003, 'mymovieNavigator', 'mymovies.png', 'DefaultVideoPlaylists.png') self.addDirectoryItem(32004, 'mytvNavigator', 'mytvshows.png', 'DefaultVideoPlaylists.png') if not control.setting('movie.widget') == '0': self.addDirectoryItem(32005, 'movieWidget', 'latest-movies.png', 'DefaultRecentlyAddedMovies.png') if (traktIndicators == True and not control.setting('tv.widget.alt') == '0') or (traktIndicators == False and not control.setting('tv.widget') == '0'): self.addDirectoryItem(32006, 'tvWidget', 'latest-episodes.png', 'DefaultRecentlyAddedEpisodes.png') if not control.setting('furk.api') == '': self.addDirectoryItem('Furk.net', 'furkNavigator', 'movies.png', 'movies.png') if self.getMenuEnabled('navi.docu') == True: self.addDirectoryItem(32631, 'docuHeaven', 'movies.png', 'DefaultMovies.png') self.addDirectoryItem(32010, 'searchNavigator', 'search.png', 'DefaultAddonProgram.png') self.addDirectoryItem(32008, 'toolNavigator', 'tools.png', 'DefaultAddonProgram.png') self.addDirectoryItem('Scraper Settings', 'openscrapersSettings&query=0.0', 'tools.png', 'DefaultAddonProgram.png') downloads = True if control.setting('downloads') == 'true' and ( len(control.listDir(control.setting('movie.download.path'))[0]) > 0 or len(control.listDir(control.setting('tv.download.path'))[0]) > 0 ) else False if downloads == True: self.addDirectoryItem(32009, 'downloadNavigator', 'downloads.png', 'DefaultAddonProgram.png') self.addDirectoryItem('Info!!', 'newsNavigator', 'tools.png', 'DefaultAddonProgram.png') self.endDirectory()
def language_filter(): # {SelectOnField: "LCID", SelectTerm: "1045", SelectMatchOption: 2} result = [] setting_lang_items = control.lang(30600).split(",") for lang_item in setting_lang_items: lang_enabled = control.setting(lang_item) if lang_enabled == "true": result.append({ "SelectOnField": "LCID", "SelectTerm": "%s" % lang_item, "SelectMatchOption": 2 }) if not result: return default_lanugage return result
def __getTrakt(url, post=None): try: url = urlparse.urljoin(BASE_URL, url) post = json.dumps(post) if post else None headers = {'Content-Type': 'application/json', 'trakt-api-key': V2_API_KEY, 'trakt-api-version': 2} if getTraktCredentialsInfo(): headers.update({'Authorization': 'Bearer %s' % control.setting('trakt.token')}) result = client.request(url, post=post, headers=headers, output='extended', error=True) resp_code = result[1] resp_header = result[2] result = result[0] if resp_code in ['500', '502', '503', '504', '520', '521', '522', '524']: log_utils.log('Temporary Trakt Error: %s' % resp_code, log_utils.LOGWARNING) return elif resp_code in ['404']: log_utils.log('Object Not Found : %s' % resp_code, log_utils.LOGWARNING) return # elif resp_code in ['429']: # log_utils.log('Trakt Rate Limit Reached: %s' % resp_code, log_utils.LOGWARNING) # return if resp_code not in ['401', '405']: return result, resp_header oauth = urlparse.urljoin(BASE_URL, '/oauth/token') opost = {'client_id': V2_API_KEY, 'client_secret': CLIENT_SECRET, 'redirect_uri': REDIRECT_URI, 'grant_type': 'refresh_token', 'refresh_token': control.setting('trakt.refresh')} result = client.request(oauth, post=json.dumps(opost), headers=headers) result = utils.json_loads_as_str(result) token, refresh = result['access_token'], result['refresh_token'] control.setSetting(id='trakt.token', value=token) control.setSetting(id='trakt.refresh', value=refresh) headers['Authorization'] = 'Bearer %s' % token result = client.request(url, post=post, headers=headers, output='extended', error=True) return result[0], result[2] except Exception as e: log_utils.log('Unknown Trakt Error: %s' % e, log_utils.LOGWARNING) pass
def __init__(self): self.library_folder = os.path.join(control.transPath(control.setting('library.movie')), '') try: lib_serv_last_run = control.setting('library.service.last.run') lib_serv_last_run = datetime.datetime.strptime(lib_serv_last_run, '%Y-%m-%d %H:%M:%S') t1 = datetime.timedelta(hours=int(control.setting('library.service.wait.time'))) czasOK = t1-abs(datetime.datetime.now() - lib_serv_last_run) except: czasOK= False dirs,files = control.listDir(self.library_folder) if self.library_folder else ([],[]) self.ilosc_filmow = 'Ilo\xc5\x9b\xc4\x87 film\xc3\xb3w w bibliotece: [B]%d[/B]'%len(dirs) self.aktualizacja_co_ile = 'Aktulizacja co: [B]%s h[/B]'%control.setting('library.service.wait.time') lib_serv_test_delay = control.setting('library.service.testlink.delay') self.nie_sa_sprawdzane = '\xc5\xb9r\xc3\xb3d\xc5\x82a biblioteki nie s\xc4\x85 sprawdzane okresowo [B](0 dni)[/B]' if lib_serv_test_delay=='0' else 'Sprawdzanie \xc5\xbar\xc3\xb3de\xc5\x82 co: [B]%s dni[/B]'%lib_serv_test_delay self.service_online = 'Service: [COLOR lightgreen]online[/COLOR]' if control.setting('library.service.active') == 'true' else 'Service: [COLOR red]offline[/COLOR]' if control.setting('library.service.active') == 'true' and czasOK: chwilka = 'chwilk\xc4\x99' if czasOK.days<0 else str(czasOK).split('.')[0]+' h' self.nast_szukanie = 'Nast\xc4\x99pne szukanie za ok: [B] %s [/B] '%chwilka else: self.nast_szukanie = 'Nast\xc4\x99pne szukanie nie wiadomo kiedy' self.ostat_aktualizacja = 'Ostatnia Aktualizacja: [B]%s[/B]'%control.setting('library.service.last.run')
def onPlayBackStarted(self): for i in range(0, 200): if control.condVisibility('Window.IsActive(busydialog)') == 1: control.idle() else: break control.sleep(100) if control.setting('playback_info') == 'true': elapsedTime = '%s %s %s' % (control.lang(30464).encode('utf-8'), int((time.time() - self.loadingTime)), control.lang(30465).encode('utf-8')) control.infoDialog(elapsedTime, heading=self.title) try: if self.offset == '0': raise Exception() self.seekTime(float(self.offset)) except Exception, e: print str(e) pass
def getVideoInfo(self, content, name, imdb, tvdb): try: self.loadingTime = time.time() self.totalTime = 0 ; self.currentTime = 0 self.folderPath = control.infoLabel('Container.FolderPath') self.name = name ; self.content = content self.file = self.name + '.strm' self.file = self.file.translate(None, '\/:*?"<>|').strip('.') self.imdb = 'tt' + imdb if imdb.isdigit() else imdb self.tvdb = tvdb if not tvdb == None else '0' except: pass try: if self.content == 'movie': self.title, self.year = re.compile('(.+?) [(](\d{4})[)]$').findall(self.name)[0] elif self.content == 'episode': self.show, self.season, self.episode = re.compile('(.+?) S(\d*)E(\d*)$').findall(self.name)[0] self.season, self.episode = '%01d' % int(self.season), '%01d' % int(self.episode) except: pass try: if control.setting('resume_playback') == 'true': self.offset = bookmarks.getBookmark(self.name, self.imdb) if self.offset == '0': raise Exception() minutes, seconds = divmod(float(self.offset), 60) ; hours, minutes = divmod(minutes, 60) yes = control.yesnoDialog('%s %02d:%02d:%02d' % (control.lang(30342).encode('utf-8'), hours, minutes, seconds), '', '', self.name, control.lang(30343).encode('utf-8'), control.lang(30344).encode('utf-8')) if yes: self.offset = '0' except: pass try: if self.content == 'movie': control.window.setProperty('script.trakt.ids', json.dumps({'imdb': self.imdb})) elif self.content == 'episode': control.window.setProperty('script.trakt.ids', json.dumps({'tvdb': self.tvdb})) except: pass
def GetNewMovies(self): from cdapl import searchCDA import thread_pool import time self.check_setting = 'false' url = 'https://www.cda.pl/video/show/cale_filmy_or_caly_film_or_lektor_or_pl_or_dubbing_or_napisy_or_fps_or_odc/p%d?duration=dlugie§ion=&quality=720p§ion=&s=date§ion=' if not control.condVisibility('Window.IsVisible(infodialog)') and not control.condVisibility('Player.HasVideo'): try: control.infoDialog('Szukam nowych film\xc3\xb3w ...', time=3) self.infoDialog = True except: self.infoDialog = False self.progressDialogBG = control.progressDialogBG self.progressDialogBG.create('cda.pl','Szukam nowych film\xc3\xb3w ...') items=[] control.setSetting('library.service.last.run', datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')) for stronkaX in range(int(control.setting('library.service.pages') or 1)): stronkaX +=1 printuj_linka('[AddMovie]: Searching cda.pl, page [%d]'%stronkaX) nowy_link,next=searchCDA(url%(stronkaX),False,False) items.extend(nowy_link) self.progressDialogBG.update(0,message='Znalaz\xc5\x82em pozycji [%d] '%(len(items))) self.progressDialogBG.update(0,message='Indentyfikuje %d film\xc3\xb3w w %d w\xc4\x85tkach ...'%(len(items),self.fredy)) items = [x for x in items if x.get('code','')!= ''] printuj_linka('[AddMovie]: Found Total %d videos ... '%(len(items))) pool = thread_pool.ThreadPool(self.fredy) self.out=[] N=len(items) for idx,one in enumerate(items): pool.add_task(self.dod_Movies, *(one,idx,N)) time.sleep(0.1) pool.wait_completion() printuj_linka('[AddMovie]: (After Threading) Found Total %d Movies ... '%(len(self.out))) self.out.reverse() self.progressDialogBG.close() self.add2( self.out ) control.setSetting('library.service.last.run', datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
''' import re import os import sys import urllib import urllib2 import urlparse import time import threading import control import cache import pyxbmct.addonwindow as pyxbmct downloadPath = control.setting('downloadPath') property = control.addonInfo('id') + '.downloader' def downloader(): thumb = control.addonThumb() ; fanart = control.addonFanart() status = control.window.getProperty(property + '.status') if not downloadPath == '': item = control.item('[COLOR FF00b8ff]Downloads[/COLOR]', iconImage=thumb, thumbnailImage=thumb) item.addContextMenuItems([], replaceItems=True) item.setProperty('fanart_image', fanart) control.addItem(handle=int(sys.argv[1]), url=downloadPath, listitem=item, isFolder=True)
def printException(function): try :debug = True if control.setting('debug') == 'true' else False except: debug = True if debug: print 'Exception in %s' % (function) traceback.print_exc()
along with this program. If not, see <http://www.gnu.org/licenses/>. ''' import re import os import sys import urllib import urllib2 import urlparse import time import threading import control import cache import pyxbmct.addonwindow as pyxbmct downloadPath = control.setting('downloadPath') property = control.addonInfo('id') + '.downloader' def downloader(): thumb = control.addonThumb() fanart = control.addonFanart() status = control.window.getProperty(property + '.status') if not downloadPath == '': item = control.item('[COLOR FF00b8ff]Downloads[/COLOR]', iconImage=thumb, thumbnailImage=thumb) item.addContextMenuItems([], replaceItems=True) item.setProperty('fanart_image', fanart)
def get(name, imdb, season, episode): try: langs = [] try: try: langs = langDict[control.setting("sublang1")].split(",") except: langs.append(langDict[control.setting("sublang1")]) except: pass try: try: langs = langs + langDict[control.setting("sublang2")].split(",") except: langs.append(langDict[control.setting("sublang2")]) except: pass try: subLang = xbmc.Player().getSubtitles() except: subLang = "" if subLang == langs[0]: raise Exception() server = xmlrpclib.Server("http://api.opensubtitles.org/xml-rpc", verbose=0) token = server.LogIn("", "", "en", "XBMC_Subtitles_v1")["token"] sublanguageid = ",".join(langs) imdbid = re.sub("[^0-9]", "", imdb) if not (season == "" or episode == ""): result = server.SearchSubtitles( token, [{"sublanguageid": sublanguageid, "imdbid": imdbid, "season": season, "episode": episode}] )["data"] fmt = ["hdtv"] else: result = server.SearchSubtitles(token, [{"sublanguageid": sublanguageid, "imdbid": imdbid}])["data"] try: vidPath = xbmc.Player().getPlayingFile() except: vidPath = "" fmt = re.split("\.|\(|\)|\[|\]|\s|\-", vidPath) fmt = [i.lower() for i in fmt] fmt = [i for i in fmt if i in quality] filter = [] result = [i for i in result if i["SubSumCD"] == "1"] for lang in langs: filter += [ i for i in result if i["SubLanguageID"] == lang and any(x in i["MovieReleaseName"].lower() for x in fmt) ] filter += [ i for i in result if i["SubLanguageID"] == lang and any(x in i["MovieReleaseName"].lower() for x in quality) ] filter += [i for i in result if i["SubLanguageID"] == lang] try: lang = xbmc.convertLanguage(filter[0]["SubLanguageID"], xbmc.ISO_639_1) except: lang = filter[0]["SubLanguageID"] content = [filter[0]["IDSubtitleFile"]] content = server.DownloadSubtitles(token, content) content = base64.b64decode(content["data"][0]["data"]) content = str(zlib.decompressobj(16 + zlib.MAX_WBITS).decompress(content)) subtitle = xbmc.translatePath("special://temp/") subtitle = os.path.join(subtitle, "TemporarySubs.%s.srt" % lang) codepage = codePageDict.get(lang, "") if codepage and control.setting("autoconvert_utf8") == "true": try: content_encoded = codecs.decode(content, codepage) content = codecs.encode(content_encoded, "utf-8") except: pass file = control.openFile(subtitle, "w") file.write(str(content)) file.close() xbmc.sleep(1000) xbmc.Player().setSubtitles(subtitle) except: pass