def alterSources(self, url, meta): try: if control.setting('hosts.mode') == '2': url += '&select=1' else: url += '&select=2' control.execute('RunPlugin(%s)' % url) except: pass
def search(self, query=None): if query is None: keydialog = control.keyboard('', "Enter Search") keydialog.doModal() self.query = keydialog.getText() if keydialog.isConfirmed() else None else: self.query = query if self.query is None or self.query is '': return if query is None: control.execute("Container.Update(%s?action=search&query=%s, false)" % (sys.argv[0], self.query)) return result = client.request("http://www.masterani.me/api/anime/search?search=%s&sb=true" % self.query) result = json.loads(result) print result if len(result) is 0: return for i in result: self.list.append({'anime_id': i['id'], 'status': 1}) self.worker() self.add_directory(self.list)
def add(self, tvshowtitle, year, imdb, tvdb, range=False): if not control.condVisibility('Window.IsVisible(infodialog)') and not control.condVisibility('Player.HasVideo'): control.infoDialog(control.lang(32552).encode('utf-8'), time=10000000) self.infoDialog = True from resources.lib.indexers import episodes items = episodes.episodes().get(tvshowtitle, year, imdb, tvdb, idx=False) try: items = [{'title': i['title'], 'year': i['year'], 'imdb': i['imdb'], 'tvdb': i['tvdb'], 'season': i['season'], 'episode': i['episode'], 'tvshowtitle': i['tvshowtitle'], 'premiered': i['premiered']} for i in items] except: items = [] try: if not self.dupe_setting == 'true': raise Exception() if items == []: raise Exception() id = [items[0]['imdb'], items[0]['tvdb']] lib = control.jsonrpc('{"jsonrpc": "2.0", "method": "VideoLibrary.GetTVShows", "params": {"properties" : ["imdbnumber", "title", "year"]}, "id": 1}') lib = unicode(lib, 'utf-8', errors='ignore') lib = json.loads(lib)['result']['tvshows'] lib = [i['title'].encode('utf-8') for i in lib if str(i['imdbnumber']) in id or (i['title'].encode('utf-8') == items[0]['tvshowtitle'] and str(i['year']) == items[0]['year'])][0] lib = control.jsonrpc('{"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodes", "params": {"filter":{"and": [{"field": "tvshow", "operator": "is", "value": "%s"}]}, "properties": ["season", "episode"]}, "id": 1}' % lib) lib = unicode(lib, 'utf-8', errors='ignore') lib = json.loads(lib)['result']['episodes'] lib = ['S%02dE%02d' % (int(i['season']), int(i['episode'])) for i in lib] items = [i for i in items if not 'S%02dE%02d' % (int(i['season']), int(i['episode'])) in lib] except: pass files_added = 0 for i in items: try: if xbmc.abortRequested == True: return sys.exit() if self.check_setting == 'true': if i['episode'] == '1': self.block = True src = lib_tools.check_sources(i['title'], i['year'], i['imdb'], i['tvdb'], i['season'], i['episode'], i['tvshowtitle'], i['premiered']) if src: self.block = False if self.block == True: raise Exception() premiered = i.get('premiered', '0') if (premiered != '0' and int(re.sub('[^0-9]', '', str(premiered))) > int(self.date)) or (premiered == '0' and not self.include_unknown): continue self.strmFile(i) files_added += 1 except: pass if range == True: return if self.infoDialog == True: control.infoDialog(control.lang(32554).encode('utf-8'), time=1) if self.library_setting == 'true' and not control.condVisibility('Library.IsScanningVideo') and files_added > 0: control.execute('UpdateLibrary(video)')
def browser(self, url): try: url = self.get(url) if url == False: return control.execute('RunPlugin(plugin://plugin.program.chrome.launcher/?url=%s&mode=showSite&stopPlayback=no)' % urllib.quote_plus(url)) except: pass
def range(self, url): control.idle() yes = control.yesnoDialog(control.lang(32555).encode('utf-8'), '', '') if not yes: return if not control.condVisibility('Window.IsVisible(infodialog)') and not control.condVisibility('Player.HasVideo'): control.infoDialog(control.lang(32552).encode('utf-8'), time=10000000) self.infoDialog = True from resources.lib.indexers import tvshows items = tvshows.tvshows().get(url, idx=False) if items == None: items = [] for i in items: try: if xbmc.abortRequested == True: return sys.exit() self.add(i['title'], i['year'], i['imdb'], i['tvdb'], range=True) except: pass if self.infoDialog == True: control.infoDialog(control.lang(32554).encode('utf-8'), time=1) if self.library_setting == 'true' and not control.condVisibility('Library.IsScanningVideo'): control.execute('UpdateLibrary(video)')
def range(self, url): control.idle() yes = control.yesnoDialog(control.lang(30425).encode("utf-8"), "", "") if not yes: return if not control.condVisibility("Window.IsVisible(infodialog)") and not control.condVisibility("Player.HasVideo"): control.infoDialog(control.lang(30421).encode("utf-8"), time=10000000) self.infoDialog = True from resources.lib.indexers import movies items = movies.movies().get(url, idx=False) if items == None: items = [] for i in items: try: if xbmc.abortRequested == True: return sys.exit() self.add(i["name"], i["title"], i["year"], i["imdb"], range=True) except: pass if self.infoDialog == True: control.infoDialog(control.lang(30423).encode("utf-8"), time=1) if self.library_setting == "true" and not control.condVisibility("Library.IsScanningVideo"): control.execute("UpdateLibrary(video)")
def play(self, name, url=None, windowedtrailer=0): try: url = self.worker(name, url) if not url: return title = control.infoLabel('listitem.title') if not title: title = control.infoLabel('listitem.label') icon = control.infoLabel('listitem.icon') item = control.item(path=url, iconImage=icon, thumbnailImage=icon) try: item.setArt({'icon': icon}) except: pass item.setInfo(type='Video', infoLabels={'title': title}) control.player.play(url, item, windowedtrailer) if windowedtrailer == 1: # The call to the play() method is non-blocking. So we delay further script execution to keep the script alive at this spot. # Otherwise this script will continue and probably already be garbage collected by the time the trailer has ended. control.sleep(1000) # Wait until playback starts. Less than 900ms is too short (on my box). Make it one second. while control.player.isPlayingVideo(): control.sleep(1000) # Close the dialog. # Same behaviour as the fullscreenvideo window when : # the media plays to the end, # or the user pressed one of X, ESC, or Backspace keys on the keyboard/remote to stop playback. control.execute("Dialog.Close(%s, true)" % control.getCurrentDialogId) except: pass
def play(self, url, content=None): try: base = url url = resolver().get(url) if url == False: return control.execute('ActivateWindow(busydialog)') url = resolver().process(url) control.execute('Dialog.Close(busydialog)') if url == None: return control.infoDialog(control.lang(30705).encode('utf-8')) if url == False: return meta = {} for i in ['title', 'originaltitle', 'tvshowtitle', 'year', 'season', 'episode', 'genre', 'rating', 'votes', 'director', 'writer', 'plot', 'tagline']: try: meta[i] = control.infoLabel('listitem.%s' % i) except: pass meta = dict((k,v) for k, v in meta.iteritems() if not v == '') if not 'title' in meta: meta['title'] = control.infoLabel('listitem.label') icon = control.infoLabel('listitem.icon') self.name = meta['title'] ; self.year = meta['year'] if 'year' in meta else '0' self.getbookmark = True if (content == 'movies' or content == 'episodes') else False self.offset = bookmarks().get(self.name, self.year) if not 'tvplayer' in url: if not 'itv' in url: f4m = resolver().f4m(url, self.name) if not f4m == None: return item = control.item(path=url, iconImage=icon, thumbnailImage=icon) try: item.setArt({'icon': icon}) except: pass item.setInfo(type='Video', infoLabels = meta) control.player.play(url, item) control.resolve(int(sys.argv[1]), True, item) self.totalTime = 0 ; self.currentTime = 0 for i in range(0, 240): if self.isPlayingVideo(): break control.sleep(1000) while self.isPlayingVideo(): try: self.totalTime = self.getTotalTime() self.currentTime = self.getTime() except: pass control.sleep(2000) control.sleep(5000) except: pass
def alterSources(self, url, meta): try: setting = control.setting('autoplay') if setting == 'false': url += '&url=direct://' else: url += '&url=dialog://' control.execute('RunPlugin(%s)' % url) except: pass
def link(self, url): try: url = self.get(url) if url == False: return control.execute('ActivateWindow(busydialog)') url = self.process(url) control.execute('Dialog.Close(busydialog)') if url == None: return control.infoDialog(control.lang(30705).encode('utf-8')) return url except: pass
def search(self): try: control.idle() k = control.keyboard('', 'Zoeken') ; k.doModal() q = k.getText() if k.isConfirmed() else None if (q == None or q == ''): return url = self.search_link % (urllib.quote_plus(q)) url = '%s?action=search_results&url=%s' % (sys.argv[0], urllib.quote_plus(url)) control.execute('Container.Update(%s)' % url) except: return
def person(self): try: control.idle() t = control.lang(32010).encode('utf-8') k = control.keyboard('', t) ; k.doModal() q = k.getText() if k.isConfirmed() else None if (q == None or q == ''): return url = self.persons_link + urllib.quote_plus(q) url = '%s?action=moviePersons&url=%s' % (sys.argv[0], urllib.quote_plus(url)) control.execute('Container.Update(%s)' % url) except: return
def setView(content, viewDict=None): for i in range(0, 200): if control.condVisibility('Container.Content(%s)' % content): try: skin = control.skin record = (skin, content) dbcon = database.connect(control.viewsFile) dbcur = dbcon.cursor() dbcur.execute("SELECT * FROM views WHERE skin = '%s' AND view_type = '%s'" % (record[0], record[1])) view = dbcur.fetchone() view = view[2] if view == None: raise Exception() return control.execute('Container.SetViewMode(%s)' % str(view)) except: try: return control.execute('Container.SetViewMode(%s)' % str(viewDict[skin])) except: return control.sleep(100)
def person(self, query=None): try: control.idle() sysloc = [urlparse.urlparse(sys.argv[0]).netloc, 'plugin.program.super.favourites' ] sysplg = True if control.infoLabel('Container.PluginName') in sysloc else False if query == None: t = control.lang(32010).encode('utf-8') k = control.keyboard('', t) ; k.doModal() query = k.getText() if k.isConfirmed() else None if (query == None or query == '' or sysplg == False): return url = self.persons_link + urllib.quote_plus(query) url = '%s?action=moviePersons&url=%s' % (sys.argv[0], urllib.quote_plus(url)) control.execute('Container.Update(%s)' % url) except: return
def search_new(self): control.idle() t = control.lang(32010).encode('utf-8') k = control.keyboard('', t) ; k.doModal() q = k.getText() if k.isConfirmed() else None if (q == None or q == ''): return try: from sqlite3 import dbapi2 as database except: from pysqlite2 import dbapi2 as database dbcon = database.connect(control.searchFile) dbcur = dbcon.cursor() dbcur.execute("INSERT INTO furk VALUES (?,?)", (None,q)) dbcon.commit() dbcur.close() url = urllib.quote_plus(q) url = '%s?action=furkMetaSearch&url=%s' % (sys.argv[0], urllib.quote_plus(url)) control.execute('Container.Update(%s)' % url)
def add(self, name, title, year, imdb, range=False): if not control.condVisibility("Window.IsVisible(infodialog)") and not control.condVisibility("Player.HasVideo"): control.infoDialog(control.lang(30421).encode("utf-8"), time=10000000) self.infoDialog = True try: if not self.dupe_setting == "true": raise Exception() id = imdb lib = control.jsonrpc( '{"jsonrpc": "2.0", "method": "VideoLibrary.GetMovies", "params": {"filter":{"or": [{"field": "year", "operator": "is", "value": "%s"}, {"field": "year", "operator": "is", "value": "%s"}, {"field": "year", "operator": "is", "value": "%s"}]}, "properties" : ["imdbnumber", "originaltitle", "year"]}, "id": 1}' % (year, str(int(year) + 1), str(int(year) - 1)) ) lib = unicode(lib, "utf-8", errors="ignore") lib = json.loads(lib)["result"]["movies"] lib = [ i for i in lib if str(i["imdbnumber"]) in id or (i["originaltitle"].encode("utf-8") == title and str(i["year"]) == year) ][0] except: lib = [] try: if not lib == []: raise Exception() self.strmFile({"name": name, "title": title, "year": year, "imdb": imdb}) except: pass if range == True: return control.infoDialog(control.lang(30423).encode("utf-8"), time=1) if self.library_setting == "true" and not control.condVisibility("Library.IsScanningVideo"): control.execute("UpdateLibrary(video)")
def play(self, title, year, imdb, tvdb, season, episode, tvshowtitle, premiered, meta, select): try: sysloc = [urlparse.urlparse(sys.argv[0]).netloc, '', 'plugin.video.live.streamspro', 'plugin.video.tinklepad'] sysplg = True if control.infoLabel('Container.PluginName') in sysloc else False syslib = False #True if '.strm' in str(control.infoLabel('ListItem.FileName')) else False items = self.getSources(title, year, imdb, tvdb, season, episode, tvshowtitle, premiered) select = control.setting('hosts.mode') if select == None else select title = tvshowtitle if not tvshowtitle == None else title url = None if syslib == True or sysplg == False: items = [] if control.window.getProperty('PseudoTVRunning') == 'True': return control.resolve(int(sys.argv[1]), True, control.item(path=str(self.sourcesDirect(items)))) if len(items) > 0: if select == '1' and 'plugin' in control.infoLabel('Container.PluginName'): control.window.clearProperty(self.itemProperty) control.window.setProperty(self.itemProperty, json.dumps(items)) control.window.clearProperty(self.metaProperty) control.window.setProperty(self.metaProperty, meta) control.sleep(200) return control.execute('Container.Update(%s?action=addItem&title=%s)' % (sys.argv[0], urllib.quote_plus(title.encode('utf-8')))) elif select == '0' or select == '1': url = self.sourcesDialog(items) else: url = self.sourcesDirect(items) if url == None: return self.errorForSources() meta = json.loads(meta) from resources.lib.modules.player import player player().run(title, year, season, episode, imdb, tvdb, url, meta) except: pass
def play(self, title, year, imdb, tmdb, tvdb, season, episode, tvshowtitle, premiered, meta, url): try: if not control.addonInfo('id').lower() == control.infoLabel('Container.PluginName').lower(): progress = True if control.setting('progress.dialog') == '1' else False else: control.resolve(int(sys.argv[1]), True, control.item(path='')) control.execute('Dialog.Close(okdialog)') progress = True if 'super.fav' in control.infoLabel('Container.PluginName'): return control.dialog.ok('Exodus', control.lang(30518).encode('utf-8'), '', '') self.sources = self.getSources(title, year, imdb, tmdb, tvdb, season, episode, tvshowtitle, premiered, progress=progress) self.sources = self.sourcesFilter() if control.window.getProperty('PseudoTVRunning') == 'True': return control.resolve(int(sys.argv[1]), True, control.item(path=str(self.sourcesDirect(progress=progress)))) if self.sources == []: raise Exception() if url == 'direct://': url = self.sourcesDirect(progress=progress) elif url == 'dialog://': url = self.sourcesDialog(progress=progress) elif control.setting('autoplay') == 'false': url = self.sourcesDialog(progress=progress) else: url = self.sourcesDirect(progress=progress) if url == None: raise Exception() if url == 'close://': return control.sleep(200) if not tvshowtitle == None: title = tvshowtitle from resources.lib.modules.player import player player().run(title, year, season, episode, imdb, tmdb, tvdb, meta, url) return url except: control.infoDialog(control.lang(30501).encode('utf-8'))
def add(self, name, title, year, imdb, tmdb, range=False): if not control.condVisibility('Window.IsVisible(infodialog)') and not control.condVisibility('Player.HasVideo')\ and self.silentDialog is False: control.infoDialog(control.lang(32552).encode('utf-8'), time=10000000) self.infoDialog = True try: if not self.dupe_setting == 'true': raise Exception() id = [imdb, tmdb] if not tmdb == '0' else [imdb] lib = control.jsonrpc('{"jsonrpc": "2.0", "method": "VideoLibrary.GetMovies", "params": {"filter":{"or": [{"field": "year", "operator": "is", "value": "%s"}, {"field": "year", "operator": "is", "value": "%s"}, {"field": "year", "operator": "is", "value": "%s"}]}, "properties" : ["imdbnumber", "originaltitle", "year"]}, "id": 1}' % (year, str(int(year)+1), str(int(year)-1))) lib = unicode(lib, 'utf-8', errors='ignore') lib = json.loads(lib)['result']['movies'] lib = [i for i in lib if str(i['imdbnumber']) in id or (i['originaltitle'].encode('utf-8') == title and str(i['year']) == year)][0] except: lib = [] files_added = 0 try: if not lib == []: raise Exception() if self.check_setting == 'true': src = lib_tools.check_sources(title, year, imdb, None, None, None, None, None) if not src: raise Exception() self.strmFile({'name': name, 'title': title, 'year': year, 'imdb': imdb, 'tmdb': tmdb}) files_added += 1 except: pass if range == True: return if self.infoDialog == True: control.infoDialog(control.lang(32554).encode('utf-8'), time=1) if self.library_setting == 'true' and not control.condVisibility('Library.IsScanningVideo') and files_added > 0: control.execute('UpdateLibrary(video)')
def play(self, title, year, imdb, tvdb, season, episode, tvshowtitle, premiered, meta, select): try: url = None control.moderator() items = self.getSources(title, year, imdb, tvdb, season, episode, tvshowtitle, premiered) select = control.setting('hosts.mode') if select == None else select title = tvshowtitle if not tvshowtitle == None else title if control.window.getProperty('PseudoTVRunning') == 'True': return control.resolve(int(sys.argv[1]), True, control.item(path=str(self.sourcesDirect(items)))) if len(items) > 0: if select == '1' and 'plugin' in control.infoLabel('Container.PluginName'): control.window.clearProperty(self.itemProperty) control.window.setProperty(self.itemProperty, json.dumps(items)) control.window.clearProperty(self.metaProperty) control.window.setProperty(self.metaProperty, meta) control.sleep(200) return control.execute('Container.Update(%s?action=addItem&title=%s)' % (sys.argv[0], urllib.quote_plus(title))) elif select == '0' or select == '1': url = self.sourcesDialog(items) else: url = self.sourcesDirect(items) if url == None: return self.errorForSources() try: meta = json.loads(meta) except: pass from resources.lib.modules.player import player player().run(title, year, season, episode, imdb, tvdb, url, meta) except: pass
def syncTraktWatched(): control.execute('RunPlugin(plugin://%s)' % 'plugin.video.venom/?action=cachesyncTVShows') control.execute('RunPlugin(plugin://%s)' % 'plugin.video.venom/?action=cachesyncMovies')
def update(self, query=None, info='true'): if not query == None: control.idle() try: items = [] season, episode = [], [] show = [ os.path.join(self.library_folder, i) for i in control.listDir(self.library_folder)[0] ] for s in show: try: season += [ os.path.join(s, i) for i in control.listDir(s)[0] ] except: pass for s in season: try: episode.append([ os.path.join(s, i) for i in control.listDir(s)[1] if i.endswith('.strm') ][-1]) except: pass for file in episode: try: file = control.openFile(file) read = file.read() read = read.encode('utf-8') file.close() if not read.startswith(sys.argv[0]): raise Exception() params = dict(urlparse.parse_qsl(read.replace('?', ''))) try: tvshowtitle = params['tvshowtitle'] except: tvshowtitle = None try: tvshowtitle = params['show'] except: pass if tvshowtitle == None or tvshowtitle == '': raise Exception() year, imdb, tvdb = params['year'], params['imdb'], params[ 'tvdb'] imdb = 'tt' + re.sub('[^0-9]', '', str(imdb)) try: tmdb = params['tmdb'] except: tmdb = '0' items.append({ 'tvshowtitle': tvshowtitle, 'year': year, 'imdb': imdb, 'tmdb': tmdb, 'tvdb': tvdb }) except: pass items = [i for x, i in enumerate(items) if i not in items[x + 1:]] if len(items) == 0: raise Exception() except: return try: lib = control.jsonrpc( '{"jsonrpc": "2.0", "method": "VideoLibrary.GetTVShows", "params": {"properties" : ["imdbnumber", "title", "year"]}, "id": 1}' ) lib = unicode(lib, 'utf-8', errors='ignore') lib = json.loads(lib)['result']['tvshows'] except: return if info == 'true' and not control.condVisibility( 'Window.IsVisible(infodialog)') and not control.condVisibility( 'Player.HasVideo'): control.infoDialog(control.lang(32553).encode('utf-8'), time=10000000) self.infoDialog = True try: control.makeFile(control.dataPath) dbcon = database.connect(control.libcacheFile) dbcur = dbcon.cursor() dbcur.execute("CREATE TABLE IF NOT EXISTS tvshows (" "id TEXT, " "items TEXT, " "UNIQUE(id)" ");") except: return try: from resources.lib.indexers import episodes except: return files_added = 0 # __init__ doesn't get called from services so self.date never gets updated and new episodes are not added to the library self.datetime = (datetime.datetime.utcnow() - datetime.timedelta(hours=5)) if control.setting('library.importdelay') != 'true': self.date = self.datetime.strftime('%Y%m%d') else: self.date = (self.datetime - datetime.timedelta(hours=24)).strftime('%Y%m%d') for item in items: it = None if xbmc.abortRequested == True: return sys.exit() try: dbcur.execute("SELECT * FROM tvshows WHERE id = '%s'" % item['tvdb']) fetch = dbcur.fetchone() it = eval(fetch[1].encode('utf-8')) except: pass try: if not it == None: raise Exception() it = episodes.episodes().get(item['tvshowtitle'], item['year'], item['imdb'], item['tvdb'], idx=False) status = it[0]['status'].lower() it = [{ 'title': i['title'], 'year': i['year'], 'imdb': i['imdb'], 'tvdb': i['tvdb'], 'season': i['season'], 'episode': i['episode'], 'tvshowtitle': i['tvshowtitle'], 'premiered': i['premiered'] } for i in it] if status == 'continuing': raise Exception() dbcur.execute("INSERT INTO tvshows Values (?, ?)", (item['tvdb'], repr(it))) dbcon.commit() except: pass try: id = [item['imdb'], item['tvdb']] if not item['tmdb'] == '0': id += [item['tmdb']] ep = [ x['title'].encode('utf-8') for x in lib if str(x['imdbnumber']) in id or ( x['title'].encode('utf-8') == item['tvshowtitle'] and str(x['year']) == item['year']) ][0] ep = control.jsonrpc( '{"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodes", "params": {"filter":{"and": [{"field": "tvshow", "operator": "is", "value": "%s"}]}, "properties": ["season", "episode"]}, "id": 1}' % ep) ep = unicode(ep, 'utf-8', errors='ignore') ep = json.loads(ep).get('result', {}).get('episodes', {}) ep = [{ 'season': int(i['season']), 'episode': int(i['episode']) } for i in ep] ep = sorted(ep, key=lambda x: (x['season'], x['episode']))[-1] num = [ x for x, y in enumerate(it) if str(y['season']) == str(ep['season']) and str(y['episode']) == str(ep['episode']) ][-1] it = [y for x, y in enumerate(it) if x > num] if len(it) == 0: continue except: continue for i in it: try: if xbmc.abortRequested == True: return sys.exit() premiered = i.get('premiered', '0') if (premiered != '0' and int(re.sub('[^0-9]', '', str(premiered))) > int(self.date)) or (premiered == '0' and not self.include_unknown): continue libtvshows().strmFile(i) files_added += 1 except: pass if self.infoDialog == True: control.infoDialog(control.lang(32554).encode('utf-8'), time=1) if self.library_setting == 'true' and not control.condVisibility( 'Library.IsScanningVideo') and files_added > 0: control.execute('UpdateLibrary(video)')
def playItem(self, title, source): try: meta = control.window.getProperty(self.metaProperty) meta = json.loads(meta) year = meta['year'] if 'year' in meta else None season = meta['season'] if 'season' in meta else None episode = meta['episode'] if 'episode' in meta else None imdb = meta['imdb'] if 'imdb' in meta else None tvdb = meta['tvdb'] if 'tvdb' in meta else None next = [] prev = [] total = [] for i in range(1, 1000): try: u = control.infoLabel('ListItem(%s).FolderPath' % str(i)) if u in total: raise Exception() total.append(u) u = dict(urlparse.parse_qsl(u.replace('?', ''))) u = json.loads(u['source'])[0] next.append(u) except: break for i in range(-1000, 0)[::-1]: try: u = control.infoLabel('ListItem(%s).FolderPath' % str(i)) if u in total: raise Exception() total.append(u) u = dict(urlparse.parse_qsl(u.replace('?', ''))) u = json.loads(u['source'])[0] prev.append(u) except: break items = json.loads(source) items = [i for i in items + next + prev][:40] header = control.addonInfo('name') header2 = header.upper() progressDialog = control.progressDialog if control.setting( 'progress.dialog') == '0' else control.progressDialogBG progressDialog.create(header, '') progressDialog.update(0) block = None for i in range(len(items)): try: try: if progressDialog.iscanceled(): break progressDialog.update( int((100 / float(len(items))) * i), str(items[i]['label']), str(' ')) except: progressDialog.update( int((100 / float(len(items))) * i), str(header2), str(items[i]['label'])) if items[i]['source'] == block: raise Exception() w = workers.Thread(self.sourcesResolve, items[i]) w.start() offset = 60 * 2 if items[i].get( 'source') in self.hostcapDict else 0 m = '' for x in range(3600): try: if xbmc.abortRequested == True: return sys.exit() if progressDialog.iscanceled(): return progressDialog.close() except: pass k = control.condVisibility( 'Window.IsActive(virtualkeyboard)') if k: m += '1' m = m[-1] if (w.is_alive() == False or x > 30 + offset) and not k: break k = control.condVisibility( 'Window.IsActive(yesnoDialog)') if k: m += '1' m = m[-1] if (w.is_alive() == False or x > 30 + offset) and not k: break time.sleep(0.5) for x in range(30): try: if xbmc.abortRequested == True: return sys.exit() if progressDialog.iscanceled(): return progressDialog.close() except: pass if m == '': break if w.is_alive() == False: break time.sleep(0.5) if w.is_alive() == True: block = items[i]['source'] if self.url == None: raise Exception() try: progressDialog.close() except: pass control.sleep(200) control.execute('Dialog.Close(virtualkeyboard)') control.execute('Dialog.Close(yesnoDialog)') from resources.lib.modules.player import player player().run(title, year, season, episode, imdb, tvdb, self.url, meta) return self.url except: pass try: progressDialog.close() except: pass self.errorForSources() except: pass
'name': item['name'], 'image': item['poster'] }) except: pass for item_url in item_urls: retrying = False playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO) if playlist.size() > 0 and control.setting( "background_list_queue") == "true" and len(item_urls) > 1: hide_progress = True else: hide_progress = False while True: if not hide_progress: control.execute('ActivateWindow(busydialog)') if retrying: resolved = Resolver().process(Resolver().get(item_url['url']), name=item_url['name'], hide_progress=hide_progress, queueing=True) else: link = Resolver().get(item_url['url'], link=selected_link) resolved = Resolver().process(link, name=item_url['name'], hide_progress=hide_progress, queueing=True) if not hide_progress: control.execute('Dialog.Close(busydialog)') if resolved: if playlist.size() == 0 and len(item_urls) > 1: play_now = True
def search_new(self): control.hide() t = control.lang(32010) k = control.keyboard('', t) k.doModal() q = k.getText() if k.isConfirmed() else None if (q is None or q == ''): return try: from sqlite3 import dbapi2 as database except: from pysqlite2 import dbapi2 as database dbcon = database.connect(control.searchFile) dbcur = dbcon.cursor() dbcur.execute("INSERT INTO furk VALUES (?,?)", (None,q)) dbcon.commit() dbcur.close() url = quote_plus(q) url = '%s?action=furkMetaSearch&url=%s' % (sys.argv[0], quote_plus(url)) control.execute('Container.Update(%s)' % url) def furk_meta_search(self, url): if self.api_key == '': return '' try: s = requests.Session() url = (self.base_link + self.meta_search_link % (self.api_key, url)).replace(' ', '+') p = s.get(url) p = json.loads(p.text) files = p['files'] for i in files: name = i['name'] id = i['id'] url_dl = '' for x in accepted_extensions: if 'url_dl' in i: if i['url_dl'].endswith(x): url_dl = i['url_dl'] else: continue else: continue if url_dl == '': continue if int(i['files_num_video_player']) !> 1: if int(i['ss_num']) > 0: thumb = i['ss_urls'][0] else: thumb = '' self.addDirectoryItem(name, url_dl, thumb, '', False) else: # print(i['name']) # self.addDirectoryItem(i['name'].encode('utf-8'), i['url_dl'], '', '') continue self.endDirectory() return '' except:
def playItem(self, source): try: f = dict(urlparse.parse_qsl(control.infoLabel('Container.FolderPath').replace('?',''))) meta = f['meta'] if 'meta' in f else None title = f['title'] if 'title' in f else None title = f['tvshowtitle'] if 'tvshowtitle' in f else title year = f['year'] if 'year' in f else None season = f['season'] if 'season' in f else None episode = f['episode'] if 'episode' in f else None imdb = f['imdb'] if 'imdb' in f else None tvdb = f['tvdb'] if 'tvdb' in f else None next = [] ; prev = [] ; total = [] for i in range(1,1000): try: u = control.infoLabel('ListItem(%s).FolderPath' % str(i)) if u in total: raise Exception() total.append(u) u = dict(urlparse.parse_qsl(u.replace('?',''))) u = json.loads(u['source'])[0] next.append(u) except: break for i in range(-1000,0)[::-1]: try: u = control.infoLabel('ListItem(%s).FolderPath' % str(i)) if u in total: raise Exception() total.append(u) u = dict(urlparse.parse_qsl(u.replace('?',''))) u = json.loads(u['source'])[0] prev.append(u) except: break items = json.loads(source) items = [i for i in items+next+prev][:20] self.progressDialog = control.progressDialog self.progressDialog.create(control.addonInfo('name'), '') self.progressDialog.update(0) block = None for i in range(len(items)): try: self.progressDialog.update(int((100 / float(len(items))) * i), str(items[i]['label']), str(' ')) if items[i]['source'] == block: raise Exception() w = workers.Thread(self.sourcesResolve, items[i]) w.start() m = '' for x in range(3600): if self.progressDialog.iscanceled(): return self.progressDialog.close() if xbmc.abortRequested == True: return sys.exit() k = control.condVisibility('Window.IsActive(virtualkeyboard)') if k: m += '1'; m = m[-1] if (w.is_alive() == False or x > 30) and not k: break k = control.condVisibility('Window.IsActive(yesnoDialog)') if k: m += '1'; m = m[-1] if (w.is_alive() == False or x > 30) and not k: break time.sleep(0.5) for x in range(30): if m == '': break if self.progressDialog.iscanceled(): return self.progressDialog.close() if xbmc.abortRequested == True: return sys.exit() if w.is_alive() == False: break time.sleep(0.5) if w.is_alive() == True: block = items[i]['source'] if self.url == None: raise Exception() try: self.progressDialog.close() except: pass control.sleep(200) control.execute('Dialog.Close(virtualkeyboard)') control.execute('Dialog.Close(yesnoDialog)') from resources.lib.modules.player import player player().run(title, year, season, episode, imdb, tvdb, meta, self.url) return self.url except: pass try: self.progressDialog.close() except: pass raise Exception() except: control.infoDialog(control.lang(30501).encode('utf-8')) pass
def update(self, query=None, info='true'): if not query == None: control.idle() try: items = [] season, episode = [], [] show = [os.path.join(self.library_folder, i) for i in control.listDir(self.library_folder)[0]] for s in show: try: season += [os.path.join(s, i) for i in control.listDir(s)[0]] except: pass for s in season: try: episode.append([os.path.join(s, i) for i in control.listDir(s)[1] if i.endswith('.strm')][-1]) except: pass for file in episode: try: file = control.openFile(file) read = file.read() read = read.encode('utf-8') file.close() if not read.startswith(sys.argv[0]): raise Exception() params = dict(urlparse.parse_qsl(read.replace('?',''))) try: tvshowtitle = params['tvshowtitle'] except: tvshowtitle = None try: tvshowtitle = params['show'] except: pass if tvshowtitle == None or tvshowtitle == '': raise Exception() year, imdb, tvdb = params['year'], params['imdb'], params['tvdb'] imdb = 'tt' + re.sub('[^0-9]', '', str(imdb)) try: tmdb = params['tmdb'] except: tmdb = '0' try: tvrage = params['tvrage'] except: tvrage = '0' items.append({'tvshowtitle': tvshowtitle, 'year': year, 'imdb': imdb, 'tmdb': tmdb, 'tvdb': tvdb, 'tvrage': tvrage}) except: pass items = [i for x, i in enumerate(items) if i not in items[x + 1:]] if len(items) == 0: raise Exception() except: return try: lib = control.jsonrpc('{"jsonrpc": "2.0", "method": "VideoLibrary.GetTVShows", "params": {"properties" : ["imdbnumber", "title", "year"]}, "id": 1}') lib = unicode(lib, 'utf-8', errors='ignore') lib = json.loads(lib)['result']['tvshows'] except: return if info == 'true' and not control.condVisibility('Window.IsVisible(infodialog)') and not control.condVisibility('Player.HasVideo'): control.infoDialog(control.lang(30422).encode('utf-8'), time=10000000) self.infoDialog = True try: control.makeFile(control.dataPath) dbcon = database.connect(control.libcacheFile) dbcur = dbcon.cursor() dbcur.execute("CREATE TABLE IF NOT EXISTS tvshows (""id TEXT, ""items TEXT, ""UNIQUE(id)"");") except: return try: from resources.lib.indexers import episodes except: return for item in items: it = None if xbmc.abortRequested == True: return sys.exit() try: dbcur.execute("SELECT * FROM tvshows WHERE id = '%s'" % item['tvdb']) fetch = dbcur.fetchone() it = eval(fetch[1].encode('utf-8')) except: pass try: if not it == None: raise Exception() it = episodes.episodes().get(item['tvshowtitle'], item['year'], item['imdb'], item['tmdb'], item['tvdb'], item['tvrage'], idx=False) status = it[0]['status'].lower() it = [{'name': i['name'], 'title': i['title'], 'year': i['year'], 'imdb': i['imdb'], 'tmdb': i['tmdb'], 'tvdb': i['tvdb'], 'tvrage': i['tvrage'], 'season': i['season'], 'episode': i['episode'], 'tvshowtitle': i['tvshowtitle'], 'alter': i['alter'], 'date': i['premiered']} for i in it] if status == 'continuing': raise Exception() dbcur.execute("INSERT INTO tvshows Values (?, ?)", (item['tvdb'], repr(it))) dbcon.commit() except: pass try: id = [item['imdb'], item['tvdb']] if not item['tmdb'] == '0': id += [item['tmdb']] ep = [x['title'].encode('utf-8') for x in lib if str(x['imdbnumber']) in id or (x['title'].encode('utf-8') == item['tvshowtitle'] and str(x['year']) == item['year'])][0] ep = control.jsonrpc('{"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodes", "params": {"filter":{"and": [{"field": "tvshow", "operator": "is", "value": "%s"}]}, "properties": ["season", "episode"]}, "id": 1}' % ep) ep = unicode(ep, 'utf-8', errors='ignore') ep = json.loads(ep)['result']['episodes'][-1] num = [x for x,y in enumerate(it) if str(y['season']) == str(ep['season']) and str(y['episode']) == str(ep['episode'])][-1] it = [y for x,y in enumerate(it) if x > num] if len(it) == 0: continue except: continue for i in it: try: if xbmc.abortRequested == True: return sys.exit() if int(self.date) <= int(re.sub('[^0-9]', '', str(i['date']))): from resources.lib.sources import sources src = sources().checkSources(i['name'], i['title'], i['year'], i['imdb'], i['tmdb'], i['tvdb'], i['tvrage'], i['season'], i['episode'], i['tvshowtitle'], i['alter'], i['date']) control.log('### SOURCES SRC 10 %s | %s' % (src,i['name'])) if src == False: raise Exception() libtvshows().strmFile(i) except: pass if self.infoDialog == True: control.infoDialog(control.lang(30423).encode('utf-8'), time=1) if self.library_setting == 'true' and not control.condVisibility('Library.IsScanningVideo'): control.execute('UpdateLibrary(video)')
# -*- coding: utf-8 -*- from resources.lib.modules import control control.setSetting(id='first.start', value='true') # FORCE NEW CACHE control.execute('RunPlugin(plugin://plugin.video.realizer/?action=service)') class Service(): def __init__(self, *args): addonName = 'Premiumize Transfers' def ServiceEntryPoint(self): monitor = xbmc.Monitor() updateTime = control.setting('rss.timeout') updateSeconds = int(updateTime) * 3600 while not monitor.abortRequested(): if monitor.waitForAbort(updateSeconds): # # Abort was requested while waiting. We should exit break if control.setting('rss.1') == 'true' or control.setting( 'rss.2') == 'true' or control.setting( 'rss.3') == 'true' or control.setting( 'rss.4') == 'true': control.execute( 'RunPlugin(plugin://plugin.video.realizer/?action=rss_update)' ) Service().ServiceEntryPoint()
def getSources(self, title, year, imdb, tvdb, season, episode, tvshowtitle, premiered, quality='HD', timeout=30): progressDialog = control.progressDialog if control.setting('progress.dialog') == '0' else control.progressDialogBG progressDialog.create(control.addonInfo('name'), '') progressDialog.update(0) self.prepareSources() sourceDict = self.sourceDict progressDialog.update(0, control.lang(32588).encode('utf-8')) content = 'movie' if tvshowtitle == None else 'episode' if content == 'movie': sourceDict = [(i[0], i[1], getattr(i[1], 'movie', None)) for i in sourceDict] genres = trakt.getGenre('movie', 'imdb', imdb) else: sourceDict = [(i[0], i[1], getattr(i[1], 'tvshow', None)) for i in sourceDict] genres = trakt.getGenre('show', 'tvdb', tvdb) progressDialog.update(0, control.lang(32589).encode('utf-8')) sourceDict = [(i[0], i[1], i[2]) for i in sourceDict if not hasattr(i[1], 'genre_filter') or not i[1].genre_filter or any(x in i[1].genre_filter for x in genres)] sourceDict = [(i[0], i[1]) for i in sourceDict if not i[2] == None] language = self.getLanguage() sourceDict = [(i[0], i[1], i[1].language) for i in sourceDict] sourceDict = [(i[0], i[1]) for i in sourceDict if any(x in i[2] for x in language)] try: sourceDict = [(i[0], i[1], control.setting('provider.' + i[0])) for i in sourceDict] except: sourceDict = [(i[0], i[1], 'true') for i in sourceDict] sourceDict = [(i[0], i[1]) for i in sourceDict if not i[2] == 'false'] sourceDict = [(i[0], i[1], i[1].priority) for i in sourceDict] threads = [] if content == 'movie': title = self.getTitle(title) localtitle = self.getLocalTitle(title, imdb, tvdb, content) aliases = self.getAliasTitles(imdb, localtitle, content) for i in sourceDict: threads.append(workers.Thread(self.getMovieSource, title, localtitle, aliases, year, imdb, i[0], i[1])) else: tvshowtitle = self.getTitle(tvshowtitle) localtvshowtitle = self.getLocalTitle(tvshowtitle, imdb, tvdb, content) aliases = self.getAliasTitles(imdb, localtvshowtitle, content) season, episode = thexem.get_scene_episode_number(tvdb, season, episode) for i in sourceDict: threads.append(workers.Thread(self.getEpisodeSource, title, year, imdb, tvdb, season, episode, tvshowtitle, localtvshowtitle, aliases, premiered, i[0], i[1])) s = [i[0] + (i[1],) for i in zip(sourceDict, threads)] s = [(i[3].getName(), i[0], i[2]) for i in s] mainsourceDict = [i[0] for i in s if i[2] == 0] sourcelabelDict = dict([(i[0], i[1].upper()) for i in s]) [i.start() for i in threads] string1 = control.lang(32404).encode('utf-8') string2 = control.lang(32405).encode('utf-8') string3 = control.lang(32406).encode('utf-8') try: timeout = int(control.setting('scrapers.timeout.1')) except: pass for i in range(0, (timeout * 2) + 60): try: if xbmc.abortRequested == True: return sys.exit() try: info = [sourcelabelDict[x.getName()] for x in threads if x.is_alive() == True] except: info = [] timerange = int(i * 0.5) try: if progressDialog.iscanceled(): break except: pass try: string4 = string1 % str(timerange) if len(info) > 5: string5 = string3 % str(len(info)) else: string5 = string3 % str(info).translate(None, "[]'") progressDialog.update(int((100 / float(len(threads))) * len([x for x in threads if x.is_alive() == False])), str(string4), str(string5)) except: pass is_alive = [x.is_alive() for x in threads] if all(x == False for x in is_alive): break if timerange >= timeout: is_alive = [x for x in threads if x.is_alive() == True and x.getName() in mainsourceDict] if not is_alive: break time.sleep(0.5) except: pass if control.addonInfo('id') == 'plugin.video.bennu': try: if progressDialog: progressDialog.update(100, control.lang(30726).encode('utf-8'), control.lang(30731).encode('utf-8')) items = self.sourcesFilter() if quality == 'RD': items = [i for i in items if i['debrid'] != ''] elif quality == 'SD': items = [i for i in items if i['quality'] == 'SD' and i['debrid'] == ''] elif quality == 'HD': items = [i for i in items if i['quality'] != 'SD'] if control.setting('bennu.dev.log') == 'true': log_utils.log('Sources Returned: %s' % str(items), log_utils.LOGNOTICE) try: progressDialog.close() except: pass if quality == 'AUTO': u = self.sourcesDirect(items) return u else: meta = '{"title": "%s", "year": "%s", "imdb": "%s"}' % (title, year, imdb) '''control.window.clearProperty("plugin.video.bennu.container.items") control.window.setProperty("plugin.video.bennu.container.items", json.dumps(items)) control.window.clearProperty("plugin.video.bennu.container.meta") control.window.setProperty("plugin.video.bennu.container.meta", meta)''' control.window.clearProperty(self.itemProperty) control.window.setProperty(self.itemProperty, json.dumps(items)) control.window.clearProperty(self.metaProperty) control.window.setProperty(self.metaProperty, meta) control.sleep(200) control.execute('Container.Update(%s?action=addItem&title=%s)' % (sys.argv[0], urllib.quote_plus(title))) return "DIR" except: try: progressDialog.close() except: pass return else: try: progressDialog.close() except: pass self.sourcesFilter() return self.sources
def get(self, name, imdb, season, episode): try: if not control.setting('subtitles') == 'true': raise Exception() langDict = { 'Afrikaans': 'afr', 'Albanian': 'alb', 'Arabic': 'ara', 'Armenian': 'arm', 'Basque': 'baq', 'Bengali': 'ben', 'Bosnian': 'bos', 'Breton': 'bre', 'Bulgarian': 'bul', 'Burmese': 'bur', 'Catalan': 'cat', 'Chinese': 'chi', 'Croatian': 'hrv', 'Czech': 'cze', 'Danish': 'dan', 'Dutch': 'dut', 'English': 'eng', 'Esperanto': 'epo', 'Estonian': 'est', 'Finnish': 'fin', 'French': 'fre', 'Galician': 'glg', 'Georgian': 'geo', 'German': 'ger', 'Greek': 'ell', 'Hebrew': 'heb', 'Hindi': 'hin', 'Hungarian': 'hun', 'Icelandic': 'ice', 'Indonesian': 'ind', 'Italian': 'ita', 'Japanese': 'jpn', 'Kazakh': 'kaz', 'Khmer': 'khm', 'Korean': 'kor', 'Latvian': 'lav', 'Lithuanian': 'lit', 'Luxembourgish': 'ltz', 'Macedonian': 'mac', 'Malay': 'may', 'Malayalam': 'mal', 'Manipuri': 'mni', 'Mongolian': 'mon', 'Montenegrin': 'mne', 'Norwegian': 'nor', 'Occitan': 'oci', 'Persian': 'per', 'Polish': 'pol', 'Portuguese': 'por,pob', 'Portuguese(Brazil)': 'pob,por', 'Romanian': 'rum', 'Russian': 'rus', 'Serbian': 'scc', 'Sinhalese': 'sin', 'Slovak': 'slo', 'Slovenian': 'slv', 'Spanish': 'spa', 'Swahili': 'swa', 'Swedish': 'swe', 'Syriac': 'syr', 'Tagalog': 'tgl', 'Tamil': 'tam', 'Telugu': 'tel', 'Thai': 'tha', 'Turkish': 'tur', 'Ukrainian': 'ukr', 'Urdu': 'urd' } codePageDict = { 'ara': 'cp1256', 'ar': 'cp1256', 'ell': 'cp1253', 'el': 'cp1253', 'heb': 'cp1255', 'he': 'cp1255', 'tur': 'cp1254', 'tr': 'cp1254', 'rus': 'cp1251', 'ru': 'cp1251' } quality = [ 'bluray', 'hdrip', 'brrip', 'bdrip', 'dvdrip', 'webrip', 'hdtv' ] langs = [] try: try: langs = langDict[control.setting( 'subtitles.lang.1')].split(',') except: langs.append(langDict[control.setting('subtitles.lang.1')]) except: pass try: try: langs = langs + langDict[control.setting( 'subtitles.lang.2')].split(',') except: langs.append(langDict[control.setting('subtitles.lang.2')]) except: pass try: subLang = xbmc.Player().getSubtitles() except: subLang = '' if subLang == langs[0]: raise Exception() un = control.setting('os.user') pw = control.setting('os.pass') server = xmlrpc_client.Server( 'http://api.opensubtitles.org/xml-rpc', verbose=0) token = server.LogIn(un, pw, 'en', 'XBMC_Subtitles_Unofficial_v5.2.14')['token'] sublanguageid = ','.join(langs) imdbid = re.sub('[^0-9]', '', imdb) if not (season == None or episode == None): 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'] subname = str(filter[0]['SubFileName']) content = [ filter[0]['IDSubtitleFile'], ] content = server.DownloadSubtitles(token, content) content = base64.b64decode(content['data'][0]['data']) content = gzip.GzipFile(fileobj=six.BytesIO(content)).read() if six.PY3: content = six.ensure_text(content) subtitle = control.transPath('special://temp/') subtitle = os.path.join(subtitle, 'TemporarySubs.%s.srt' % lang) codepage = codePageDict.get(lang, '') if codepage and control.setting('subtitles.utf') == '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) if control.setting('subtitles.notify') == 'true': if xbmc.Player().isPlaying() and xbmc.Player().isPlayingVideo( ): control.execute('Dialog.Close(all,true)') xbmc.sleep(3000) control.infoDialog( subname, heading='{} subtitles downloaded'.format( str(lang).upper()), time=6000) except: pass
def get_movies(self, tmdb, status): try: if not tmdb or tmdb == '0': return control.infoDialog('No ID found') sysaddon = sys.argv[0] cache_dur = 720 if status in ['Released', 'Canceled'] else 96 url = self.tmdb_movie_credits % tmdb r = cache.get(client.request, cache_dur, url) r = utils.json_loads_as_str(r) crew = r['crew'] crew_cast = [d for d in crew if d['job'] == 'Director'] crew_cast += r['cast'][:50] ids = [str(i['id']) for i in crew_cast] names = [ ' '.join((i['name'], i.get('job', ''))) for i in crew_cast ] items = [] for person in crew_cast: role = person[ 'character'] if 'character' in person else person['job'] name = '%s [I](as %s)[/I]' % (person['name'], role) if role else person['name'] name = name.replace('as Director', 'Director') if control.getKodiVersion() >= 17: icon = self.tm_img_link % person['profile_path'] if person[ 'profile_path'] else self.fallback_img item = control.item(label=name) item.setArt({'icon': icon, 'thumb': icon, 'poster': icon}) items.append(item) else: items.append(name) select = control.selectDialog(items, heading='Actors / Director(s):', useDetails=True) if select == -1: return c_id = ids[select] c_name = names[select] if 'Director' in c_name: choose = control.selectDialog( ['Movies credited in', 'Biography'], heading=c_name.replace(' Director', '')) if choose == -1: return elif choose == 0: control.execute( 'Container.Update(%s?action=movies&url=%s)' % (sysaddon, urllib_parse.quote_plus( self.tmdb_moviedirector_link % c_id))) elif choose == 1: self.bio_txt(c_id) else: choose = control.selectDialog([ 'Movies appeared in', 'TV Shows appeared in', 'Biography' ], heading=c_name) if choose == -1: return elif choose == 0: control.execute( 'Container.Update(%s?action=movies&url=%s)' % (sysaddon, urllib_parse.quote_plus( self.tmdb_moviepeople_link % c_id))) elif choose == 1: control.execute( 'Container.Update(%s?action=tvshows&url=%s)' % (sysaddon, urllib_parse.quote_plus( self.tmdb_tvpeople_link % c_id))) elif choose == 2: self.bio_txt(c_id) except: log_utils.log('get_movies credits', 1) return
elif mode[0] == 'play_playlist': url = args['url'][0] title = args['title'][0] img = args['img'][0] if url.endswith('.ts'): import liveresolver resolved = liveresolver.resolve(url,cache_timeout=0,title=title) else: resolved = url li = xbmcgui.ListItem(title, path=resolved) li.setThumbnailImage(img) li.setLabel(title) li.setProperty('IsPlayable', 'true') if resolved.startswith('plugin'): control.execute("RunPlugin(%s)"%resolved) else: xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, li) ################################################################################################################################## ################################################################################################################################## elif mode[0]=='reddit': from resources.lib.modules import subreddits items = subreddits.get_subreddits() for item in items: delete = addon.build_plugin_url({'mode':'delete_subreddit','reddit':item}) context = [('Remove subreddit','RunPlugin(%s)'%delete)]
def search_term(self, name): control.idle() url = self.search_link + urllib.quote_plus(name) url = '%s?action=moviePage&url=%s' % (sys.argv[0], urllib.quote_plus(url)) control.execute('Container.Update(%s)' % url)
def onAVStarted(self): xbmc.sleep(1000) control.execute('Dialog.Close(all,true)') if not self.offset == '0': self.seekTime(float(self.offset)) subtitles().get(self.name, self.imdb, self.season, self.episode) self.idleForPlayback()
try: control.infoDialog(rlist[rand]['title'], control.lang(32536).encode('utf-8'), time=30000) except: pass elif rtype == "episode": try: control.infoDialog(rlist[rand]['tvshowtitle'] + " - Season " + rlist[rand]['season'] + " - " + rlist[rand]['title'], control.lang(32536).encode('utf-8'), time=30000) except: pass control.execute('RunPlugin(%s)' % r) except: control.infoDialog(control.lang(32537).encode('utf-8'), time=8000) elif action == 'movieToLibrary': from resources.lib.modules import libtools libtools.libmovies().add(name, title, year, imdb, tmdb) elif action == 'moviesToLibrary': from resources.lib.modules import libtools libtools.libmovies().range(url) elif action == 'moviesToLibrarySilent': from resources.lib.modules import libtools libtools.libmovies().silent(url)
def sourcesDialog(self, items, progress=True): try: sources = [{'label': '00 | [B]%s[/B]' % control.lang(30509).encode('utf-8').upper()}] + items labels = [i['label'] for i in sources] select = control.selectDialog(labels) if select == 0: return self.sourcesDirect(items, progress=progress) if select == -1: return 'close://' next = [y for x,y in enumerate(items) if x >= select] prev = [y for x,y in enumerate(items) if x < select][::-1] items = [items[select-1]] items = [i for i in items+next+prev][:20] if progress == True: self.progressDialog = control.progressDialog self.progressDialog.create(control.addonInfo('name'), '') self.progressDialog.update(0) block = None for i in range(len(items)): try: if progress == True: if self.progressDialog.iscanceled(): break self.progressDialog.update(int((100 / float(len(items))) * i), str(items[i]['label']), str(' ')) if items[i]['source'] == block: raise Exception() w = workers.Thread(self.sourcesResolve, items[i]) w.start() m = '' for x in range(3600): if progress == True: if self.progressDialog.iscanceled(): return self.progressDialog.close() if xbmc.abortRequested == True: return sys.exit() k = control.condVisibility('Window.IsActive(virtualkeyboard)') if k: m += '1'; m = m[-1] if (w.is_alive() == False or x > 30) and not k: break k = control.condVisibility('Window.IsActive(yesnoDialog)') if k: m += '1'; m = m[-1] if (w.is_alive() == False or x > 30) and not k: break time.sleep(0.5) for x in range(30): if m == '': break if progress == True: if self.progressDialog.iscanceled(): return self.progressDialog.close() if xbmc.abortRequested == True: return sys.exit() if w.is_alive() == False: break time.sleep(0.5) if w.is_alive() == True: block = items[i]['source'] if self.url == None: raise Exception() self.selectedSource = items[i]['label'] try: self.progressDialog.close() except: pass control.execute('Dialog.Close(virtualkeyboard)') control.execute('Dialog.Close(yesnoDialog)') return self.url except: pass try: self.progressDialog.close() except: pass except: try: self.progressDialog.close() except: pass
def onPlayBackStarted(self): control.execute('Dialog.Close(all,true)') control.setSetting("anime.lastvisited", str(self.anime_id)) pass
def update(self): if control.setting('library.service.update') == 'false': control.notification(message=32106) contains = lib_tools().ckKodiSources() if not contains: control.notification(message=32107) return try: items, season, episode = [], [], [] show = [control.joinPath(self.library_folder, i) for i in control.listDir(self.library_folder)[0]] if show == []: control.notification(message=32108) return for s in show: try: season += [control.joinPath(s, i) for i in control.listDir(s)[0]] except: pass for s in season: try: episode.append([control.joinPath(s, i) for i in control.listDir(s)[1] if i.endswith('.strm')][-1]) except: pass for file in episode: try: file = control.openFile(file) read = file.read() read = read.encode('utf-8') file.close() if not read.startswith(sys.argv[0]): continue params = dict(parse_qsl(read.replace('?',''))) try: tvshowtitle = params['tvshowtitle'] except: tvshowtitle = None try: tvshowtitle = params['show'] except: pass if tvshowtitle is None or tvshowtitle == '': continue year, imdb, tvdb = params['year'], params['imdb'], params['tvdb'] imdb = 'tt' + re.sub(r'[^0-9]', '', str(imdb)) tmdb = params.get('tmdb', '0') items.append({'tvshowtitle': tvshowtitle, 'year': year, 'imdb': imdb, 'tmdb': tmdb, 'tvdb': tvdb}) except: pass items = [i for x, i in enumerate(items) if i not in items[x + 1:]] if len(items) == 0: return except: log_utils.error() return try: lib = control.jsonrpc('{"jsonrpc": "2.0", "method": "VideoLibrary.GetTVShows", "params": {"properties": ["imdbnumber", "title", "year"]}, "id": 1 }') # lib = control.jsonrpc('{"jsonrpc": "2.0", "method": "VideoLibrary.GetTVShows", "params": {"filter":{"or": [{"field": "year", "operator": "is", "value": "%s"}, {"field": "year", "operator": "is", "value": "%s"}, {"field": "year", "operator": "is", "value": "%s"}]}, "properties": ["imdbnumber", "title", "year"]}, "id": 1}' % (year, str(int(year)+1), str(int(year)-1))) lib = unicode(lib, 'utf-8', errors='ignore') lib = loads(lib)['result']['tvshows'] except: log_utils.error() return if service_notification and not control.condVisibility('Window.IsVisible(infodialog)') and not control.condVisibility('Player.HasVideo'): control.notification(message=32553) try: control.makeFile(control.dataPath) dbcon = database.connect(control.libcacheFile) dbcur = dbcon.cursor() dbcur.execute('''CREATE TABLE IF NOT EXISTS tvshows (id TEXT, items TEXT, UNIQUE(id));''') dbcur.connection.commit() # from resources.lib.menus import episodes from resources.lib.menus import seasons except: log_utils.error() try: dbcur.close() ; dbcon.close() except: pass return files_added = 0 # __init__ doesn't get called from services so self.date never gets updated and new episodes are not added to the library # self.date_time = (datetime.utcnow() - timedelta(hours=5)) self.date_time = datetime.utcnow() if control.setting('library.importdelay') != 'true': self.date = self.date_time.strftime('%Y%m%d') else: self.date = (self.date_time - timedelta(hours=24)).strftime('%Y%m%d') for item in items: it = None if control.monitor.abortRequested(): try: dbcur.close() ; dbcon.close() except: pass return sys.exit() try: fetch = dbcur.execute("SELECT * FROM tvshows WHERE id = '%s'" % item['tvdb']).fetchone() if fetch: it = eval(fetch[1].encode('utf-8')) except: log_utils.error() try: if it: raise Exception() # it = episodes.Episodes().get(item['tvshowtitle'], item['year'], item['imdb'], item['tmdb'], item['tvdb'], idx=False) it = seasons.Seasons().tvdb_list(item['tvshowtitle'], item['year'], item['imdb'], item['tmdb'], item['tvdb'], control.apiLanguage()['tvdb'], '-1') # fetch fresh meta (uncached) if not it: continue status = it[0]['status'].lower() it = [{'title': i['title'], 'year': i['year'], 'imdb': i['imdb'], 'tmdb': i['tmdb'], 'tvdb': i['tvdb'], 'season': i['season'], 'episode': i['episode'], 'tvshowtitle': i['tvshowtitle'], 'premiered': i['premiered']} for i in it] if status == 'continuing': raise Exception() dbcur.execute("INSERT INTO tvshows Values (?, ?)", (item['tvdb'], repr(it))) dbcur.connection.commit() except: log_utils.error() try: id = [item['imdb'], item['tvdb']] if item['tmdb'] != '0': id += [item['tmdb']] ep = [x['title'].encode('utf-8') for x in lib if str(x['imdbnumber']) in id or (x['title'].encode('utf-8') == item['tvshowtitle'] and str(x['year']) == item['year'])][0] ep = control.jsonrpc('{"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodes", "params": {"filter":{"and": [{"field": "tvshow", "operator": "is", "value": "%s"}]}, "properties": ["season", "episode"]}, "id": 1}' % ep) ep = unicode(ep, 'utf-8', errors = 'ignore') ep = loads(ep).get('result', {}).get('episodes', {}) ep = [{'season': int(i['season']), 'episode': int(i['episode'])} for i in ep] ep = sorted(ep, key = lambda x: (x['season'], x['episode']))[-1] num = [x for x,y in enumerate(it) if str(y['season']) == str(ep['season']) and str(y['episode']) == str(ep['episode'])][-1] it = [y for x,y in enumerate(it) if x > num] if len(it) == 0: continue except: # log_utils.error() continue for i in it: if control.monitor.abortRequested(): return sys.exit() try: # Show Season Special(Season0). if str(i.get('season')) == '0' and control.setting('tv.specials') == 'false': continue # Show Unaired items. premiered = i.get('premiered', '0') if premiered == '0' and self.include_unknown == 'false': continue elif int(re.sub(r'[^0-9]', '', str(premiered))) > int(re.sub(r'[^0-9]', '', str(self.date))): if self.showunaired != 'true': continue libtvshows().strmFile(i) files_added += 1 if service_notification : control.notification(title=item['tvshowtitle'], message=32678) except: log_utils.error() try: dbcur.close() ; dbcon.close() except: pass if files_added == 0 and service_notification : control.notification(message=32109) if self.library_update == 'true' and not control.condVisibility('Library.IsScanningVideo') and files_added > 0: if contains: if service_notification: control.notification(message=32554) control.sleep(10000) control.execute('UpdateLibrary(video)') elif service_notification: control.notification(message=32103)
def onPlayBackStarted(self): control.execute('Dialog.Close(all,true)') if self.getbookmark is True and not self.offset == '0': self.seekTime(float(self.offset))
def reloadProfile(profile=None): if profile == None: control.execute('LoadProfile(Master user)') else: control.execute('LoadProfile(%s)' % profile)
def clean(): control.execute('CleanLibrary(video)')
def process(self, url, direct=True): try: if not any(i in url for i in ['.jpg', '.png', '.gif']): raise Exception() ext = url.split('?')[0].split('&')[0].split('|')[0].rsplit('.')[-1].replace('/', '').lower() if not ext in ['jpg', 'png', 'gif']: raise Exception() try: i = os.path.join(control.dataPath,'img') control.deleteFile(i) f = control.openFile(i, 'w') f.write(client.request(url)) f.close() control.execute('ShowPicture("%s")' % i) return False except: return except: pass try: r, x = re.findall('(.+?)\|regex=(.+?)$', url)[0] x = regex.fetch(x) r += urllib.unquote_plus(x) if not '</regex>' in r: raise Exception() u = regex.resolve(r) if not u == None: url = u except: pass try: if not url.startswith('rtmp'): raise Exception() if len(re.compile('\s*timeout=(\d*)').findall(url)) == 0: url += ' timeout=10' return url except: pass try: if not any(i in url for i in ['.m3u8', '.f4m', '.ts']): raise Exception() ext = url.split('?')[0].split('&')[0].split('|')[0].rsplit('.')[-1].replace('/', '').lower() if not ext in ['m3u8', 'f4m', 'ts']: raise Exception() return url except: pass try: preset = re.findall('<preset>(.+?)</preset>', url)[0] if not 'search' in preset: raise Exception() title, year, imdb = re.findall('<title>(.+?)</title>', url)[0], re.findall('<year>(.+?)</year>', url)[0], re.findall('<imdb>(.+?)</imdb>', url)[0] try: tvdb, tvshowtitle, premiered, season, episode = re.findall('<tvdb>(.+?)</tvdb>', url)[0], re.findall('<tvshowtitle>(.+?)</tvshowtitle>', url)[0], re.findall('<premiered>(.+?)</premiered>', url)[0], re.findall('<season>(.+?)</season>', url)[0], re.findall('<episode>(.+?)</episode>', url)[0] except: tvdb = tvshowtitle = premiered = season = episode = None direct = False quality = 'HD' if not preset == 'searchsd' else 'SD' from resources.lib.modules import sources u = sources.sources().getSources(title, year, imdb, tvdb, season, episode, tvshowtitle, premiered, quality) if not u == None: return u except: pass try: from resources.lib.modules import sources u = sources.sources().getURISource(url) if not u == False: direct = False if u == None or u == False: raise Exception() return u except: pass try: if not '.google.com' in url: raise Exception() from resources.lib.modules import directstream u = directstream.google(url)[0]['url'] return u except: pass try: if not 'filmon.com/' in url: raise Exception() from resources.lib.modules import filmon u = filmon.resolve(url) return u except: pass try: try: headers = dict(urlparse.parse_qsl(url.rsplit('|', 1)[1])) except: headers = dict('') if not url.startswith('http'): raise Exception() result = client.request(url.split('|')[0], headers=headers, output='headers', timeout='20') if 'Content-Type' in result and not 'html' in result['Content-Type']: raise Exception() import liveresolver if liveresolver.isValid(url) == True: direct = False u = liveresolver.resolve(url) if not u == None: try: dialog.close() except: pass return u except: pass try: import urlresolver hmf = urlresolver.HostedMediaFile(url=url) if hmf.valid_url() == False: raise Exception() direct = False ; u = hmf.resolve() if not u == False: return u except: pass if direct == True: return url
def play(self, url): try: control.execute('PlayMedia(%s)' % url) except: return
def onPlayBackStarted(self): control.execute('Dialog.Close(all,true)') if self.getbookmark == True and not self.offset == '0': self.seekTime(float(self.offset))
def add(self, tvshowtitle, year, imdb, tvdb, range=False): if not control.condVisibility('Window.IsVisible(infodialog)') and not control.condVisibility('Player.HasVideo')\ and self.silentDialog is False: control.infoDialog(control.lang(32552).encode('utf-8'), time=10000000) self.infoDialog = True from resources.lib.indexers import episodes items = episodes.episodes().get(tvshowtitle, year, imdb, tvdb, idx=False) try: items = [{ 'title': i['title'], 'year': i['year'], 'imdb': i['imdb'], 'tvdb': i['tvdb'], 'season': i['season'], 'episode': i['episode'], 'tvshowtitle': i['tvshowtitle'], 'premiered': i['premiered'] } for i in items] except: items = [] try: if not self.dupe_setting == 'true': raise Exception() if items == []: raise Exception() id = [items[0]['imdb'], items[0]['tvdb']] lib = control.jsonrpc( '{"jsonrpc": "2.0", "method": "VideoLibrary.GetTVShows", "params": {"properties" : ["imdbnumber", "title", "year"]}, "id": 1}' ) lib = unicode(lib, 'utf-8', errors='ignore') lib = json.loads(lib)['result']['tvshows'] lib = [ i['title'].encode('utf-8') for i in lib if str(i['imdbnumber']) in id or ( i['title'].encode('utf-8') == items[0]['tvshowtitle'] and str(i['year']) == items[0]['year']) ][0] lib = control.jsonrpc( '{"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodes", "params": {"filter":{"and": [{"field": "tvshow", "operator": "is", "value": "%s"}]}, "properties": ["season", "episode"]}, "id": 1}' % lib) lib = unicode(lib, 'utf-8', errors='ignore') lib = json.loads(lib)['result']['episodes'] lib = [ 'S%02dE%02d' % (int(i['season']), int(i['episode'])) for i in lib ] items = [ i for i in items if not 'S%02dE%02d' % (int(i['season']), int(i['episode'])) in lib ] except: pass files_added = 0 for i in items: try: if xbmc.abortRequested == True: return sys.exit() if self.check_setting == 'true': if i['episode'] == '1': self.block = True src = lib_tools.check_sources(i['title'], i['year'], i['imdb'], i['tvdb'], i['season'], i['episode'], i['tvshowtitle'], i['premiered']) if src: self.block = False if self.block == True: raise Exception() premiered = i.get('premiered', '0') if (premiered != '0' and int(re.sub('[^0-9]', '', str(premiered))) > int( self.date)) or (premiered == '0' and not self.include_unknown): continue self.strmFile(i) files_added += 1 except: pass if range == True: return if self.infoDialog is True: control.infoDialog(control.lang(32554).encode('utf-8'), time=1) if self.library_setting == 'true' and not control.condVisibility( 'Library.IsScanningVideo') and files_added > 0: control.execute('UpdateLibrary(video)')
def range(self, url, list_name): control.hide() if not control.yesnoDialog(control.lang(32555), '', ''): return try: if 'traktcollection' in url: message = 32661 elif 'traktwatchlist' in url: message = 32662 elif all(i in url for i in ['trakt', '/me/', '/lists/']): message = 32663 elif all(i in url for i in ['trakt', '/lists/']) and '/me/' not in url: message = 32664 elif 'tmdb_watchlist' in url: message = 32679 elif 'tmdb_favorites' in url: message = 32680 elif all(i in url for i in ['themoviedb', '/list/']): message = 32681 else: message = 'list import' except: log_utils.error() if general_notification: if not control.condVisibility('Window.IsVisible(infodialog)') and not control.condVisibility('Player.HasVideo'): control.notification(message=message) items = [] try: if 'trakt' in url: if 'traktcollection' in url: url = 'https://api.trakt.tv/users/me/collection/shows' if 'traktwatchlist' in url: url = 'https://api.trakt.tv/users/me/watchlist/shows' from resources.lib.menus import tvshows items = tvshows.TVshows().trakt_list(url, control.setting('trakt.user').strip()) if 'tmdb' in url: if 'tmdb_watchlist' in url: url = 'https://api.themoviedb.org/3/account/{account_id}/watchlist/tv?api_key=%s&session_id=%s' % ('%s', tmdb_session_id) if 'tmdb_favorites' in url: url = 'https://api.themoviedb.org/3/account/{account_id}/favorite/tv?api_key=%s&session_id=%s' % ('%s', tmdb_session_id) from resources.lib.indexers import tmdb items = tmdb.TVshows().tmdb_list(url) if (all(i in url for i in ['themoviedb', '/list/'])): url = url.split('&sort_by')[0] from resources.lib.indexers import tmdb items = tmdb.TVshows().tmdb_collections_list(url) except: log_utils.error() if items is None or items == []: if general_notification: control.notification(title=message, message=33049) return contains = lib_tools().ckKodiSources() total_added = 0 for i in items: if control.monitor.abortRequested(): return sys.exit() try: files_added = self.add(i['title'], i['year'], i['imdb'], i['tmdb'], i['tvdb'], range=True) if general_notification and files_added > 0: control.notification(title=i['title'], message=32554) if files_added > 0: total_added += 1 except: log_utils.error() try: type = 'tvshows' control.makeFile(control.dataPath) dbcon = database.connect(control.libcacheFile) dbcur = dbcon.cursor() dbcur.execute('''CREATE TABLE IF NOT EXISTS lists (type TEXT, list_name TEXT, url TEXT, UNIQUE(type, list_name, url));''') dbcur.execute('''INSERT OR REPLACE INTO lists Values (?, ?, ?)''', (type, list_name, url)) dbcur.connection.commit() except: log_utils.error() finally: dbcur.close() ; dbcon.close() if self.library_update == 'true' and not control.condVisibility('Library.IsScanningVideo') and total_added > 0: if contains: control.sleep(10000) control.execute('UpdateLibrary(video)') elif general_notification: control.notification(message=32103)
control.infoDialog(rlist[rand]['title'], control.lang(32536).encode('utf-8'), time=30000) except: pass elif rtype == "episode": try: control.infoDialog(rlist[rand]['tvshowtitle'] + " - Season " + rlist[rand]['season'] + " - " + rlist[rand]['title'], control.lang(32536).encode('utf-8'), time=30000) except: pass control.execute('RunPlugin(%s)' % r) except: control.infoDialog(control.lang(32537).encode('utf-8'), time=8000) #################################################### #----Library Actions #################################################### elif action == 'movieToLibrary': from resources.lib.modules import libtools libtools.libmovies().add(name, title, year, imdb, tmdb) elif action == 'moviesToLibrary': from resources.lib.modules import libtools libtools.libmovies().range(url) elif action == 'moviesToLibrarySilent':
def onPlayBackStarted(self): control.execute('Dialog.Close(all,true)') self.idleForPlayback() self.setProgress()
def sourcesDialog(self, items): try: labels = [i['label'] for i in items] select = control.selectDialog(labels) if select == -1: return 'close://' next = [y for x, y in enumerate(items) if x >= select] prev = [y for x, y in enumerate(items) if x < select][::-1] items = [items[select]] items = [i for i in items + next + prev][:40] header = control.addonInfo('name') header2 = header.upper() progressDialog = control.progressDialog if control.setting( 'progress.dialog') == '0' else control.progressDialogBG progressDialog.create(header, '') progressDialog.update(0) block = None for i in range(len(items)): try: if items[i]['source'] == block: raise Exception() w = workers.Thread(self.sourcesResolve, items[i]) w.start() try: if progressDialog.iscanceled(): break progressDialog.update( int((100 / float(len(items))) * i), str(items[i]['label']), str(' ')) except: progressDialog.update( int((100 / float(len(items))) * i), str(header2), str(items[i]['label'])) m = '' for x in range(3600): try: if xbmc.abortRequested == True: return sys.exit() if progressDialog.iscanceled(): return progressDialog.close() except: pass k = control.condVisibility( 'Window.IsActive(virtualkeyboard)') if k: m += '1' m = m[-1] if (w.is_alive() == False or x > 30) and not k: break k = control.condVisibility( 'Window.IsActive(yesnoDialog)') if k: m += '1' m = m[-1] if (w.is_alive() == False or x > 30) and not k: break time.sleep(0.5) for x in range(30): try: if xbmc.abortRequested == True: return sys.exit() if progressDialog.iscanceled(): return progressDialog.close() except: pass if m == '': break if w.is_alive() == False: break time.sleep(0.5) if w.is_alive() == True: block = items[i]['source'] if self.url == None: raise Exception() self.selectedSource = items[i]['label'] try: progressDialog.close() except: pass control.execute('Dialog.Close(virtualkeyboard)') control.execute('Dialog.Close(yesnoDialog)') return self.url except: pass try: progressDialog.close() except: pass except: try: progressDialog.close() except: pass
def process(self, url, direct=True): try: if not any(i in url for i in ['.jpg', '.png', '.gif']): raise Exception() ext = url.split('?')[0].split('&')[0].split('|')[0].rsplit('.')[-1].replace('/', '').lower() if not ext in ['jpg', 'png', 'gif']: raise Exception() try: i = os.path.join(control.dataPath,'img') control.deleteFile(i) f = control.openFile(i, 'w') f.write(client.request(url)) f.close() control.execute('ShowPicture("%s")' % i) return False except: return except: pass try: r, x = re.findall('(.+?)\|regex=(.+?)$', url)[0] x = regex.fetch(x) r += urllib.unquote_plus(x) if not '</regex>' in r: raise Exception() u = regex.resolve(r) if not u == None: url = u except: pass try: if not url.startswith('rtmp'): raise Exception() if len(re.compile('\s*timeout=(\d*)').findall(url)) == 0: url += ' timeout=10' return url except: pass try: if not any(i in url for i in ['.m3u8', '.f4m', '.ts']): raise Exception() ext = url.split('?')[0].split('&')[0].split('|')[0].rsplit('.')[-1].replace('/', '').lower() if not ext in ['m3u8', 'f4m', 'ts']: raise Exception() return url except: pass try: preset = re.findall('<preset>(.+?)</preset>', url)[0] if not 'search' in preset: raise Exception() title, year, imdb = re.findall('<title>(.+?)</title>', url)[0], re.findall('<year>(.+?)</year>', url)[0], re.findall('<imdb>(.+?)</imdb>', url)[0] try: tvdb, tvshowtitle, premiered, season, episode = re.findall('<tvdb>(.+?)</tvdb>', url)[0], re.findall('<tvshowtitle>(.+?)</tvshowtitle>', url)[0], re.findall('<premiered>(.+?)</premiered>', url)[0], re.findall('<season>(.+?)</season>', url)[0], re.findall('<episode>(.+?)</episode>', url)[0] except: tvdb = tvshowtitle = premiered = season = episode = None direct = False quality = 'HD' if not preset == 'searchsd' else 'SD' from resources.sources import sources u = sources().getSources(title, year, imdb, tvdb, season, episode, tvshowtitle, premiered, quality) if not u == None: return u except: pass try: from resources.sources import sources u = sources().getURISource(url) if not u == False: direct = False if u == None or u == False: raise Exception() return u except: pass try: if not '.google.com' in url: raise Exception() from resources.lib.modules import directstream u = directstream.google(url)[0]['url'] return u except: pass try: if not 'filmon.com/' in url: raise Exception() from resources.lib.modules import filmon u = filmon.resolve(url) return u except: pass try: if not 'uptostream/' in url: raise Exception() from resources.lib.modules import filmon u = url.replace('uptostream','uptobox') return u except: pass try: if not 'liveonlinetv' in url: raise Exception() u = liveonlinetv247(url) return (str(u)).replace('["' , '').replace(']"' , '').replace('[[' , '').replace(']]' , '').replace('[' , '').replace(']' , '').replace('"' , '').replace("'" , "") + '|User-Agent=Mozilla/5.0 (Windows NT 6.3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36' except: pass try: if not 'tvplayer' in url: raise Exception() u = playtvplayer(url) return u except: pass try: if not 'tvcatchup' in url: raise Exception() open = getUrl(url) u = re.compile("file: '(.+?)'").findall(open)[0] return u except: pass try: if not 'robssatellitetv.com' in url: raise Exception() open = getUrl(url) u = re.compile('src: "(.+?)"').findall(open)[0] return u except: pass try: if not 'arconaitv.me' in url: raise Exception() url = 'http://www.justproxy.co.uk/index.php?q='+base64.b64encode(url) open = getUrl(url) u = re.compile('"src":"(.+?)"').findall(open)[0] u = u.strip() return str(u).replace('\/','/').replace('"','') except: pass try: import urlresolver hmf = urlresolver.HostedMediaFile(url=url) if hmf.valid_url() == False: raise Exception() direct = False ; u = hmf.resolve() if not u == False: return u except: pass if direct == True: return url
import glob import os import re import traceback import xbmc import xbmcgui import xbmcaddon from resources.lib.modules import log_utils from resources.lib.modules import control from xbmc import (LOGDEBUG, LOGERROR, LOGFATAL, LOGINFO, LOGNONE, LOGNOTICE, LOGSEVERE, LOGWARNING) import threading control.execute('RunPlugin(plugin://%s)' % control.get_plugin_url({'action': 'service'})) def syncTraktLibrary(): control.execute( 'RunPlugin(plugin://%s)' % 'plugin.video.marvelrus/?action=tvshowsToLibrarySilent&url=traktcollection' ) control.execute( 'RunPlugin(plugin://%s)' % 'plugin.video.marvelrus/?action=moviesToLibrarySilent&url=traktcollection' ) try: ModuleVersion = control.addon('script.module.marvelrus').getAddonInfo(
def add(self, tvshowtitle, year, imdb, tmdb, tvdb, range=False): try: contains = lib_tools().ckKodiSources() if general_notification: if not control.condVisibility('Window.IsVisible(infodialog)') and not control.condVisibility('Player.HasVideo'): control.notification(title=tvshowtitle, message=32552) try: # from resources.lib.menus import episodes # items = episodes.Episodes().get(tvshowtitle, year, imdb, tmdb, tvdb, idx=False) from resources.lib.menus import seasons items = seasons.Seasons().tvdb_list(tvshowtitle, year, imdb, tmdb, tvdb, control.apiLanguage()['tvdb'], '-1') # fetch fresh meta (uncached) except: log_utils.error() return status = items[0]['status'].lower() try: items = [{'title': i['title'], 'year': i['year'], 'imdb': i['imdb'], 'tmdb': i['tmdb'], 'tvdb': i['tvdb'], 'season': i['season'], 'episode': i['episode'], 'tvshowtitle': i['tvshowtitle'], 'premiered': i['premiered']} for i in items] except: items = [] if items == []: return try: if self.dupe_chk != 'true': raise Exception() id = [items[0]['imdb'], items[0]['tvdb']] # lib = control.jsonrpc('{"jsonrpc": "2.0", "method": "VideoLibrary.GetTVShows", "params": {"properties" : ["imdbnumber", "title", "year"]}, "id": 1}') lib = control.jsonrpc('{"jsonrpc": "2.0", "method": "VideoLibrary.GetTVShows", "params": {"filter":{"or": [{"field": "year", "operator": "is", "value": "%s"}, {"field": "year", "operator": "is", "value": "%s"}, {"field": "year", "operator": "is", "value": "%s"}]}, "properties": ["imdbnumber", "title", "year"]}, "id": 1}' % (year, str(int(year)+1), str(int(year)-1))) lib = unicode(lib, 'utf-8', errors='ignore') lib = loads(lib)['result']['tvshows'] lib = [i['title'].encode('utf-8') for i in lib if str(i['imdbnumber']) in id or (i['title'].encode('utf-8') == items[0]['tvshowtitle'] and str(i['year']) == items[0]['year'])][0] lib = control.jsonrpc('{"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodes", "params": {"filter":{"and": [{"field": "tvshow", "operator": "is", "value": "%s"}]}, "properties": ["season", "episode"]}, "id": 1}' % lib) lib = unicode(lib, 'utf-8', errors='ignore') lib = loads(lib)['result']['episodes'] lib = ['S%02dE%02d' % (int(i['season']), int(i['episode'])) for i in lib] items = [i for i in items if not 'S%02dE%02d' % (int(i['season']), int(i['episode'])) in lib] except: lib = [] files_added = 0 for i in items: if lib != []: continue if control.monitor.abortRequested(): return sys.exit() try: if self.check_setting == 'true': if i['episode'] == '1': self.block = True src = lib_tools.check_sources(i['title'], i['year'], i['imdb'], i['tvdb'], i['season'], i['episode'], i['tvshowtitle'], i['premiered']) if src: self.block = False if self.block: continue # Show Season Special(Season0). if str(i.get('season')) == '0' and control.setting('tv.specials') == 'false': continue # Show Unaired or Unknown items. premiered = i.get('premiered', '0') if premiered == '0' and self.include_unknown == 'false': continue elif int(re.sub(r'[^0-9]', '', str(premiered))) > int(re.sub(r'[^0-9]', '', str(self.date))): if self.showunaired != 'true': continue self.strmFile(i) files_added += 1 except: log_utils.error() if files_added == 0 and general_notification: control.notification(title=tvshowtitle, message=32652) if range: return files_added if self.library_update == 'true' and not control.condVisibility('Library.IsScanningVideo') and files_added > 0: if contains: if general_notification: control.notification(title=tvshowtitle, message=32554) control.execute('UpdateLibrary(video)') elif general_notification: control.notification(title=tvshowtitle, message=32104) except: pass
def play(anime_id, episode_id): episode_link = episode_id l1 = "Fetching video." progressDialog.create(heading="Masterani", line1="Fetching video.") progressDialog.update(0, line1=l1, line3="Loading hosts.") hosts = getlinks(episode_link) ep_id = getid(episode_link) #linkforcover = getcover(episode_link) if hosts is None: xbmcgui.Dialog().ok("Masterani", "Something went wrong.", "Please try again later.") return #Remove Tiwi Kiwi as it is broken for e in hosts: if 'Tiwi.kiwi' in e['name']: hosts.remove(e) #Remove Disabled Hosts if control.setting("host.mp4upload") == "false": for e in hosts: if 'MP4Upload' in e['name']: hosts.remove(e) if control.setting("host.aniupload") == "false": for e in hosts: if 'Aniupload' in e['name']: hosts.remove(e) if control.setting("host.bakavide") == "false": for e in hosts: if 'Bakavideo' in e['name']: hosts.remove(e) if control.setting("host.youtube") == "false": for e in hosts: if 'YouTube' in e['name']: hosts.remove(e) if control.setting("host.beta") == "false": for e in hosts: if 'Beta' in e['name']: hosts.remove(e) if control.setting("host.stream.moe") == "false": for e in hosts: if 'Stream.moe' in e['name']: hosts.remove(e) if control.setting("host.drive.g") == "false": for e in hosts: if 'Drive.g' in e['name']: hosts.remove(e) if control.setting("host.vidstreaming") == "false": for e in hosts: if 'Vidstreaming' in e['name']: hosts.remove(e) if control.setting("host.rapidvideo") == "false": for e in hosts: if 'Rapidvideo' in e['name']: hosts.remove(e) if control.setting("host.aika") == "false": for e in hosts: if 'Aika' in e['name']: hosts.remove(e) if control.setting("host.streamango") == "false": for e in hosts: if 'Streamango' in e['name']: hosts.remove(e) if control.setting("host.openload") == "false": for e in hosts: if 'Openload' in e['name']: hosts.remove(e) progressDialog.update(25, line1=l1, line3="Loading episodes urls.") progressDialog.update(50, line1=l1, line3="Picking nose.") hostlist = [] videos = sorted(hosts, key=lambda k: (-int(k['type']), int(k['quality'])), reverse=True) print videos autoplay = control.setting("autoplay.enabled") maxq = control.setting("autoplay.maxquality") subdub = control.setting("autoplay.subdub") videoCounter = 0 autoplayHost = 0 hostCounter = 0 while videoCounter < len(videos): try: hostname = videos[videoCounter]['name'] subs = 'Sub' if videos[videoCounter]['type'] is 1 else 'Dub' quality = videos[videoCounter]['quality'] if 'true' in autoplay: if subdub == subs and int(quality) <= int(maxq): hostlist.append("%s | %s | %s" % (quality, subs, hostname)) autoplayHost = hostCounter break hostCounter += 1 else: hostlist.append("%s | %s | %s" % (quality, subs, hostname)) videoCounter += 1 except: videos.remove(videos[videoCounter]) if len(hostlist) is 0: progressDialog.close() xbmcgui.Dialog().ok("Masterani Redux", "No supported hosts found.") return if 'false' in autoplay: hostDialog = control.dialog.select("Select host.", hostlist) else: if len(hostlist) is 0: progressDialog.close() xbmcgui.Dialog().ok("Masterani Redux", "No hosts found for autoplay.", "Change addon settings and try again.") hostDialog = -1 else: hostDialog = autoplayHost if hostDialog == -1: progressDialog.close() control.execute('dialog.close(okdialog)') return hostname = videos[hostDialog]['name'] hostlink = videos[hostDialog]['url'] hostquality = videos[hostDialog]['quality'] embed_id = videos[hostDialog]['embed_id'] progressDialog.update(75, line1=l1, line3="Loading video.") #Resolve Links mp4 = getdirect(hostname, hostlink, hostquality, embed_id) progressDialog.close() MAPlayer().run(anime_id, ep_id, mp4)
def resolve(self, url): try: m3u8 = [ '#EXTM3U', '#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="audio",DEFAULT=YES,AUTOSELECT=YES,NAME="Stream 1",URI="{audio_stream}"', '', '#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=0,NAME="{stream_name}",AUDIO="audio"', '{video_stream}' ] query = urlparse.parse_qs(url) query = dict([(key, query[key][0]) if query[key] else (key, '') for key in query]) auth = 'http://streamtorrent.tv/api/torrent/%s/%s.m3u8?json=true' % (query['vid_id'], query['stream_id']) r = client.request(auth) r = json.loads(r) try: url = r['url'] except: url = None if not url == None: def dialog(url): try: self.disableScraper = control.yesnoDialog('Torba requires you visit, on any device, the following url to watch this video:', '[COLOR skyblue]%s[/COLOR]' % url, '', 'Torba', 'Cancel', 'Settings') except: pass workers.Thread(dialog, url).start() control.sleep(3000) for i in range(100): try: if not control.condVisibility('Window.IsActive(yesnoDialog)'): break r = client.request(auth) r = json.loads(r) try: url = r['url'] except: url = None if url == None: break workers.Thread(dialog, url).start() control.sleep(3000) except: pass if self.disableScraper: control.openSettings(query='2.0') return '' control.execute('Dialog.Close(yesnoDialog)') if not url == None: return stream_name = '%sp' % (query['height']) video_stream = r[stream_name] if not 'audio' in r: return video_stream audio_stream = r['audio'] content = ('\n'.join(m3u8)).format(**{'audio_stream': audio_stream, 'stream_name': stream_name, 'video_stream': video_stream}) path = os.path.join(control.dataPath, 'torbase.m3u8') control.makeFile(control.dataPath) ; control.deleteFile(path) file = control.openFile(path, 'w') ; file.write(content) ; file.close() return path except: return
def onPlayBackStarted(self): control.execute('Dialog.Close(all,true)') if not self.offset == '0': self.seekTime(float(self.offset)) subtitles().get(self.name, self.imdb, self.season, self.episode) self.idleForPlayback()
def play(anime_id, episode_id): # try: # content = cache.get(masterani.get_anime_details(anime_id), 2) l1 = "Fetching video" progressDialog.create(heading="MasterAni", line1="Fetching video") progressDialog.update(0, line1=l1, line3="Loading hosts") hosts = client.request("http://www.masterani.me/api/hosts") hosts = json.loads(hosts) progressDialog.update(25, line1=l1, line3="Loading episodes urls") videos = client.request("http://www.masterani.me/api/episode/%s?videos=1" % episode_id) videos = json.loads(videos)['videos'] progressDialog.update(50, line1=l1, line3="Picking nose") hostlist = [] videos = sorted(videos, key=lambda k: (int(k['quality']), int(k['type'])), reverse=True) autoplay = control.setting("autoplay.enabled") maxq = control.setting("autoplay.maxquality") subdub = control.setting("autoplay.subdub") for video in videos: hostname = [ x['name'] for x in hosts if int(x['id']) == int(video['host_id']) ][0] subs = 'Sub' if video['type'] is 1 else 'Dub' quality = video['quality'] if 'true' in autoplay: if subdub in subs and int(quality) <= int(maxq): hostlist.append("%s | %s | %s" % (quality, subs, hostname)) else: hostlist.append("%s | %s | %s" % (quality, subs, hostname)) if autoplay in 'false': hostdialog = control.dialog.select("Select host", hostlist) else: if len(hostlist) is 0: progressDialog.close() xbmcgui.Dialog().ok("Masterani", "No hosts found for autoplay.", "Change addon settings and try again.") hostdialog = -1 else: hostdialog = 0 if hostdialog == -1: progressDialog.close() control.execute('Dialog.Close(okdialog)') return host_id = videos[hostdialog]['host_id'] embed_id = videos[hostdialog]['embed_id'] if host_id is '': return prefix = "" suffix = "" for host in hosts: if str(host_id) in str(host['id']): prefix = host['embed_prefix'] suffix = host['embed_suffix'] break try: if suffix is not None: url = prefix + embed_id + suffix else: url = prefix + embed_id except: pass progressDialog.update(75, line1=l1, line3="Loading video") if 'moe' in host['name']: content = base64.b64decode( re.compile("atob\('(.+?)'\)").findall(client.request(url))[0]) mp4 = re.compile("source src=\"(.+?)\"").findall(content)[0] if 'MP4Upload' in host['name']: mp4 = re.compile("\"file\": \"(.+?)\"").findall(client.request(url))[0] if 'Bakavideo' in host['name']: content = re.compile("go\((.+?)\)").findall(client.request(url))[0] content = content.replace("'", "").replace(", ", "/") content = "https://bakavideo.tv/" + content content = client.request(content) content = json.loads(content) content = content['content'] content = base64.b64decode(content) mp4 = client.parseDOM(content, 'source', ret='src')[0] if 'BETA' in host['name']: mp4 = embed_id if 'Vidstream' in host['name']: mp4 = re.compile("source src='(.+?)'").findall(client.request(url))[0] if 'Aniupload' in host['name']: mp4 = re.compile("\(\[\{src: \"(.+?)\"").findall( client.request(url))[0] if 'Drive.g' in host['name']: mp4 = re.compile("url_encoded_fmt_stream_map\",\"(.+?)\"\]").findall( client.request(url))[0] mp4 = mp4.split(",")[0] mp4 = mp4[mp4.find("https"):] mp4 = urllib.unquote(mp4) progressDialog.close() control.sleep(100) MAPlayer().run(anime_id, episode_id, mp4)
def process(self, url, direct=True): try: if not any(i in url for i in ['.jpg', '.png', '.gif']): raise Exception() ext = url.split('?')[0].split('&')[0].split('|')[0].rsplit('.')[-1].replace('/', '').lower() if not ext in ['jpg', 'png', 'gif']: raise Exception() try: i = os.path.join(control.dataPath,'img') control.deleteFile(i) f = control.openFile(i, 'w') f.write(client.request(url)) f.close() control.execute('ShowPicture("%s")' % i) return False except: return except: pass try: r, x = re.findall('(.+?)\|regex=(.+?)$', url)[0] x = regex.fetch(x) r += urllib.unquote_plus(x) if not '</regex>' in r: raise Exception() u = regex.resolve(r) if not u is None: url = u except: pass try: if not url.startswith('rtmp'): raise Exception() if len(re.compile('\s*timeout=(\d*)').findall(url)) == 0: url += ' timeout=10' return url except: pass try: if not any(i in url for i in ['.m3u8', '.f4m', '.ts']): raise Exception() ext = url.split('?')[0].split('&')[0].split('|')[0].rsplit('.')[-1].replace('/', '').lower() if not ext in ['m3u8', 'f4m', 'ts']: raise Exception() return url except: pass try: preset = re.findall('<preset>(.+?)</preset>', url)[0] if not 'search' in preset: raise Exception() title, year, imdb = re.findall('<title>(.+?)</title>', url)[0], re.findall('<year>(.+?)</year>', url)[0], re.findall('<imdb>(.+?)</imdb>', url)[0] try: tvdb, tvshowtitle, premiered, season, episode = re.findall('<tvdb>(.+?)</tvdb>', url)[0], re.findall('<tvshowtitle>(.+?)</tvshowtitle>', url)[0], re.findall('<premiered>(.+?)</premiered>', url)[0], re.findall('<season>(.+?)</season>', url)[0], re.findall('<episode>(.+?)</episode>', url)[0] except: tvdb = tvshowtitle = premiered = season = episode = None direct = False quality = 'HD' if not preset == 'searchsd' else 'SD' from resources.lib.modules import sources u = sources.Sources().getSources(title, year, imdb, tvdb, season, episode, tvshowtitle, premiered, quality) if not u is None: return u except: pass try: from resources.lib.modules import sources u = sources.Sources().getURISource(url) if not u is False: direct = False if u is None or u is False: raise Exception() return u except: pass try: if not '.google.com' in url: raise Exception() from resources.lib.modules import directstream u = directstream.google(url)[0]['url'] return u except: pass try: if not 'filmon.com/' in url: raise Exception() from resources.lib.modules import filmon u = filmon.resolve(url) return u except: pass try: try: headers = dict(urlparse.parse_qsl(url.rsplit('|', 1)[1])) except: headers = dict('') if not url.startswith('http'): raise Exception() result = client.request(url.split('|')[0], headers=headers, output='headers', timeout='20') if 'Content-Type' in result and not 'html' in result['Content-Type']: raise Exception() import liveresolver if liveresolver.isValid(url) is True: direct = False u = liveresolver.resolve(url) if not u is None: try: dialog.close() except: pass return u except: pass try: import resolveurl hmf = resolveurl.HostedMediaFile(url=url) if hmf.valid_url() is False: raise Exception() direct = False ; u = hmf.resolve() if not u is False: return u except: pass if direct is True: return url
def resolve(self, url): try: m3u8 = [ [ '#EXTM3U', '', '#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH={bandwidth},NAME="{stream_name}"', '{video_stream}' ], [ '#EXTM3U', '#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="{audio_group}",DEFAULT=YES,AUTOSELECT=YES,NAME="Stream 1",URI="{audio_stream}"', '', '#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH={bandwidth},NAME="{stream_name}",AUDIO="{audio_group}"', '{video_stream}' ] ] query = urlparse.parse_qs(url) query = dict([(key, query[key][0]) if query[key] else (key, '') for key in query]) for i in m3u8: try: content = ('\n'.join(i)).format(**query) except: pass auth = query['video_stream'] r = client.request(auth, headers={'User-Agent': 'Lavf/56.40.101'}) try: url = json.loads(r)['url'] except: url = None if not url == None: def dialog(url): try: self.disableScraper = control.yesnoDialog('To watch this video visit from any device', '[COLOR skyblue]%s[/COLOR]' % url, '', 'Torba', 'Cancel', 'Settings') except: pass workers.Thread(dialog, url).start() control.sleep(3000) for i in range(100): try: if not control.condVisibility('Window.IsActive(yesnoDialog)'): break r = client.request(auth, headers={'User-Agent': 'Lavf/56.40.101'}) try: url = json.loads(r)['url'] except: url = None if url == None: break workers.Thread(dialog, url).start() control.sleep(3000) except: pass if self.disableScraper: control.openSettings(query='2.0') return '' control.execute('Dialog.Close(yesnoDialog)') if not url == None: return path = os.path.join(control.dataPath, 'torbase.m3u8') control.makeFile(control.dataPath) ; control.deleteFile(path) file = control.openFile(path, 'w') ; file.write(content) ; file.close() return path except: return
def ReloadMySkin(): control.execute("ReloadSkin()")