def range(self, url, query): if query == 'tool': return xbmc.executebuiltin('RunPlugin(%s?action=tvshowsToLibrary&url=%s)' % (sys.argv[0], urllib.quote_plus(url))) 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 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['tmdb'], i['tvdb'], i['tvrage'], 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 add(self, name, title, year, imdb, tmdb, 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, 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 = [] try: if not lib == []: raise Exception() if self.check_setting == 'true': from resources.lib.sources import sources src = sources().getSources(name, title, year, imdb, tmdb, '0', '0', None, None, None, '0', None) if not len(src) > 0: raise Exception() self.strmFile({'name': name, 'title': title, 'year': year, 'imdb': imdb, 'tmdb': tmdb}) except: pass if range == True: return 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 deleteFavourite(meta, content): try: meta = json.loads(meta) imdb = meta['imdb'] if 'title' in meta: title = meta['title'] if 'tvshowtitle' in meta: title = meta['tvshowtitle'] try: dbcon = database.connect(control.favouritesFile) dbcur = dbcon.cursor() dbcur.execute("DELETE FROM %s WHERE id = '%s'" % (content, imdb)) dbcon.commit() except: pass try: dbcon = database.connect(control.databaseFile) dbcur = dbcon.cursor() dbcur.execute("DELETE FROM favourites WHERE imdb_id = '%s'" % imdb) dbcon.commit() except: pass control.refresh() control.infoDialog(control.lang(30412).encode('utf-8'), heading=title) except: return
def addFavourite(meta, content, query): try: item = dict() meta = json.loads(meta) imdb = item['imdb'] = meta['imdb'] if 'title' in meta: title = item['title'] = meta['title'] if 'tvshowtitle' in meta: title = item['title'] = meta['tvshowtitle'] if 'year' in meta: item['year'] = meta['year'] if 'poster' in meta: item['poster'] = meta['poster'] if 'fanart' in meta: item['fanart'] = meta['fanart'] if 'tmdb' in meta: item['tmdb'] = meta['tmdb'] if 'tvdb' in meta: item['tvdb'] = meta['tvdb'] if 'tvrage' in meta: item['tvrage'] = meta['tvrage'] control.makeFile(control.dataPath) dbcon = database.connect(control.favouritesFile) dbcur = dbcon.cursor() dbcur.execute("CREATE TABLE IF NOT EXISTS %s (""id TEXT, ""items TEXT, ""UNIQUE(id)"");" % content) dbcur.execute("DELETE FROM %s WHERE id = '%s'" % (content, imdb)) dbcur.execute("INSERT INTO %s Values (?, ?)" % content, (imdb, repr(item))) dbcon.commit() if query == None: control.refresh() control.infoDialog(control.lang(30411).encode('utf-8'), heading=title) except: return
def silent(self, url): control.idle() if not control.condVisibility( 'Window.IsVisible(infodialog)') and not control.condVisibility( 'Player.HasVideo'): control.infoDialog(control.lang(32608).encode('utf-8'), time=10000000) self.infoDialog = True self.silentDialog = 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 is True: self.silentDialog = False control.infoDialog("Trakt TV Show Sync Complete", time=1)
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'], i['tmdb'], 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 clearCacheAll(self): control.idle() yes = control.yesnoDialog(control.lang(32056).encode('utf-8'), '', '') if not yes: return from resources.lib.libraries import cache cache.cache_clear_all() control.infoDialog(control.lang(32057).encode('utf-8'), sound=True, icon='INFO')
def addView(content): try: skin = control.skin skinPath = control.skinPath xml = os.path.join(skinPath,'addon.xml') file = control.openFile(xml) read = file.read().replace('\n','') file.close() try: src = re.compile('defaultresolution="(.+?)"').findall(read)[0] except: src = re.compile('<res.+?folder="(.+?)"').findall(read)[0] src = os.path.join(skinPath, src) src = os.path.join(src, 'MyVideoNav.xml') file = control.openFile(src) read = file.read().replace('\n','') file.close() views = re.compile('<views>(.+?)</views>').findall(read)[0] views = [int(x) for x in views.split(',')] for view in views: label = control.infoLabel('Control.GetLabel(%s)' % (view)) if not (label == '' or label == None): break record = (skin, content, str(view)) control.makeFile(control.dataPath) dbcon = database.connect(control.databaseFile) dbcur = dbcon.cursor() dbcur.execute("CREATE TABLE IF NOT EXISTS views (""skin TEXT, ""view_type TEXT, ""view_id TEXT, ""UNIQUE(skin, view_type)"");") dbcur.execute("DELETE FROM views WHERE skin = '%s' AND view_type = '%s'" % (record[0], record[1])) dbcur.execute("INSERT INTO views Values (?, ?, ?)", record) dbcon.commit() viewName = control.infoLabel('Container.Viewmode') control.infoDialog(control.lang(30491).encode('utf-8'), heading=viewName) except: return
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"], i["tmdb"], 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 range(self, url, query): if query == 'tool': return xbmc.executebuiltin('RunPlugin(%s?action=moviesToLibrary&url=%s)' % (sys.argv[0], urllib.quote_plus(url))) 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'], i['tmdb'], 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 add(self, tvshowtitle, year, imdb, tmdb, tvdb, tvrage, 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 from resources.lib.indexers import episodes items = episodes.episodes().get(tvshowtitle, year, imdb, tmdb, tvdb, tvrage, idx=False) try: items = [{'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 items] except: items = [] try: if not self.dupe_setting == 'true': raise Exception() if items == []: raise Exception() id = [items[0]['imdb'], items[0]['tvdb']] if not items[0]['tmdb'] == '0': id += [items[0]['tmdb']] 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 for i in items: try: if xbmc.abortRequested == True: return sys.exit() if self.check_setting == 'true': if i['episode'] == '1': self.block = True 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']) if src == True: self.block = False if self.block == True: raise Exception() 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']) if src == False: raise Exception() self.strmFile(i) except: pass if range == True: return 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 addView(content): try: # import pydevd # pydevd.settrace('localhost', port=5678, stdoutToServer=True, stderrToServer=True) skin = control.skin record = (skin, content, str(control.getCurrentViewId())) control.makeFile(control.dataPath) dbcon = database.connect(control.viewsFile) dbcur = dbcon.cursor() dbcur.execute("CREATE TABLE IF NOT EXISTS views (" "skin TEXT, " "view_type TEXT, " "view_id TEXT, " "UNIQUE(skin, view_type)" ");") dbcur.execute( "DELETE FROM views WHERE skin = '%s' AND view_type = '%s'" % (record[0], record[1])) dbcur.execute("INSERT INTO views Values (?, ?, ?)", record) dbcon.commit() viewName = control.infoLabel('Container.Viewmode') skinName = control.addon(skin).getAddonInfo('name') skinIcon = control.addon(skin).getAddonInfo('icon') control.infoDialog(viewName, heading=skinName, sound=True, icon=skinIcon) except: return
def add(self, name, title, year, imdb, tmdb, 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, 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 = [] try: if not lib == []: raise Exception() if self.check_setting == 'true': from resources.lib.sources import sources src = sources().checkSources(name, title, year, imdb, tmdb, '0', '0', None, None, None, '0', None) if src == False: raise Exception() self.strmFile({'name': name, 'title': title, 'year': year, 'imdb': imdb, 'tmdb': tmdb}) except: pass if range == True: return 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 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: control.log('## ITEMS %s' % i['title']) for i in items: try: if xbmc.abortRequested == True: return sys.exit() self.add('%s (%s)' % (i['title'], i['year']), i['title'], i['year'], i['imdb'], i['tmdb'], 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 onPlayBackStarted(self): for i in range(0, 200): if control.condVisibility('Window.IsActive(busydialog)') == 1: control.idle() else: break control.sleep(100) if control.setting('playback_info') == 'true': elapsedTime = '%s %s %s' % (control.lang(30464).encode('utf-8'), int((time.time() - self.loadingTime)), control.lang(30465).encode('utf-8')) control.infoDialog(elapsedTime, heading=self.name) try: if self.offset == '0': raise Exception() self.seekTime(float(self.offset)) except: pass try: if not control.setting('subtitles') == 'true': raise Exception() try: subtitle = subtitles.get(self.name, self.imdb, self.season, self.episode) except: subtitle = subtitles.get(self.name, self.imdb, '', '') except: pass
def add(self, tvshowtitle, year, imdb, tmdb, tvdb, tvrage, 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 from resources.lib.indexers import episodes items = episodes.episodes().get(tvshowtitle, year, imdb, tmdb, tvdb, tvrage, idx=False) try: items = [{'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 items] except: items = [] try: if not self.dupe_setting == 'true': raise Exception() if items == []: raise Exception() id = [items[0]['imdb'], items[0]['tvdb']] if not items[0]['tmdb'] == '0': id += [items[0]['tmdb']] 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 for i in items: try: if xbmc.abortRequested == True: return sys.exit() if self.check_setting == 'true': if i['episode'] == '1': self.block = True from resources.lib.sources import sources src = sources().getSources(i['name'], i['title'], i['year'], i['imdb'], i['tmdb'], i['tvdb'], i['tvrage'], i['season'], i['episode'], i['tvshowtitle'], i['alter'], i['date']) if len(src) > 0: self.block = False if self.block == True: raise Exception() if int(self.date) <= int(re.sub('[^0-9]', '', str(i['date']))): from resources.lib.sources import sources src = sources().getSources(i['name'], i['title'], i['year'], i['imdb'], i['tmdb'], i['tvdb'], i['tvrage'], i['season'], i['episode'], i['tvshowtitle'], i['alter'], i['date']) if not len(src) > 0: raise Exception() self.strmFile(i) except: pass if range == True: return 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 wizja_userstatus(): s = webClient() r = s.get('http://wizja.tv/users/index.php').text #print ('result :#%s#' % r) if 'login_input_username' in r: control.log('NIEZALOGOWANY') return 'NIEZALOGOWANY' if 'Zalogowany jako' in r: control.log('ZALOGOWANY') # no premium if '<font color=ff0000>Brak premium' in r: control.log('WIZJA.TV FREE PREMIUM: %s' % '') control.infoDialog(control.lang(30490).encode('utf-8'), time=6000) control.dialog.ok( control.addonInfo('name') + ' - WIZJA TV', control.lang(30490).encode('utf-8'), '') return 'FREE' else: try: premium = re.findall('Premium aktywne do (\d{4}.*?)</font>', r)[0] control.set_setting('wizja.expire', premium) control.infoDialog('Premium Wizja.tv do: ' + premium.encode('utf-8'), time=2000) return 'PREMIUM%s' % premium except: pass return 'PREMIUM%s' return True
def cache_version_check(): if _find_cache_version(): cache_clear() cache_clear_meta() cache_clear_providers() control.infoDialog(control.lang(32057).encode('utf-8'), sound=True, icon='INFO')
def play(self, name, title, year, imdb, tmdb, tvdb, tvrage, season, episode, tvshowtitle, alter, date, meta, url): control.log('############# PLAY # %s' % url) try: if not control.infoLabel('Container.FolderPath').startswith( 'plugin://'): control.playlist.clear() control.resolve(int(sys.argv[1]), True, control.item(path='')) control.execute('Dialog.Close(okdialog)') if imdb == '0': imdb = '0000000' imdb = 'tt' + re.sub('[^0-9]', '', str(imdb)) content = 'movie' if tvshowtitle == None else 'episode' self.sources = self.getSources(name, title, year, imdb, tmdb, tvdb, tvrage, season, episode, tvshowtitle, alter, date) if self.sources == []: raise Exception() self.sources = self.sourcesFilter() if control.window.getProperty('PseudoTVRunning') == 'True': url = self.sourcesDirect() elif url == 'dialog://': url = self.sourcesDialog() elif url == 'direct://': url = self.sourcesDirect() elif not control.infoLabel('Container.FolderPath').startswith( 'plugin://') and control.setting( 'autoplay_library') == 'false': url = self.sourcesDialog() elif control.infoLabel('Container.FolderPath').startswith( 'plugin://') and control.setting('autoplay') == 'false': url = self.sourcesDialog() else: url = self.sourcesDirect() if url == None: raise Exception() if url == 'close://': return if control.setting('playback_info') == 'true': control.infoDialog(self.selectedSource, heading=name) control.sleep(200) from resources.lib.libraries.player import player player().run(content, name, url, year, imdb, tvdb, meta) return url except: control.infoDialog(control.lang(30501).encode('utf-8'))
def play(self, name, title, year, imdb, tmdb, tvdb, tvrage, season, episode, tvshowtitle, alter, date, url): try: if imdb == "0": imdb = "0000000" imdb = "tt" + re.sub("[^0-9]", "", str(imdb)) content = "movie" if tvshowtitle == None else "episode" self.sources = self.getSources( name, title, year, imdb, tmdb, tvdb, tvrage, season, episode, tvshowtitle, alter, date ) if self.sources == []: raise Exception() self.sources = self.sourcesFilter() if control.window.getProperty("PseudoTVRunning") == "True": url = self.sourcesDirect() elif url == "dialog://": url = self.sourcesDialog() elif url == "direct://": url = self.sourcesDirect() elif ( not control.infoLabel("Container.FolderPath").startswith("plugin://") and control.setting("autoplay_library") == "false" ): url = self.sourcesDialog() elif ( control.infoLabel("Container.FolderPath").startswith("plugin://") and control.setting("autoplay") == "false" ): url = self.sourcesDialog() else: url = self.sourcesDirect() if url == None: raise Exception() if url == "close://": return if control.setting("playback_info") == "true": control.infoDialog(self.selectedSource, heading=name) from resources.lib.libraries.player import player player().run(content, name, url, imdb, tvdb) return url except: control.infoDialog(control.lang(30501).encode("utf-8")) pass
def playItem(self, content, name, imdb, tvdb, source): try: next = [] prev = [] for i in range(1,1000000): try: u = control.infoLabel('ListItem(%s).FolderPath' % str(i)) u = json.loads(dict(urlparse.parse_qsl(u.replace('?','')))['source'])[0] next.append(u) except: break for i in range(-1000000,0)[::-1]: try: u = control.infoLabel('ListItem(%s).FolderPath' % str(i)) u = json.loads(dict(urlparse.parse_qsl(u.replace('?','')))['source'])[0] prev.append(u) except: break items = json.loads(source) source, quality = items[0]['source'], items[0]['quality'] items = [i for i in items+next+prev if i['quality'] == quality and i['source'] == source][:15] items += [i for i in next+prev if i['quality'] == quality and not i['source'] == source][:35] block = None for i in items: try: if i['source'] == block: raise Exception() w = workers.Thread(self.sourcesResolve, i['url'], i['provider']) w.start() ; time.sleep(20) if w.is_alive() == True: block = i['source'] if self.url == None: raise Exception() if control.setting('playback_info') == 'true': control.infoDialog(i['label'], heading=name) from resources.lib.libraries.player import player player().run(content, name, self.url, imdb, tvdb) return self.url except: pass raise Exception() except: control.infoDialog(control.lang(30501).encode('utf-8')) pass
def play(self, name, title, year, imdb, tmdb, tvdb, tvrage, season, episode, tvshowtitle, alter, date, meta, url): try: if not control.infoLabel('Container.FolderPath').startswith('plugin://'): control.playlist.clear() control.resolve(int(sys.argv[1]), True, control.item(path=None)) control.execute('Dialog.Close(okdialog)') if imdb == '0': imdb = '0000000' imdb = 'tt' + re.sub('[^0-9]', '', str(imdb)) content = 'movie' if tvshowtitle == None else 'episode' self.sources = self.getSources(name, title, year, imdb, tmdb, tvdb, tvrage, season, episode, tvshowtitle, alter, date) if self.sources == []: raise Exception() self.sources = self.sourcesFilter() if control.window.getProperty('PseudoTVRunning') == 'True': url = self.sourcesDirect() elif url == 'dialog://': url = self.sourcesDialog() elif url == 'direct://': url = self.sourcesDirect() elif not control.infoLabel('Container.FolderPath').startswith('plugin://') and control.setting('autoplay_library') == 'false': url = self.sourcesDialog() elif control.infoLabel('Container.FolderPath').startswith('plugin://') and control.setting('autoplay') == 'false': url = self.sourcesDialog() else: url = self.sourcesDirect() if url == None: raise Exception() if url == 'close://': return if control.setting('playback_info') == 'true': control.infoDialog(self.selectedSource, heading=name) try: self.progressDialog.close() except: pass control.sleep(200) from resources.lib.libraries.player import player player().run(content, name, url, year, imdb, tvdb, meta) return url except: control.infoDialog(control.lang(30501).encode('utf-8'))
def removeDownload(url): try: def download(): return [] result = cache.get(download, 600000000, table='rel_dl') if result == '': result = [] result = [i for i in result if not i['url'] == url] if result == []: result = '' def download(): return result result = cache.get(download, 0, table='rel_dl') control.refresh() except: control.infoDialog('You need to remove file manually', 'Can not remove from Queue')
def clearSources(self): try: yes = control.yesnoDialog(control.lang(30510).encode('utf-8'), '', '') if not yes: return control.makeFile(control.dataPath) dbcon = database.connect(control.sourcescacheFile) dbcur = dbcon.cursor() dbcur.execute("DROP TABLE IF EXISTS rel_src") dbcur.execute("VACUUM") dbcon.commit() control.infoDialog(control.lang(30511).encode('utf-8')) except: pass
def playItem(self, content, name, imdb, tvdb, url, source, provider): try: url = self.sourcesResolve(url, provider) if url == None: raise Exception() if control.setting('playback_info') == 'true': control.infoDialog(source, heading=name) from resources.lib.libraries.player import player player().run(content, name, url, imdb, tvdb) return url except: control.infoDialog(control.lang(30501).encode('utf-8')) pass
def add(self, name, title, year, imdb, tmdb, 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, 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 = [] try: if not lib == []: raise Exception() if self.check_setting == "true": from resources.lib.sources import sources src = sources().checkSources(name, title, year, imdb, tmdb, "0", "0", None, None, None, "0", None) if src == False: raise Exception() self.strmFile({"name": name, "title": title, "year": year, "imdb": imdb, "tmdb": tmdb}) except: pass if range == True: return 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 onPlayBackStarted(self): if control.setting('playback_info') == 'true': elapsedTime = '%s %s %s' % (control.lang(30464).encode('utf-8'), int((time.time() - self.loadingTime)), control.lang(30465).encode('utf-8')) control.infoDialog(elapsedTime, heading=self.name) try: if self.offset == '0': raise Exception() self.seekTime(float(self.offset)) except: pass try: if not control.setting('subtitles') == 'true': raise Exception() try: subtitle = subtitles.get(self.name, self.imdb, self.season, self.episode) except: subtitle = subtitles.get(self.name, self.imdb, '', '') except: pass
def startDownload(): if downloadPath == '': return control.infoDialog( 'You need to set your download folder in addon settings first', 'File Not Downloadable') control.execute('RunPlugin(%s?action=startDownloadThread)' % sys.argv[0])
def play(self, name, title, year, imdb, tmdb, tvdb, tvrage, season, episode, tvshowtitle, alter, date, url): try: imdb = 'tt' + re.sub('[^0-9]', '', str(imdb)) content = 'movie' if tvshowtitle == None else 'episode' self.sources = self.getSources(name, title, year, imdb, tmdb, tvdb, tvrage, season, episode, tvshowtitle, alter, date) if self.sources == []: raise Exception() self.sources = self.sourcesFilter() if control.window.getProperty('PseudoTVRunning') == 'True': url = self.sourcesDirect() elif url == 'dialog://': url = self.sourcesDialog() elif url == 'direct://': url = self.sourcesDirect() elif not control.infoLabel('Container.FolderPath').startswith( 'plugin://') and control.setting( 'autoplay_library') == 'false': url = self.sourcesDialog() elif control.infoLabel('Container.FolderPath').startswith( 'plugin://') and control.setting('autoplay') == 'false': url = self.sourcesDialog() else: url = self.sourcesDirect() if url == None: raise Exception() if url == 'close://': return if control.setting('playback_info') == 'true': control.infoDialog(self.selectedSource, heading=name) from resources.lib.libraries.player import player player().run(content, name, url, imdb, tvdb) return url except: control.infoDialog(control.lang(30501).encode('utf-8')) pass
def download(name, image, url): if type(url) is list: url = url[0] from resources.lib.libraries import control if url == None: return control.infoDialog(control.lang(30501).encode('utf-8')) try: headers = dict(urlparse.parse_qsl(url.rsplit('|', 1)[1])) except: headers = dict('') url = url.split('|')[0] content = re.compile('(.+?)\sS(\d*)E\d*$').findall(name) transname = name.translate(None, '\/:*?"<>|').strip('.') levels =['../../../..', '../../..', '../..', '..'] if len(content) == 0: dest = control.setting('movie.download.path') dest = control.transPath(dest) for level in levels: try: control.makeFile(os.path.abspath(os.path.join(dest, level))) except: pass control.makeFile(dest) dest = os.path.join(dest, transname) control.makeFile(dest) else: dest = control.setting('tv.download.path') dest = control.transPath(dest) for level in levels: try: control.makeFile(os.path.abspath(os.path.join(dest, level))) except: pass control.makeFile(dest) transtvshowtitle = content[0][0].translate(None, '\/:*?"<>|').strip('.') dest = os.path.join(dest, transtvshowtitle) control.makeFile(dest) dest = os.path.join(dest, 'Season %01d' % int(content[0][1])) control.makeFile(dest) ext = os.path.splitext(urlparse.urlparse(url).path)[1][1:] if not ext in ['mp4', 'mkv', 'flv', 'avi', 'mpg']: ext = 'mp4' dest = os.path.join(dest, transname + '.' + ext) sysheaders = urllib.quote_plus(json.dumps(headers)) sysurl = urllib.quote_plus(url) systitle = urllib.quote_plus(name) sysimage = urllib.quote_plus(image) sysdest = urllib.quote_plus(dest) script = inspect.getfile(inspect.currentframe()) cmd = 'RunScript(%s, %s, %s, %s, %s, %s)' % (script, sysurl, sysdest, systitle, sysimage, sysheaders) xbmc.executebuiltin(cmd)
def manager(name, imdb, tvdb, content): try: post = {"movies": [{"ids": {"imdb": imdb}}]} if content == 'movie' else {"shows": [{"ids": {"tvdb": tvdb}}]} items = [(control.lang(32516).encode('utf-8'), '/sync/collection')] items += [(control.lang(32517).encode('utf-8'), '/sync/collection/remove')] items += [(control.lang(32518).encode('utf-8'), '/sync/watchlist')] items += [(control.lang(32519).encode('utf-8'), '/sync/watchlist/remove')] items += [(control.lang(32520).encode('utf-8'), '/users/me/lists/%s/items')] result = getTraktAsJson('/users/me/lists') lists = [(i['name'], i['ids']['slug']) for i in result] lists = [lists[i // 2] for i in range(len(lists) * 2)] for i in range(0, len(lists), 2): lists[i] = ((control.lang(32521) % lists[i][0]).encode('utf-8'), '/users/me/lists/%s/items' % lists[i][1]) for i in range(1, len(lists), 2): lists[i] = ( (control.lang(32522) % lists[i][0]).encode('utf-8'), '/users/me/lists/%s/items/remove' % lists[i][1]) items += lists select = control.selectDialog([i[0] for i in items], control.lang(32515).encode('utf-8')) if select == -1: return elif select == 4: t = control.lang(32520).encode('utf-8') k = control.keyboard('', t); k.doModal() new = k.getText() if k.isConfirmed() else None if (new == None or new == ''): return result = __getTrakt('/users/me/lists', post={"name": new, "privacy": "private"})[0] try: slug = utils.json_loads_as_str(result)['ids']['slug'] except: return control.infoDialog(control.lang(32515).encode('utf-8'), heading=str(name), sound=True, icon='ERROR') result = __getTrakt(items[select][1] % slug, post=post)[0] else: result = __getTrakt(items[select][1], post=post)[0] icon = control.infoLabel('ListItem.Icon') if not result == None else 'ERROR' control.infoDialog(control.lang(32515).encode('utf-8'), heading=str(name), sound=True, icon=icon) except: return
def get(self, tvshowtitle, year, imdb, tmdb, tvdb, tvrage, season=None, episode=None, idx=True, provider=None, url=None): try: if idx == True: #if not (tvdb == None or tvdb == '0') : #self.list = cache.get(seasons().tvdb_list, 1, tvshowtitle, year, imdb, tmdb, tvdb, tvrage, self.info_lang, season) #else : if not provider == None: call = __import__('resources.lib.sources.%s' % provider, globals(), locals(), ['source'], -1).source() self.list = call.get_episodes(tvshowtitle, url) if self.list == [] : raise Exception(control.lang(30516).encode('utf-8')) self.list = self.super_info(self.list) self.episodeDirectory(self.list, provider) return self.list except Exception as e: logger.error(e) control.infoDialog(control.lang(30516).encode('utf-8')) pass
def manager(name, imdb, tvdb, content): try: user, password = getTraktCredentials() post = {"movies": [{"ids": {"imdb": imdb}}]} if content == 'movie' else {"shows": [{"ids": {"tvdb": tvdb}}]} items = [(control.lang(30472).encode('utf-8'), '/sync/collection')] items += [(control.lang(30473).encode('utf-8'), '/sync/collection/remove')] items += [(control.lang(30474).encode('utf-8'), '/sync/watchlist')] items += [(control.lang(30475).encode('utf-8'), '/sync/watchlist/remove')] items += [(control.lang(30476).encode('utf-8'), '/users/%s/lists/%s/items' % (user, '%s'))] result = getTrakt('/users/%s/lists' % user) result = json.loads(result) lists = [(i['name'], i['ids']['slug']) for i in result] lists = [lists[i//2] for i in range(len(lists)*2)] for i in range(0, len(lists), 2): lists[i] = ((control.lang(30477) + ' ' + lists[i][0]).encode('utf-8'), '/users/%s/lists/%s/items' % (user, lists[i][1])) for i in range(1, len(lists), 2): lists[i] = ((control.lang(30478) + ' ' + lists[i][0]).encode('utf-8'), '/users/%s/lists/%s/items/remove' % (user, lists[i][1])) items += lists select = control.selectDialog([i[0] for i in items], control.lang(30471).encode('utf-8')) if select == -1: return elif select == 4: t = control.lang(30476).encode('utf-8') k = control.keyboard('', t) ; k.doModal() new = k.getText() if k.isConfirmed() else None if (new == None or new == ''): return url = '/users/%s/lists' % user result = getTrakt('/users/%s/lists' % user, post={"name": new, "privacy": "private"}) try: slug = json.loads(result)['ids']['slug'] except: return control.infoDialog('Failed', heading=name) result = getTrakt(items[select][1] % slug, post=post) else: result = getTrakt(items[select][1], post=post) info = 'Successful' if not result == None else 'Failed' control.infoDialog(info, heading=name) except: return
def manager(name, imdb, tvdb, content): try: post = {"movies": [{"ids": {"imdb": imdb}}]} if content == 'movie' else {"shows": [{"ids": {"tvdb": tvdb}}]} items = [(control.lang(32516).encode('utf-8'), '/sync/collection')] items += [(control.lang(32517).encode('utf-8'), '/sync/collection/remove')] items += [(control.lang(32518).encode('utf-8'), '/sync/watchlist')] items += [(control.lang(32519).encode('utf-8'), '/sync/watchlist/remove')] items += [(control.lang(32520).encode('utf-8'), '/users/me/lists/%s/items')] result = getTrakt('/users/me/lists') result = json.loads(result) lists = [(i['name'], i['ids']['slug']) for i in result] lists = [lists[i//2] for i in range(len(lists)*2)] for i in range(0, len(lists), 2): lists[i] = ((control.lang(32521) % lists[i][0]).encode('utf-8'), '/users/me/lists/%s/items' % lists[i][1]) for i in range(1, len(lists), 2): lists[i] = ((control.lang(32522) % lists[i][0]).encode('utf-8'), '/users/me/lists/%s/items/remove' % lists[i][1]) items += lists select = control.selectDialog([i[0] for i in items], control.lang(32515).encode('utf-8')) if select == -1: return elif select == 4: t = control.lang(32520).encode('utf-8') k = control.keyboard('', t) ; k.doModal() new = k.getText() if k.isConfirmed() else None if (new == None or new == ''): return result = getTrakt('/users/me/lists', post={"name": new, "privacy": "private"}) try: slug = json.loads(result)['ids']['slug'] except: return control.infoDialog(control.lang(32515).encode('utf-8'), heading=str(name), sound=True, icon='ERROR') result = getTrakt(items[select][1] % slug, post=post) else: result = getTrakt(items[select][1], post=post) icon = control.infoLabel('ListItem.Icon') if not result == None else 'ERROR' control.infoDialog(control.lang(32515).encode('utf-8'), heading=str(name), sound=True, icon=icon) except: return
def clear(table=None): try: if table == None: table = ['rel_list', 'rel_lib'] elif not type(table) == list: table = [table] yes = control.yesnoDialog(control.lang(30401).encode('utf-8'), '', '') if not yes: return dbcon = database.connect(control.cacheFile) dbcur = dbcon.cursor() for t in table: try: dbcur.execute("DROP TABLE IF EXISTS %s" % t) dbcur.execute("VACUUM") dbcon.commit() except: pass control.infoDialog(control.lang(30402).encode('utf-8')) except: pass
def run(self): def download(): return [] result = cache.get(download, 600000000, table='rel_dl') for item in result: self.name = item['name'] ; self.image = item['image'] ; self.url = item['url'] sysname = self.name.translate(None, '\/:*?"<>|').strip('.') url = self.url.split('|')[0] try: headers = dict(urlparse.parse_qsl(self.url.rsplit('|', 1)[1])) except: headers = dict('') ext = os.path.splitext(urlparse.urlparse(url).path)[1][1:].lower() if not ext in ['mp4', 'mkv', 'flv', 'avi', 'mpg']: ext = 'mp4' hdlr = re.compile('.+? ([(]\d{4}[)]|S\d*E\d*)$').findall(self.name) if len(hdlr) == 0: self.content = 'Uncategorised' hdlr = re.compile('.+? (S\d*E\d*)$').findall(self.name) if len(hdlr) > 0: self.content = 'TVShows' hdlr = re.compile('.+? [(](\d{4})[)]$').findall(self.name) if len(hdlr) > 0: self.content = 'Movies' if self.content == 'Movies': dest = os.path.join(downloadPath, 'Movies') control.makeFile(dest) dest = os.path.join(dest, sysname) control.makeFile(dest) elif self.content == 'TVShows': d = re.compile('(.+?) S(\d*)E(\d*)$').findall(sysname)[0] dest = os.path.join(downloadPath, 'TV Shows') control.makeFile(dest) dest = os.path.join(dest, d[0]) control.makeFile(dest) dest = os.path.join(dest, 'Season %01d' % int(d[1])) control.makeFile(dest) else: dest = os.path.join(downloadPath, 'Uncategorised') control.makeFile(dest) dest = os.path.join(dest, sysname + '.' + ext) control.infoDialog(self.name + ' Is Downloading', 'Downloads Started', self.image, time=7000) try: req = urllib2.Request(url, headers=headers) resp = urllib2.urlopen(req, timeout=30) except Exception,e: removeDownload(self.url) print '%s ERROR - File Failed To Open' % (dest) continue try: self.size = int(resp.headers['Content-Length']) except: self.size = 0 if self.size < 1: removeDownload(self.url) print '%s Unknown filesize - Unable to download' % (dest) continue try: resumable = 'bytes' in resp.headers['Accept-Ranges'].lower() except: resumable = False size = 1024 * 1024 if self.size < size: size = self.size gb = '%.2f GB' % (float(self.size) / 1073741824) start = time.clock() total = 0 ; notify = 0 ; errors = 0 ; count = 0 ; resume = 0 ; sleep = 0 self.clear() control.window.setProperty(property + '.status', 'downloading') control.window.setProperty(property + '.name', str(self.name)) control.window.setProperty(property + '.image', str(self.image)) control.window.setProperty(property + '.size', str(gb)) f = control.openFile(dest, 'wb') chunk = None chunks = [] while True: downloaded = total for c in chunks: downloaded += len(c) percent = min(100 * downloaded / self.size, 100) self.speed = str(int((downloaded / 1024) / (time.clock() - start))) + ' KB/s' self.percent = str(percent) + '%' control.window.setProperty(property + '.percent', str(self.percent)) control.window.setProperty(property + '.speed', str(self.speed)) if percent >= notify: control.infoDialog('Downloaded %s' % self.percent, self.name, self.image, time=5000) notify += 10 chunk = None error = False try: chunk = resp.read(size) if not chunk: if self.percent < 99: error = True else: while len(chunks) > 0: c = chunks.pop(0) f.write(c) del c f.close() print '%s download complete' % (dest) break except Exception, e: print str(e) error = True sleep = 10 errno = 0 if hasattr(e, 'errno'): errno = e.errno if errno == 10035: # 'A non-blocking socket operation could not be completed immediately' pass if errno == 10054: #'An existing connection was forcibly closed by the remote host' errors = 10 #force resume sleep = 30 if errno == 11001: # 'getaddrinfo failed' errors = 10 #force resume sleep = 30 if chunk: errors = 0 chunks.append(chunk) if len(chunks) > 5: c = chunks.pop(0) f.write(c) total += len(c) del c if error: errors += 1 count += 1 print '%d Error(s) whilst downloading %s' % (count, dest) control.sleep(sleep*1000) if (resumable and errors > 0) or errors >= 10: if (not resumable and resume >= 50) or resume >= 500: #Give up! print '%s download canceled - too many error whilst downloading' % (dest) break resume += 1 errors = 0 if resumable: chunks = [] #create new response print 'Download resumed (%d) %s' % (resume, dest) h = headers ; h['Range'] = 'bytes=%d-' % int(total) try: resp = urllib2.urlopen(urllib2.Request(url, headers=h), timeout=10) except: resp = None else: #use existing response pass if control.window.getProperty(property + '.status') == 'stop': control.infoDialog('Process Complete', 'Downloads', time=5000) return self.clear()
def addDownload(name, url, image, provider=None): try: def download(): return [] result = cache.get(download, 600000000, table='rel_dl') result = [i['name'] for i in result] except: pass if name in result: return control.infoDialog('Item Already In Your Queue', name) try: if not provider == None: from resources.lib.sources import sources url = sources().sourcesResolve(url, provider) if url == None: raise Exception() #legacy issue, will be removed later if 'afdah.org' in url and not '</source>' in url: url += '<source>afdah</source>' if '</source>' in url: source = re.compile('<source>(.+?)</source>').findall(url)[0] url = re.compile('(.+?)<source>').findall(url)[0] for i in ['_mv', '_tv', '_mv_tv']: try: call = __import__( 'resources.lib.sources.%s%s' % (source, i), globals(), locals(), ['object'], -1).source() except: pass from resources.lib import sources d = sources.sources() url = call.get_sources(url, d.hosthdfullDict, d.hostsdfullDict, d.hostlocDict) if type(url) == list: url = sorted(url, key=lambda k: k['quality']) url = url[0]['url'] url = call.resolve(url) from resources.lib import resolvers url = resolvers.request(url) if type(url) == list: url = sorted(url, key=lambda k: k['quality']) url = url[0]['url'] if url == None: raise Exception() except: return control.infoDialog('Unplayable stream') pass try: u = url.split('|')[0] try: headers = dict(urlparse.parse_qsl(url.rsplit('|', 1)[1])) except: headers = dict('') ext = os.path.splitext(urlparse.urlparse(u).path)[1][1:].lower() if ext == 'm3u8': raise Exception() #if not ext in ['mp4', 'mkv', 'flv', 'avi', 'mpg']: ext = 'mp4' dest = name + '.' + ext req = urllib2.Request(u, headers=headers) resp = urllib2.urlopen(req, timeout=30) size = int(resp.headers['Content-Length']) size = ' %.2f GB' % (float(size) / 1073741824) no = control.yesnoDialog(dest, 'Complete file is' + size, 'Continue with download?', name + ' - ' + 'Confirm Download', 'Confirm', 'Cancel') if no: return except: return control.infoDialog('Unable to download') pass def download(): return [{'name': name, 'url': url, 'image': image}] result = cache.get(download, 600000000, table='rel_dl') result = [i for i in result if not i['url'] == url] def download(): return result + [{'name': name, 'url': url, 'image': image}] result = cache.get(download, 0, table='rel_dl') control.infoDialog('Item Added to Queue', name)
pass if control.window.getProperty(property + '.status') == 'stop': control.infoDialog('Process Complete', 'Downloads', time=5000) return self.clear() self.clear() control.infoDialog(self.name + ' Completed', 'Download Complete', self.image, time=5000) removeDownload(self.url) control.infoDialog('Process Complete', 'Downloads', time=5000) return def kill(self): control.window.setProperty(property + '.status', 'stop') def clear(self): control.window.clearProperty(property + '.status') control.window.clearProperty(property + '.name') control.window.clearProperty(property + '.image') control.window.clearProperty(property + '.percent') control.window.clearProperty(property + '.speed') control.window.clearProperty(property + '.size') control.refresh()
def addItem(self, name, title, year, imdb, tmdb, tvdb, tvrage, season, episode, tvshowtitle, alter, date, meta): try: if imdb == '0': imdb = '0000000' imdb = 'tt' + re.sub('[^0-9]', '', str(imdb)) content = 'movie' if tvshowtitle == None else 'episode' self.sources = self.getSources(name, title, year, imdb, tmdb, tvdb, tvrage, season, episode, tvshowtitle, alter, date) if self.sources == []: raise Exception() self.sources = self.sourcesFilter() meta = json.loads(meta) infoMenu = control.lang(30502).encode('utf-8') if content == 'movie' else control.lang(30503).encode('utf-8') poster = meta['poster'] if 'poster' in meta else '0' banner = meta['banner'] if 'banner' in meta else '0' thumb = meta['thumb'] if 'thumb' in meta else poster fanart = meta['fanart'] if 'fanart' in meta else '0' if poster == '0': poster = control.addonPoster() if banner == '0' and poster == '0': banner = control.addonBanner() elif banner == '0': banner = poster if thumb == '0' and fanart == '0': thumb = control.addonFanart() elif thumb == '0': thumb = fanart if control.setting('fanart') == 'true' and not fanart == '0': pass else: fanart = control.addonFanart() sysaddon = sys.argv[0] for i in self.sources: try: url, label, provider = i['url'], i['label'], i['provider'] sysname, sysurl, sysimage, sysprovider = urllib.quote_plus(name), urllib.quote_plus(url), urllib.quote_plus(poster), urllib.quote_plus(provider) syssource = urllib.quote_plus(json.dumps([i])) query = 'action=playItem&content=%s&name=%s&imdb=%s&tvdb=%s&source=%s' % (content, sysname, imdb, tvdb, syssource) cm = [] cm.append((control.lang(30504).encode('utf-8'), 'RunPlugin(%s?action=queueItem)' % sysaddon)) cm.append((control.lang(30505).encode('utf-8'), 'RunPlugin(%s?action=download&name=%s&image=%s&url=%s&provider=%s)' % (sysaddon, sysname, sysimage, sysurl, sysprovider))) cm.append((infoMenu, 'Action(Info)')) cm.append((control.lang(30506).encode('utf-8'), 'RunPlugin(%s?action=refresh)' % sysaddon)) cm.append((control.lang(30507).encode('utf-8'), 'RunPlugin(%s?action=openSettings)' % sysaddon)) cm.append((control.lang(30508).encode('utf-8'), 'RunPlugin(%s?action=openPlaylist)' % sysaddon)) item = control.item(label=label, iconImage='DefaultVideo.png', thumbnailImage=thumb) try: item.setArt({'poster': poster, 'tvshow.poster': poster, 'season.poster': poster, 'banner': banner, 'tvshow.banner': banner, 'season.banner': banner}) except: pass item.setInfo(type='Video', infoLabels = meta) if not fanart == None: item.setProperty('Fanart_Image', fanart) item.setProperty('Video', 'true') item.setProperty('IsPlayable', 'true') item.addContextMenuItems(cm, replaceItems=True) control.addItem(handle=int(sys.argv[1]), url='%s?%s' % (sysaddon, query), listitem=item, isFolder=False) except: pass control.directory(int(sys.argv[1]), cacheToDisc=True) except: control.infoDialog(control.lang(30501).encode('utf-8')) pass
def resolveUrl(name, url, audio, image, fanart, playable, content): try: if '.f4m'in url: label = cleantitle(name) ext = url.split('?')[0].split('&')[0].split('|')[0].rsplit('.')[-1].replace('/', '').lower() if not ext == 'f4m': raise Exception() from resources.lib.libraries.f4mproxy.F4mProxy import f4mProxyHelper return f4mProxyHelper().playF4mLink(url, label, None, None,'',image) #legacy issue, will be removed later if 'afdah.org' in url and not '</source>' in url: url += '<source>afdah</source>' if '</source>' in url: source = re.compile('<source>(.+?)</source>').findall(url)[0] url = re.compile('(.+?)<source>').findall(url)[0] for i in ['_mv', '_tv', '_mv_tv']: try: call = __import__('resources.lib.sources.%s%s' % (source, i), globals(), locals(), ['object'], -1).source() except: pass from resources.lib import sources ; d = sources.sources() url = call.get_sources(url, d.hosthdfullDict, d.hostsdfullDict, d.hostlocDict) if type(url) == list and len(url) == 1: url = url[0]['url'] elif type(url) == list: url = sorted(url, key=lambda k: k['quality']) for i in url: i.update((k, '720p') for k, v in i.iteritems() if v == 'HD') for i in url: i.update((k, '480p') for k, v in i.iteritems() if v == 'SD') q = [i['quality'].upper() for i in url] u = [i['url'] for i in url] select = control.selectDialog(q) if select == -1: return url = u[select] url = call.resolve(url) from resources.lib import resolvers url = resolvers.request(url) if type(url) == list and len(url) == 1: url = url[0]['url'] elif type(url) == list: url = sorted(url, key=lambda k: k['quality']) for i in url: i.update((k, '720p') for k, v in i.iteritems() if v == 'HD') for i in url: i.update((k, '480p') for k, v in i.iteritems() if v == 'SD') q = [i['quality'].upper() for i in url] u = [i['url'] for i in url] select = control.selectDialog(q) if select == -1: return url = u[select] if url == None: raise Exception() except: return control.infoDialog('Unplayable stream') pass if playable == 'true': item = control.item(path=url) return control.resolve(int(sys.argv[1]), True, item) else: label = cleantitle(name) item = control.item(path=url, iconImage=image, thumbnailImage=image) item.setInfo( type='Video', infoLabels = {'title': label} ) control.playlist.clear() control.player.play(url, item)
def addItem(self, name, title, year, imdb, tmdb, tvdb, tvrage, season, episode, tvshowtitle, alter, date, meta): try: if imdb == '0': imdb = '0000000' imdb = 'tt' + re.sub('[^0-9]', '', str(imdb)) content = 'movie' if tvshowtitle == None else 'episode' self.sources = self.getSources(name, title, year, imdb, tmdb, tvdb, tvrage, season, episode, tvshowtitle, alter, date) if self.sources == []: raise Exception() self.sources = self.sourcesFilter() meta = json.loads(meta) infoMenu = control.lang(30502).encode( 'utf-8') if content == 'movie' else control.lang(30503).encode( 'utf-8') poster = meta['poster'] if 'poster' in meta else '0' banner = meta['banner'] if 'banner' in meta else '0' thumb = meta['thumb'] if 'thumb' in meta else poster fanart = meta['fanart'] if 'fanart' in meta else '0' if poster == '0': poster = control.addonPoster() if banner == '0' and poster == '0': banner = control.addonBanner() elif banner == '0': banner = poster if thumb == '0' and fanart == '0': thumb = control.addonFanart() elif thumb == '0': thumb = fanart if control.setting('fanart') == 'true' and not fanart == '0': pass else: fanart = control.addonFanart() sysaddon = sys.argv[0] for i in self.sources: try: url, label, provider = i['url'], i['label'], i['provider'] sysname, sysurl, sysimage, sysprovider = urllib.quote_plus( name), urllib.quote_plus(url), urllib.quote_plus( poster), urllib.quote_plus(provider) syssource = urllib.quote_plus(json.dumps([i])) query = 'action=playItem&content=%s&name=%s&imdb=%s&tvdb=%s&source=%s' % ( content, sysname, imdb, tvdb, syssource) cm = [] cm.append((control.lang(30504).encode('utf-8'), 'RunPlugin(%s?action=queueItem)' % sysaddon)) cm.append(( control.lang(30505).encode('utf-8'), 'RunPlugin(%s?action=download&name=%s&image=%s&url=%s&provider=%s)' % (sysaddon, sysname, sysimage, sysurl, sysprovider))) cm.append((infoMenu, 'Action(Info)')) cm.append((control.lang(30506).encode('utf-8'), 'RunPlugin(%s?action=refresh)' % sysaddon)) cm.append((control.lang(30507).encode('utf-8'), 'RunPlugin(%s?action=openSettings)' % sysaddon)) cm.append((control.lang(30508).encode('utf-8'), 'RunPlugin(%s?action=openPlaylist)' % sysaddon)) item = control.item(label=label, iconImage='DefaultVideo.png', thumbnailImage=thumb) try: item.setArt({ 'poster': poster, 'tvshow.poster': poster, 'season.poster': poster, 'banner': banner, 'tvshow.banner': banner, 'season.banner': banner }) except: pass item.setInfo(type='Video', infoLabels=meta) if not fanart == None: item.setProperty('Fanart_Image', fanart) item.setProperty('Video', 'true') item.setProperty('IsPlayable', 'true') item.addContextMenuItems(cm, replaceItems=True) control.addItem(handle=int(sys.argv[1]), url='%s?%s' % (sysaddon, query), listitem=item, isFolder=False) except: pass control.directory(int(sys.argv[1]), cacheToDisc=True) except: control.infoDialog(control.lang(30501).encode('utf-8')) pass
def playItem(self, content, name, imdb, tvdb, source): try: next = [] prev = [] total = [] for i in range(1, 10000): try: u = control.infoLabel('ListItem(%s).FolderPath' % str(i)) if u in total: raise Exception() total.append(u) u = json.loads( dict(urlparse.parse_qsl(u.replace('?', '')))['source'])[0] next.append(u) except: break for i in range(-10000, 0)[::-1]: try: u = control.infoLabel('ListItem(%s).FolderPath' % str(i)) if u in total: raise Exception() total.append(u) u = json.loads( dict(urlparse.parse_qsl(u.replace('?', '')))['source'])[0] prev.append(u) except: break items = json.loads(source) source, quality = items[0]['source'], items[0]['quality'] items = [ i for i in items + next + prev if i['quality'] == quality and i['source'] == source ][:10] items += [ i for i in next + prev if i['quality'] == quality and not i['source'] == source ][:10] import xbmc dialog = control.progressDialog dialog.create(control.addonInfo('name'), '') dialog.update(0) block = None for i in range(len(items)): try: dialog.update(int((100 / float(len(items))) * i), str(items[i]['label'])) if items[i]['source'] == block: raise Exception() w = workers.Thread(self.sourcesResolve, items[i]['url'], items[i]['provider']) w.start() for x in range(0, 15 * 2): if dialog.iscanceled(): return dialog.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: dialog.close() except: pass if control.setting('playback_info') == 'true': control.infoDialog(items[i]['label'], heading=name) from resources.lib.libraries.player import player player().run(content, name, self.url, imdb, tvdb) return self.url except: pass try: dialog.close() except: pass raise Exception() except: control.infoDialog(control.lang(30501).encode('utf-8')) pass
def nhlStreams(name, url): try: name = re.sub('\s\[COLOR.+?\].+?\[/COLOR\]', '', name).strip() n1 = name + ' [COLOR gold]%s[/COLOR]' ; n2 = name + ' [COLOR red]%s[/COLOR]' selectHomeGame = 'x0xe%sx0xehome' % str(url) selectAwayGame = 'x0xe%sx0xeaway' % str(url) url = re.compile('(\d{4})(\d{2})(\d{4})').findall(url)[0] url = 'http://smb.cdnak.neulion.com/fs/nhl/mobile/feed_new/data/streams/%s/ipad/%s_%s.json' % (url[0], url[1], url[2]) result = client.request(url) result = json.loads(result) items = result['gameStreams']['ipad'] h = items['home'] ; a = items['away'] except: pass l1 = []; l2 = [] try: finish = result['finish'] except: finish = 'true' try: image = re.compile('"image" *: *"(.+?)"').findall(json.dumps(h))[-1] except: image = '0' try: l1.append({'name': n1 % 'Home LIVE', 'url': h['live']['bitrate0'] + selectHomeGame, 'image': image}) except: pass try: l2.append({'name': n2 % 'Home Whole', 'url': h['vod-whole']['bitrate0'], 'image': image}) except: pass try: l2.append({'name': n2 % 'Home Continuous', 'url': h['vod-continuous']['bitrate0'], 'image': image}) except: pass try: l2.append({'name': n2 % 'Home Condensed', 'url': h['vod-condensed']['bitrate0'], 'image': image}) except: pass try: image = re.compile('"image" *: *"(.+?)"').findall(json.dumps(a))[-1] except: image = '0' try: l1.append({'name': n1 % 'Away LIVE', 'url': a['live']['bitrate0'] + selectAwayGame, 'image': image}) except: pass try: l2.append({'name': n2 % 'Away Whole', 'url': a['vod-whole']['bitrate0'], 'image': image}) except: pass try: l2.append({'name': n2 % 'Away Continuous', 'url': a['vod-continuous']['bitrate0'], 'image': image}) except: pass try: l2.append({'name': n2 % 'Away Condensed', 'url': a['vod-condensed']['bitrate0'], 'image': image}) except: pass if finish == 'false': for i in l1: addDirectoryItem(i['name'], i['url'], 'nhlResolve', i['image'], '0', isFolder=False) else: for i in l2: addDirectoryItem(i['name'], i['url'], 'nhlResolve', i['image'], '0', isFolder=False) if l1 == [] and l2 == []: return control.infoDialog(control.lang(30755).encode('utf-8'), name, addonIcon) endDirectory()
else: #use existing response pass if control.window.getProperty(property + '.status') == 'stop': control.infoDialog('Process Complete', 'Downloads', time=5000) return self.clear() self.clear() control.infoDialog(self.name + ' Completed', 'Download Complete', self.image, time=5000) removeDownload(self.url) control.infoDialog('Process Complete', 'Downloads', time=5000) return def kill(self): control.window.setProperty(property + '.status', 'stop') def clear(self): control.window.clearProperty(property + '.status') control.window.clearProperty(property + '.name') control.window.clearProperty(property + '.image') control.window.clearProperty(property + '.percent') control.window.clearProperty(property + '.speed') control.window.clearProperty(property + '.size') control.refresh()
def playItem(self, content, name, year, imdb, tvdb, source): try: control.resolve(int(sys.argv[1]), True, control.item(path='')) control.execute('Dialog.Close(okdialog)') next = [] prev = [] total = [] meta = None for i in range(1, 10000): 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('?', ''))) if 'meta' in u: meta = u['meta'] u = json.loads(u['source'])[0] next.append(u) except: break for i in range(-10000, 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('?', ''))) if 'meta' in u: meta = u['meta'] u = json.loads(u['source'])[0] prev.append(u) except: break items = json.loads(source) source, quality = items[0]['source'], items[0]['quality'] items = [ i for i in items + next + prev if i['quality'] == quality and i['source'] == source ][:10] items += [ i for i in next + prev if i['quality'] == quality and not i['source'] == source ][:10] 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]['url'], items[i]['provider']) 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 time.sleep(1) 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(1) if w.is_alive() == True: block = items[i]['source'] if self.url == None: raise Exception() try: self.progressDialog.close() except: pass control.sleep(200) if control.setting('playback_info') == 'true': control.infoDialog(items[i]['label'], heading=name) from resources.lib.libraries.player import player player().run(content, name, self.url, year, imdb, tvdb, meta) return self.url except: pass try: self.progressDialog.close() except: pass raise Exception() except: control.infoDialog(control.lang(30501).encode('utf-8')) pass
def startDownload(): if downloadPath == '': return control.infoDialog('You need to set your download folder in addon settings first', 'File Not Downloadable') control.execute('RunPlugin(%s?mode=startDownloadThread)' % sys.argv[0])
def playItem(self, content, name, year, imdb, tvdb, source): try: control.resolve(int(sys.argv[1]), True, control.item(path='')) control.execute('Dialog.Close(okdialog)') next = [] ; prev = [] ; total = [] meta = None for i in range(1,10000): 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('?',''))) if 'meta' in u: meta = u['meta'] u = json.loads(u['source'])[0] next.append(u) except: break for i in range(-10000,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('?',''))) if 'meta' in u: meta = u['meta'] u = json.loads(u['source'])[0] prev.append(u) except: break items = json.loads(source) source, quality = items[0]['source'], items[0]['quality'] items = [i for i in items+next+prev if i['quality'] == quality and i['source'] == source][:10] items += [i for i in next+prev if i['quality'] == quality and not i['source'] == source][:10] 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]['url'], items[i]['provider']) 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 time.sleep(1) 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(1) if w.is_alive() == True: block = items[i]['source'] if self.url == None: raise Exception() try: self.progressDialog.close() except: pass control.sleep(200) if control.setting('playback_info') == 'true': control.infoDialog(items[i]['label'], heading=name) from resources.lib.libraries.player import player player().run(content, name, self.url, year, imdb, tvdb, meta) 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, info='true'): if query == 'tool': return xbmc.executebuiltin('RunPlugin(%s?action=updateLibrary)' % sys.argv[0]) 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().getSources(i['name'], i['title'], i['year'], i['imdb'], i['tmdb'], i['tvdb'], i['tvrage'], i['season'], i['episode'], i['tvshowtitle'], i['alter'], i['date']) if not len(src) > 2: 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)')
def run(self): def download(): return [] result = cache.get(download, 600000000, table='rel_dl') for item in result: self.name = item['name'] self.image = item['image'] self.url = item['url'] sysname = self.name.translate(None, '\/:*?"<>|').strip('.') url = self.url.split('|')[0] try: headers = dict(urlparse.parse_qsl(self.url.rsplit('|', 1)[1])) except: headers = dict('') ext = os.path.splitext(urlparse.urlparse(url).path)[1][1:].lower() if not ext in ['mp4', 'mkv', 'flv', 'avi', 'mpg']: ext = 'mp4' hdlr = re.compile('.+? ([(]\d{4}[)]|S\d*E\d*)$').findall(self.name) if len(hdlr) == 0: self.content = 'Uncategorised' hdlr = re.compile('.+? (S\d*E\d*)$').findall(self.name) if len(hdlr) > 0: self.content = 'TVShows' hdlr = re.compile('.+? [(](\d{4})[)]$').findall(self.name) if len(hdlr) > 0: self.content = 'Movies' if self.content == 'Movies': dest = os.path.join(downloadPath, 'Movies') control.makeFile(dest) dest = os.path.join(dest, sysname) control.makeFile(dest) elif self.content == 'TVShows': d = re.compile('(.+?) S(\d*)E(\d*)$').findall(sysname)[0] dest = os.path.join(downloadPath, 'TVShows') control.makeFile(dest) dest = os.path.join(dest, d[0]) control.makeFile(dest) dest = os.path.join(dest, 'Season %01d' % int(d[1])) control.makeFile(dest) else: dest = os.path.join(downloadPath, 'Uncategorised') control.makeFile(dest) dest = os.path.join(dest, sysname + '.' + ext) control.infoDialog(self.name + ' Is Downloading', 'Downloads Started', self.image, time=7000) try: req = urllib2.Request(url, headers=headers) resp = urllib2.urlopen(req, timeout=30) except Exception, e: removeDownload(self.url) print '%s ERROR - File Failed To Open' % (dest) continue try: self.size = int(resp.headers['Content-Length']) except: self.size = 0 if self.size < 1: removeDownload(self.url) print '%s Unknown filesize - Unable to download' % (dest) continue try: resumable = 'bytes' in resp.headers['Accept-Ranges'].lower() except: resumable = False size = 1024 * 1024 if self.size < size: size = self.size gb = '%.2f GB' % (float(self.size) / 1073741824) start = time.clock() total = 0 notify = 0 errors = 0 count = 0 resume = 0 sleep = 0 self.clear() control.window.setProperty(property + '.status', 'downloading') control.window.setProperty(property + '.name', str(self.name)) control.window.setProperty(property + '.image', str(self.image)) control.window.setProperty(property + '.size', str(gb)) f = control.openFile(dest, 'wb') chunk = None chunks = [] while True: downloaded = total for c in chunks: downloaded += len(c) percent = min(100 * downloaded / self.size, 100) self.speed = str( int((downloaded / 1024) / (time.clock() - start))) + ' KB/s' self.percent = str(percent) + '%' control.window.setProperty(property + '.percent', str(self.percent)) control.window.setProperty(property + '.speed', str(self.speed)) if percent >= notify: control.infoDialog('Downloaded %s' % self.percent, self.name, self.image, time=5000) notify += 10 chunk = None error = False try: chunk = resp.read(size) if not chunk: if self.percent < 99: error = True else: while len(chunks) > 0: c = chunks.pop(0) f.write(c) del c f.close() print '%s download complete' % (dest) break except Exception, e: print str(e) error = True sleep = 10 errno = 0 if hasattr(e, 'errno'): errno = e.errno if errno == 10035: # 'A non-blocking socket operation could not be completed immediately' pass if errno == 10054: #'An existing connection was forcibly closed by the remote host' errors = 10 #force resume sleep = 30 if errno == 11001: # 'getaddrinfo failed' errors = 10 #force resume sleep = 30 if chunk: errors = 0 chunks.append(chunk) if len(chunks) > 5: c = chunks.pop(0) f.write(c) total += len(c) del c if error: errors += 1 count += 1 print '%d Error(s) whilst downloading %s' % (count, dest) control.sleep(sleep * 1000) if (resumable and errors > 0) or errors >= 10: if (not resumable and resume >= 50) or resume >= 500: #Give up! print '%s download canceled - too many error whilst downloading' % ( dest) break resume += 1 errors = 0 if resumable: chunks = [] #create new response print 'Download resumed (%d) %s' % (resume, dest) h = headers h['Range'] = 'bytes=%d-' % int(total) try: resp = urllib2.urlopen(urllib2.Request(url, headers=h), timeout=10) except: resp = None else: #use existing response pass if control.window.getProperty(property + '.status') == 'stop': control.infoDialog('Process Complete', 'Downloads', time=5000) return self.clear()
def addDownload(name, url, image, provider=None): try: def download(): return [] result = cache.get(download, 600000000, table='rel_dl') result = [i['name'] for i in result] except: pass if name in result: return control.infoDialog('Item Already In Your Queue', name) try: if not provider == None: from resources.lib.sources import sources url = sources().sourcesResolve(url, provider) if url == None: raise Exception() #legacy issue, will be removed later if 'afdah.org' in url and not '</source>' in url: url += '<source>afdah</source>' if '</source>' in url: source = re.compile('<source>(.+?)</source>').findall(url)[0] url = re.compile('(.+?)<source>').findall(url)[0] for i in ['_mv', '_tv', '_mv_tv']: try: call = __import__('resources.lib.sources.%s%s' % (source, i), globals(), locals(), ['object'], -1).source() except: pass from resources.lib import sources ; d = sources.sources() url = call.get_sources(url, d.hosthdfullDict, d.hostsdfullDict, d.hostlocDict) if type(url) == list: url = sorted(url, key=lambda k: k['quality']) url = url[0]['url'] url = call.resolve(url) from resources.lib import resolvers url = resolvers.request(url) if type(url) == list: url = sorted(url, key=lambda k: k['quality']) url = url[0]['url'] if url == None: raise Exception() except: return control.infoDialog('Unplayable stream') pass try: u = url.split('|')[0] try: headers = dict(urlparse.parse_qsl(url.rsplit('|', 1)[1])) except: headers = dict('') ext = os.path.splitext(urlparse.urlparse(u).path)[1][1:].lower() if ext == 'm3u8': raise Exception() #if not ext in ['mp4', 'mkv', 'flv', 'avi', 'mpg']: ext = 'mp4' dest = name + '.' + ext req = urllib2.Request(u, headers=headers) resp = urllib2.urlopen(req, timeout=30) size = int(resp.headers['Content-Length']) size = ' %.2f GB' % (float(size) / 1073741824) no = control.yesnoDialog(dest, 'Complete file is' + size, 'Continue with download?', name + ' - ' + 'Confirm Download', 'Confirm', 'Cancel') if no: return except: return control.infoDialog('Unable to download') pass def download(): return [{'name': name, 'url': url, 'image': image}] result = cache.get(download, 600000000, table='rel_dl') result = [i for i in result if not i['url'] == url] def download(): return result + [{'name': name, 'url': url, 'image': image}] result = cache.get(download, 0, table='rel_dl') control.infoDialog('Item Added to Queue', name)