def root(self): self.addDirectoryItem(30001, 'movieNavigator', 'movies.jpg', 'DefaultMovies.png') self.addDirectoryItem(30002, 'tvNavigator', 'tvshows.jpg', 'DefaultTVShows.png') self.addDirectoryItem(30003, 'channels', 'channels.jpg', 'DefaultMovies.png') self.addDirectoryItem(30004, 'myNavigator', 'myspecto.jpg', 'DefaultVideoPlaylists.png') if not control.setting('movie_widget') == '0': self.addDirectoryItem(30005, 'movieWidget', 'moviesAdded.jpg', 'DefaultRecentlyAddedMovies.png') if (traktMode == True and not control.setting('tv_alt_widget') == '0') or (traktMode == False and not control.setting('tv_widget') == '0'): #self.addDirectoryItem(30006, 'tvWidget', 'calendarsAdded.jpg', 'DefaultRecentlyAddedEpisodes.png') self.addDirectoryItem(30006, 'calendar&url=added', 'calendarsAdded.jpg', 'DefaultRecentlyAddedEpisodes.png') if not control.setting('calendar_widget') == '0': self.addDirectoryItem(30007, 'calendars', 'calendar.jpg', 'DefaultRecentlyAddedEpisodes.png') self.addDirectoryItem(30008, 'toolNavigator', 'tools.jpg', 'DefaultAddonProgram.png') self.addDirectoryItem(30009, 'searchNavigator', 'search.jpg', 'DefaultFolder.png') self.endDirectory() from resources.lib.libraries import cache from resources.lib.libraries import changelog
def __init__(self): self.base_link = 'http://ororo.tv' self.sign_link = 'http://ororo.tv/users/sign_in' self.user = control.setting('ororo_user') self.password = control.setting('ororo_password') self.post = {'user[email]': self.user, 'user[password]': self.password, 'user[remember_me]': 1} self.post = urllib.urlencode(self.post)
def get_episode(self, url, imdb, tvdb, title, date, season, episode): try: if control.setting('alluc_user'): if control.setting('realdebrid_token') or control.setting('premiumize_user'): self.moviesearch_link = '/api/search/download?user=%s&password=%s&query=%s' else: self.moviesearch_link = '/api/search/stream/?user=%s&password=%s&query=%s' tvshowtitle, year = re.compile('(.+?) [(](\d{4})[)]$').findall(url)[0] season, episode = season.zfill(2), episode.zfill(2) query = '%s s%se%s' % (tvshowtitle, season, episode) query = self.moviesearch_link % (control.setting('alluc_user'), control.setting('alluc_password'), urllib.quote_plus(query)) r = urlparse.urljoin(self.base_link, query) r = r + "+%23newlinks" r = requests.get(r).json() for item in r['result']: if len(item['hosterurls']) == 1 and 'en' in item['lang']: tmp = item['hosterurls'][0]['url'] tmp = client.replaceHTMLCodes(tmp) tmp = tmp.encode('utf-8') title = item['title'].encode('utf-8') self.stream_url.append({'url': tmp, 'hoster': item['hostername'], 'title': title }) return self.stream_url except Exception as e: control.log('alluc error tv') control.log(e) return
def get_movie(self, imdb, title, year): try: if control.setting('alluc_user'): if control.setting('realdebrid_token') or control.setting('premiumize_user'): self.moviesearch_link = '/api/search/download?user=%s&password=%s&query=%s+%s' else: self.moviesearch_link = '/api/search/stream/?user=%s&password=%s&query=%s+%s' url = self.moviesearch_link % (control.setting('alluc_user'), control.setting('alluc_password'),cleantitle.geturl(title), year) r = urlparse.urljoin(self.base_link, url) r = r + "+%23newlinks" r = client.request(r) r1 = json.loads(r) for item in r1['result']: if len(item['hosterurls']) == 1 and 'en' in item['lang']: tmp = item['hosterurls'][0]['url'] tmp = client.replaceHTMLCodes(tmp) tmp = tmp.encode('utf-8') title = item['title'].encode('utf-8') self.stream_url.append({'url': tmp, 'hoster': item['hostername'], 'title': title }) return self.stream_url except Exception as e: control.log(e) return
def genesis(self): if traktMode == True: self.addDirectoryItem(30081, 'movies&url=traktcollection', 'moviesTraktcollection.jpg', 'DefaultMovies.png', context=(30191, 'moviesToLibrary&url=traktcollection')) self.addDirectoryItem(30082, 'movies&url=traktwatchlist', 'moviesTraktwatchlist.jpg', 'DefaultMovies.png', context=(30191, 'moviesToLibrary&url=traktwatchlist')) self.addDirectoryItem(30083, 'movies&url=traktfeatured', 'movies.jpg', 'DefaultMovies.png') self.addDirectoryItem(30084, 'movies&url=traktratings', 'movies.jpg', 'DefaultMovies.png') self.addDirectoryItem(30085, 'tvshows&url=traktcollection', 'tvshowsTraktcollection.jpg', 'DefaultTVShows.png', context=(30191, 'tvshowsToLibrary&url=traktcollection')) self.addDirectoryItem(30086, 'tvshows&url=traktwatchlist', 'tvshowsTraktwatchlist.jpg', 'DefaultTVShows.png', context=(30191, 'tvshowsToLibrary&url=traktwatchlist')) self.addDirectoryItem(30087, 'tvshows&url=traktfeatured', 'tvshows.jpg', 'DefaultTVShows.png') self.addDirectoryItem(30088, 'tvshows&url=traktratings', 'tvshows.jpg', 'DefaultTVShows.png') self.addDirectoryItem(30089, 'calendar&url=progress', 'calendarsProgress.jpg', 'DefaultRecentlyAddedEpisodes.png') self.addDirectoryItem(30090, 'calendar&url=mycalendar', 'calendarsMycalendar.jpg', 'DefaultRecentlyAddedEpisodes.png') if imdbMode == True: self.addDirectoryItem(30091, 'movies&url=imdbwatchlist', 'moviesImdbwatchlist.jpg', 'DefaultMovies.png', context=(30191, 'moviesToLibrary&url=imdbwatchlist')) self.addDirectoryItem(30092, 'tvshows&url=imdbwatchlist', 'tvshowsImdbwatchlist.jpg', 'DefaultTVShows.png', context=(30191, 'tvshowsToLibrary&url=imdbwatchlist')) if traktMode == True or imdbMode == True: self.addDirectoryItem(30093, 'movieUserlists', 'movieUserlists.jpg', 'DefaultMovies.png') self.addDirectoryItem(30094, 'tvUserlists', 'tvUserlists.jpg', 'DefaultTVShows.png') self.addDirectoryItem(30095, 'movieFavourites', 'movieFavourites.jpg', 'DefaultMovies.png') self.addDirectoryItem(30096, 'episodeFavourites', 'tvFavourites.jpg', 'DefaultTVShows.png') self.addDirectoryItem(30097, 'tvFavourites', 'tvFavourites.jpg', 'DefaultTVShows.png') movie_downloads = control.setting('movie_downloads') tv_downloads = control.setting('tv_downloads') if len(control.listDir(movie_downloads)[0]) > 0 or len(control.listDir(tv_downloads)[0]) > 0: self.addDirectoryItem(30098, 'downloadNavigator', 'downloads.jpg', 'DefaultFolder.png') self.endDirectory()
def __init__(self): movie_library = os.path.join(control.transPath(control.setting('movie_library')),'') tv_library = os.path.join(control.transPath(control.setting('tv_library')),'') tv_downloads = os.path.join(control.transPath(control.setting('tv_downloads')),'') #movie_downloads = os.path.join(control.transPath(control.setting('movie_downloads')),'') if not os.path.exists(movie_library): os.makedirs(movie_library) if not os.path.exists(tv_library): os.makedirs(tv_library)
def __init__(self): self.base_link = 'http://members.easynews.com' self.user = control.setting('easynews_user') self.password = control.setting('easynews_password') self.cookie = 'chickenlicker=%s%%3A%s' % (self.user, self.password) self.moviesearch_link = '/2.0/search/solr-search/advanced?st=adv&safeO=0&sb=1&from=&ns=&fex=mkv%%2Cmp4&vc=AVC1%%2CHEVC%%2CH264%%2CH265&ac=&s1=nsubject&s1d=%%2B&s2=nrfile&s2d=%%2B&s3=dsize&s3d=%%2B&fty[]=VIDEO&spamf=1&u=1&gx=1&pby=1000&pno=1&sS=3&d1=&d1t=&d2=&d2t=&b1=&b1t=17&b2=&b2t=28&px1=&px1t=&px2=&px2t=&fps1=&fps1t=&fps2=&fps2t=&bps1=&bps1t=8&bps2=&bps2t=&hz1=&hz1t=&hz2=&hz2t=&rn1=&rn1t=&rn2=&rn2t=&gps=%s&sbj=%s' self.tvsearch_link = '/2.0/search/solr-search/advanced?st=adv&safeO=0&sb=1&from=&ns=&fil=&fex=mkv%%2Cmp4%%2Cavi&vc=&ac=&s1=nsubject&s1d=%%2B&s2=nrfile&s2d=%%2B&s3=dsize&s3d=%%2B&fty[]=VIDEO&spamf=1&u=1&gx=1&pby=1000&pno=1&sS=3&d1=&d1t=&d2=&d2t=&b1=&b1t=14&b2=&b2t=26&px1=&px1t=&px2=&px2t=&fps1=&fps1t=&fps2=&fps2t=&bps1=&bps1t=8&bps2=&bps2t=&hz1=&hz1t=&hz2=&hz2t=&rn1=&rn1t=&rn2=&rn2t=&gps=%s&sbj=%s'
def resolve(url): try: log("---1 --- %s" % control.setting('realdebrid_authorize'),xbmc.LOGNOTICE) if control.setting('realdebrid_authorize') == 'false': return log("---2 --- %s " % control.setting('realdebrid_authorize'), xbmc.LOGNOTICE) print("---3---",control.setting('realdebrid_token')) myreal = RealDebridResolver() #myreal.login() log("Mu url: %s" % url, xbmc.LOGNOTICE) myurl = myreal.get_media_url('www.real-debrid.com',url) #login_data = urllib.urlencode({'user' : user, 'pass' : password}) #login_link = 'http://real-debrid.com/ajax/login.php?%s' % login_data #result = client.source(login_link, close=False) #result = json.loads(result) #error = result['error'] #if not error == 0: raise Exception() #cookie = result['cookie'] #url = 'http://real-debrid.com/ajax/unrestrict.php?link=%s' % url #url = url.replace('filefactory.com/stream/', 'filefactory.com/file/') #result = client.source(url, cookie=cookie, close=False) #result = json.loads(result) #url = result['generated_links'][0][-1] #url = '%s|Cookie=%s' % (url, urllib.quote_plus(cookie)) return myurl except: return
def root(self): self.addDirectoryItem(30001, 'movieNavigator', 'movies.jpg', 'DefaultMovies.png') self.addDirectoryItem(30002, 'tvNavigator', 'tvshows.jpg', 'DefaultTVShows.png') self.addDirectoryItem(30003, 'channels', 'channels.jpg', 'DefaultMovies.png') self.addDirectoryItem(30004, 'myNavigator', 'myspecto.jpg', 'DefaultVideoPlaylists.png') if not control.setting('movie_widget') == '0': self.addDirectoryItem(30005, 'movieWidget', 'moviesAdded.jpg', 'DefaultRecentlyAddedMovies.png') if (traktMode == True and not control.setting('tv_alt_widget') == '0') or (traktMode == False and not control.setting('tv_widget') == '0'): #self.addDirectoryItem(30006, 'tvWidget', 'calendarsAdded.jpg', 'DefaultRecentlyAddedEpisodes.png') self.addDirectoryItem(30006, 'calendar&url=added', 'calendarsAdded.jpg', 'DefaultRecentlyAddedEpisodes.png') if not control.setting('calendar_widget') == '0': self.addDirectoryItem(30007, 'calendars', 'calendar.jpg', 'DefaultRecentlyAddedEpisodes.png') self.addDirectoryItem(30008, 'toolNavigator', 'tools.jpg', 'DefaultAddonProgram.png') self.addDirectoryItem(30009, 'searchNavigator', 'search.jpg', 'DefaultFolder.png') self.endDirectory() if ntptime.checkDate(): control.log('Error date time setup') msg = control.lang(32020).encode('utf-8') msg1 ='Go to settings, set your correct date and time'.encode('utf-8') msg = 'You have to set your clock in your tv box.'.encode('utf-8') control.dialog.ok(control.addonInfo('name'),'',msg, msg1 ) from resources.lib.libraries import cache from resources.lib.libraries import changelog
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 getSources(self, name, title, year, imdb, tmdb, tvdb, tvrage, season, episode, tvshowtitle, alter, date): sourceDict = [] for package, name, is_pkg in pkgutil.walk_packages(__path__): sourceDict.append((name, is_pkg)) sourceDict = [i[0] for i in sourceDict if i[1] == False] content = 'movie' if tvshowtitle == None else 'episode' if content == 'movie': sourceDict = [i for i in sourceDict if i.endswith(('_mv', '_mv_tv'))] try: sourceDict = [(i, control.setting(re.sub('_mv_tv$|_mv$|_tv$', '', i))) for i in sourceDict] except: sourceDict = [(i, 'true') for i in sourceDict] else: sourceDict = [i for i in sourceDict if i.endswith(('_tv', '_mv_tv'))] try: sourceDict = [(i, control.setting(re.sub('_mv_tv$|_mv$|_tv$', '', i) + '_tv')) for i in sourceDict] except: sourceDict = [(i, 'true') for i in sourceDict] global global_sources global_sources = [] threads = [] control.makeFile(control.dataPath) self.sourceFile = control.sourcescacheFile sourceDict = [i[0] for i in sourceDict if i[1] == 'true'] if content == 'movie': title = cleantitle.normalize(title) for source in sourceDict: threads.append(workers.Thread(self.getMovieSource, title, year, imdb, re.sub('_mv_tv$|_mv$|_tv$', '', source), __import__(source, globals(), locals(), [], -1).source())) else: tvshowtitle = cleantitle.normalize(tvshowtitle) season, episode = alterepisode.alterepisode().get(imdb, tmdb, tvdb, tvrage, season, episode, alter, title, date) for source in sourceDict: threads.append(workers.Thread(self.getEpisodeSource, title, year, imdb, tvdb, season, episode, tvshowtitle, date, re.sub('_mv_tv$|_mv$|_tv$', '', source), __import__(source, globals(), locals(), [], -1).source())) try: timeout = int(control.setting('sources_timeout_40')) except: timeout = 40 [i.start() for i in threads] #[i.join() for i in threads] ; self.sources = global_sources ; return self.sources for i in range(0, timeout * 2): is_alive = [x.is_alive() for x in threads] if all(x == False for x in is_alive): break time.sleep(0.5) for i in range(0, 5 * 2): is_alive = len([i for i in threads if i.is_alive() == True]) if is_alive < 10: break time.sleep(0.5) self.sources = global_sources return self.sources
def __init__(self): self.library_folder = os.path.join(control.transPath(control.setting("movie_library")), "") self.check_setting = control.setting("check_movie_link") or "false" self.library_setting = control.setting("update_library") or "true" self.dupe_setting = control.setting("check_library") or "true" self.infoDialog = False
def __init__(self): self.base_link = 'https://www.alluc.com' self.user = control.setting('alluc_user') self.password = control.setting('alluc_password') #self.download_link = '/api/search/download/?user=%s&password=%s&count=20&from=0&getmeta=0&query=%s+lang%%3Aen+host%%3A%s' #self.stream_link = '/api/search/stream/?user=%s&password=%s&count=20&from=0&getmeta=0&query=%s+lang%%3Aen+host%%3A%s' self.download_link = '/api/search/download/?user=%s&password=%s&count=100&from=0&getmeta=0&query=%s+lang%%3Aen' self.stream_link = '/api/search/stream/?user=%s&password=%s&count=100&from=0&getmeta=0&query=%s+lang%%3Aen'
def __init__(self): self.library_folder = os.path.join(control.transPath(control.setting('movie_library')),'') self.check_setting = control.setting('check_movie_link') or 'false' self.library_setting = control.setting('update_library') or 'true' self.dupe_setting = control.setting('check_library') or 'true' self.infoDialog = False
def __init__(self): self.base_link = 'http://ororo.tv' self.sign_link = 'http://ororo.tv/en/users/sign_in' self.cookie = None self.lang_cookie = 'locale=en; nl=true' self.user = control.setting('ororo_user') self.password = control.setting('ororo_password') self.post = {'user[email]': self.user, 'user[password]': self.password, 'user[remember_me]': 1}
def service(self): try: control.makeFile(control.dataPath) dbcon = database.connect(control.libcacheFile) dbcur = dbcon.cursor() dbcur.execute("CREATE TABLE IF NOT EXISTS service (""setting TEXT, ""value TEXT, ""UNIQUE(setting)"");") dbcur.execute("SELECT * FROM service WHERE setting = 'last_run'") fetch = dbcur.fetchone() if fetch == None: serviceProperty = "1970-01-01 23:59:00.000000" dbcur.execute("INSERT INTO service Values (?, ?)", ('last_run', serviceProperty)) dbcon.commit() else: serviceProperty = str(fetch[1]) dbcon.close() except: try: return dbcon.close() except: return try: control.window.setProperty(self.property, serviceProperty) except: return while (not xbmc.abortRequested): try: serviceProperty = control.window.getProperty(self.property) t1 = datetime.timedelta(hours=6) t2 = datetime.datetime.strptime(serviceProperty, '%Y-%m-%d %H:%M:%S.%f') t3 = datetime.datetime.now() check = abs(t3 - t2) > t1 if check == False: raise Exception() if (control.player.isPlaying() or control.condVisibility('Library.IsScanningVideo')): raise Exception() serviceProperty = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f') control.window.setProperty(self.property, serviceProperty) try: dbcon = database.connect(control.libcacheFile) dbcur = dbcon.cursor() dbcur.execute("CREATE TABLE IF NOT EXISTS service (""setting TEXT, ""value TEXT, ""UNIQUE(setting)"");") dbcur.execute("DELETE FROM service WHERE setting = 'last_run'") dbcur.execute("INSERT INTO service Values (?, ?)", ('last_run', serviceProperty)) dbcon.commit() dbcon.close() except: try: dbcon.close() except: pass if not control.setting('service_update') == 'true': raise Exception() info = control.setting('service_notification') or 'true' self.update(None, info=info) except: pass control.sleep(10000)
def __init__(self): self.base_link_1 = 'http://erosnow.com' self.base_link_2 = self.base_link_1 self.search_link = '/search/movies?q=%s&start=0&rows=20&cc=US' self.info_link = '/catalog/movie/%s/cc=US' self.login_link = 'https://erosnow.com/secured/dologin' self.now = datetime.datetime.now() self.user = control.setting('eros_user') self.password = control.setting('eros_pwd') self.list = []
def __init__(self): self.library_folder = os.path.join(control.transPath(control.setting("tv_library")), "") self.library_setting = control.setting("update_library") or "true" self.property = "%s_service_property" % control.addonInfo("name").lower() self.datetime = datetime.datetime.utcnow() - datetime.timedelta(hours=5) self.date = (self.datetime - datetime.timedelta(hours=24)).strftime("%Y%m%d") self.infoDialog = False
def downloads(self): movie_downloads = control.setting('movie_downloads') tv_downloads = control.setting('tv_downloads') if len(control.listDir(movie_downloads)[0]) > 0: self.addDirectoryItem(30099, movie_downloads, 'movies.jpg', 'DefaultMovies.png', isAction=False) if len(control.listDir(tv_downloads)[0]) > 0: self.addDirectoryItem(30100, tv_downloads, 'tvshows.jpg', 'DefaultTVShows.png', isAction=False) self.endDirectory()
def __init__(self): self.library_folder = os.path.join(control.transPath(control.setting('tv_library')),'') self.library_setting = control.setting('update_library') or 'true' self.property = '%s_service_property' % control.addonInfo('name').lower() self.datetime = (datetime.datetime.utcnow() - datetime.timedelta(hours = 5)) self.date = (self.datetime - datetime.timedelta(hours = 24)).strftime('%Y%m%d') self.infoDialog = False
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 get_media_url(self, host, media_id, retry=False): try: url = 'http://api.real-debrid.com/rest/1.0/unrestrict/link' headers = self.headers headers['Authorization'] = 'Bearer %s' % (control.setting('realdebrid_token')) data = {'link': media_id} myresult = client.request(url, post=data, headers=headers,output='response2') result = myresult[1] log(">>> RealDebrid res %s >>>>>> DATA: %s " % (myresult[0],myresult [1])) if myresult[0] != '200': raise ValueError(myresult[0]) except ValueError as e: log("RealDebrid ERROR %s RETRY: %s" % (e,retry)) print ("Myre",e,myresult[0]=='401',control.setting('realdebrid_refresh')) if not retry and myresult[0] == 401: if control.setting('realdebrid_refresh'): self.refresh_token() return self.get_media_url(host, media_id, retry=True) else: control.set_setting('realdebrid_client_id', '') control.set_setting('realdebrid_client_secret', '') control.set_setting('realdebrid_token', '') raise UrlResolver.ResolverError('Real Debrid Auth Failed & No Refresh Token') else: try: js_result = json.loads(e.read()) if 'error' in js_result: msg = js_result['error'] else: msg = 'Unknown Error (1)' except: msg = 'Unknown Error (2)' raise UrlResolver.ResolverError('Real Debrid Error: %s (%s)' % (msg, e.code)) except Exception as e: raise UrlResolver.ResolverError('Unexpected Exception during RD Unrestrict: %s' % (e)) else: js_result = json.loads(result) links = [] link = self.__get_link(js_result) if link is not None: links.append(link) if 'alternative' in js_result: for alt in js_result['alternative']: link = self.__get_link(alt) if link is not None: links.append(link) if len(links) == 1 or control.setting('realdebrid_autopick') == 'true': return links[0][1] elif len(links) > 1: sd = xbmcgui.Dialog() ret = sd.select('Select a Link', [link[0] for link in links]) if ret > -1: return links[ret][1] else: raise UrlResolver.ResolverError('No usable link from Real Debrid')
def checkSources(self, name, title, year, imdb, tmdb, tvdb, tvrage, season, episode, tvshowtitle, alter, date): sourceDict = [] for package, name, is_pkg in pkgutil.walk_packages(__path__): sourceDict.append((name, is_pkg)) sourceDict = [i[0] for i in sourceDict if i[1] == False] content = 'movie' if tvshowtitle == None else 'episode' if content == 'movie': sourceDict = [i for i in sourceDict if i.endswith(('_mv', '_mv_tv'))] try: sourceDict = [(i, control.setting(re.sub('_mv_tv$|_mv$|_tv$', '', i))) for i in sourceDict] except: sourceDict = [(i, 'true') for i in sourceDict] else: sourceDict = [i for i in sourceDict if i.endswith(('_tv', '_mv_tv'))] try: sourceDict = [(i, control.setting(re.sub('_mv_tv$|_mv$|_tv$', '', i) + '_tv')) for i in sourceDict] except: sourceDict = [(i, 'true') for i in sourceDict] threads = [] control.makeFile(control.dataPath) self.sourceFile = control.sourcescacheFile sourceDict = [i[0] for i in sourceDict if i[1] == 'true'] if content == 'movie': title = cleantitle.normalize(title) for source in sourceDict: threads.append(workers.Thread(self.getMovieSource, title, year, imdb, re.sub('_mv_tv$|_mv$|_tv$', '', source), __import__(source, globals(), locals(), [], -1).source())) else: tvshowtitle = cleantitle.normalize(tvshowtitle) season, episode = alterepisode.alterepisode().get(imdb, tmdb, tvdb, tvrage, season, episode, alter, title, date) for source in sourceDict: #control.log("SOURCE S2 %s" % source) threads.append(workers.Thread(self.getEpisodeSource, title, year, imdb, tvdb, season, episode, tvshowtitle, date, re.sub('_mv_tv$|_mv$|_tv$', '', source), __import__(source, globals(), locals(), [], -1).source())) try: timeout = int(control.setting('sources_timeout_40')) except: timeout = 40 [i.start() for i in threads] for i in range(0, timeout * 2): try: if xbmc.abortRequested == True: return sys.exit() if len(self.sources) >= 10: break is_alive = [x.is_alive() for x in threads] if all(x == False for x in is_alive): break time.sleep(0.5) except: pass if len(self.sources) >= 10: return True else: return False
def debridCredentials(): return { "realdebrid": { "id": control.setting("realdebrid_id"), "secret": control.setting("realdebrid_secret"), "token": control.setting("realdebrid_token"), "refresh": control.setting("realdebrid_refresh"), }, "premiumize": {"user": control.setting("premiumize_user"), "pass": control.setting("premiumize_password")}, "alldebrid": {"user": control.setting("alldebrid_user"), "pass": control.setting("alldebrid_password")}, "rpnet": {"user": control.setting("rpnet_user"), "pass": control.setting("rpnet_password")}, }
def __init__(self): self.library_folder = os.path.join(control.transPath(control.setting('tv_library')),'') self.check_setting = control.setting('check_episode_link') or 'false' self.library_setting = control.setting('update_library') or 'true' self.dupe_setting = control.setting('check_library') or 'true' self.datetime = (datetime.datetime.utcnow() - datetime.timedelta(hours = 5)) self.date = (self.datetime - datetime.timedelta(hours = 24)).strftime('%Y%m%d') self.infoDialog = False self.block = False
def __init__(self): self.list = [] self.tmdb_link = 'http://api.themoviedb.org' self.trakt_link = 'http://api-v2launch.trakt.tv' self.imdb_link = 'http://www.imdb.com' self.tmdb_key = base64.urlsafe_b64decode('NTc5ODNlMzFmYjQzNWRmNGRmNzdhZmI4NTQ3NDBlYTk=') self.tvdb_key = base64.urlsafe_b64decode('MUQ2MkYyRjkwMDMwQzQ0NA==') self.datetime = (datetime.datetime.utcnow() - datetime.timedelta(hours = 5)) self.today_date = (self.datetime).strftime('%Y-%m-%d') self.month_date = (self.datetime - datetime.timedelta(days = 30)).strftime('%Y-%m-%d') self.year_date = (self.datetime - datetime.timedelta(days = 365)).strftime('%Y-%m-%d') self.trakt_user = control.setting('trakt_user') self.imdb_user = control.setting('imdb_user').replace('ur', '') self.info_lang = control.setting('infoLang') or 'en' self.tmdb_info_link = 'http://api.themoviedb.org/3/tv/%s?api_key=%s&language=%s&append_to_response=credits,content_ratings,external_ids' % ('%s', self.tmdb_key, self.info_lang) self.tvdb_info_link = 'http://thetvdb.com/api/%s/series/%s/%s.xml' % (self.tvdb_key, '%s', self.info_lang) self.tmdb_by_imdb = 'http://api.themoviedb.org/3/find/%s?api_key=%s&external_source=imdb_id' % ('%s', self.tmdb_key) self.tvdb_by_imdb = 'http://thetvdb.com/api/GetSeriesByRemoteID.php?imdbid=%s' self.imdb_by_query = 'http://www.omdbapi.com/?t=%s&y=%s' self.tmdb_image = 'http://image.tmdb.org/t/p/original' self.tmdb_poster = 'http://image.tmdb.org/t/p/w500' self.tvdb_image = 'http://thetvdb.com/banners/' self.persons_link = 'http://api.themoviedb.org/3/search/person?api_key=%s&query=%s&include_adult=false&page=1' % (self.tmdb_key, '%s') self.genres_link = 'http://api.themoviedb.org/3/genre/tv/list?api_key=%s&language=%s' % (self.tmdb_key, self.info_lang) self.popular_link = 'http://api.themoviedb.org/3/tv/popular?api_key=%s&page=1' self.airing_link = 'http://api.themoviedb.org/3/tv/airing_today?api_key=%s&page=1' self.premiere_link = 'http://api.themoviedb.org/3/discover/tv?api_key=%s&first_air_date.gte=%s&first_air_date.lte=%s&page=1' % ('%s', self.year_date, self.today_date) self.active_link = 'http://api.themoviedb.org/3/tv/on_the_air?api_key=%s&page=1' self.rating_link = 'http://api.themoviedb.org/3/tv/top_rated?api_key=%s&page=1' self.views_link = 'http://api.themoviedb.org/3/discover/tv?api_key=%s&vote_count.gte=10&sort_by=vote_average.desc&page=1' self.person_link = 'http://api.themoviedb.org/3/person/%s?api_key=%s&append_to_response=tv_credits' self.genre_link = 'http://api.themoviedb.org/3/discover/tv?api_key=%s&with_genres=%s&air_date.gte=%s&air_date.lte=%s&page=1' % ('%s', '%s', self.year_date, self.today_date) self.network_link = 'http://api.themoviedb.org/3/discover/tv?api_key=%s&with_networks=%s&air_date.gte=%s&air_date.lte=%s&page=1' % ('%s', '%s', self.year_date, self.today_date) self.year_link = 'http://api.themoviedb.org/3/discover/tv?api_key=%s&first_air_date_year=%s&air_date.lte=%s&page=1' % ('%s', '%s', self.today_date) self.trending_link = 'http://api-v2launch.trakt.tv/shows/trending?limit=20&page=1' self.search_link = 'https://api-v2launch.trakt.tv/search?type=show&query=%s' self.traktlists_link = 'http://api-v2launch.trakt.tv/users/%s/lists' % self.trakt_user self.traktlist_link = 'http://api-v2launch.trakt.tv/users/%s/lists/%s/items' % (self.trakt_user, '%s') self.traktcollection_link = 'http://api-v2launch.trakt.tv/users/%s/collection/shows' % self.trakt_user self.traktwatchlist_link = 'http://api-v2launch.trakt.tv/users/%s/watchlist/shows' % self.trakt_user self.traktfeatured_link = 'http://api-v2launch.trakt.tv/recommendations/shows?limit=20' self.traktratings_link = 'https://api-v2launch.trakt.tv/users/%s/ratings/shows' % self.trakt_user self.imdblists_link = 'http://www.imdb.com/user/ur%s/lists?tab=all&sort=modified:desc&filter=titles' % self.imdb_user self.imdblist_link = 'http://www.imdb.com/list/%s/?view=detail&sort=title:asc&title_type=tv_series,mini_series&start=1' self.imdbwatchlist_link = 'http://www.imdb.com/user/ur%s/watchlist' % self.imdb_user
def __init__(self): self.library_folder = os.path.join(control.transPath(control.setting("tv_library")), "") self.version = control.version() self.check_setting = control.setting("check_episode_link") or "false" self.library_setting = control.setting("update_library") or "true" self.dupe_setting = control.setting("check_library") or "true" self.datetime = datetime.datetime.utcnow() - datetime.timedelta(hours=5) self.date = (self.datetime - datetime.timedelta(hours=24)).strftime("%Y%m%d") self.infoDialog = False self.block = False
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 alterSources(self, url, meta): try: setting = control.setting('autoplay') if setting == 'false': url += '&url=direct://' else: url += '&url=dialog://' meta = json.loads(meta) 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 playlist = control.playlist playlist.clear() item = control.item(label='', iconImage=thumb, 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) item.setProperty('Video', 'true') item.setProperty('IsPlayable', 'true') control.player.play(url, item) except: pass
def sourcesDirect(self): self.sources = [i for i in self.sources if not i["source"] in self.hostcapDict] self.sources = [ i for i in self.sources if not ( i["quality"] in ["1080p", "HD"] and i["source"] in self.hosthdDict and not i["source"] in self.rdDict + self.pzDict ) ] self.sources = [i for i in self.sources if not i["source"] in ["furk", "vk"]] if control.setting("playback_auto_sd") == "true": self.sources = [i for i in self.sources if not i["quality"] in ["1080p", "HD"]] u = None for i in self.sources: try: url = self.sourcesResolve(i["url"], i["provider"]) if url == None: raise Exception() if u == None: u = url self.selectedSource = i["label"] return url except: pass return u
def getSources(self, name, title, year, imdb, tmdb, tvdb, tvrage, season, episode, tvshowtitle, alter, date, meta=None): sourceDict = [] for package, name, is_pkg in pkgutil.walk_packages(__path__): sourceDict.append((name, is_pkg)) sourceDict = [i[0] for i in sourceDict if i[1] == False] if tvshowtitle == None and title == None: content = 'live' else: content = 'movie' if tvshowtitle == None else 'episode' if content == 'movie': sourceDict = [i for i in sourceDict if i.endswith(('_mv', '_mv_tv'))] try: sourceDict = [(i, control.setting(re.sub('_mv_tv$|_mv$|_tv$', '', i))) for i in sourceDict] except: sourceDict = [(i, 'true') for i in sourceDict] elif content == 'episode': sourceDict = [i for i in sourceDict if i.endswith(('_tv', '_mv_tv'))] #try: sourceDict = [(i, control.setting(re.sub('_mv_tv$|_mv$|_tv$', '', i) + '_tv')) for i in sourceDict] try: sourceDict = [(i, control.setting(re.sub('_mv_tv$|_mv$|_tv$', '', i))) for i in sourceDict] except: sourceDict = [(i, 'true') for i in sourceDict] elif content == 'live': sourceDict = [i for i in sourceDict if i.endswith('_live')] try: sourceDict = [(i, control.setting(re.sub('_live$', '', i))) for i in sourceDict] except: sourceDict = [(i, 'true') for i in sourceDict] threads = [] control.makeFile(control.dataPath) self.sourceFile = control.sourcescacheFile sourceDict = [i[0] for i in sourceDict if i[1] == 'true'] if content == 'movie': title = cleantitle.normalize(title) for source in sourceDict: threads.append(workers.Thread(self.getMovieSource, title, year, imdb, re.sub('_mv_tv$|_mv$|_tv$', '', source), __import__(source, globals(), locals(), [], -1).source())) elif content == 'episode': tvshowtitle = cleantitle.normalize(tvshowtitle) season, episode = alterepisode.alterepisode().get(imdb, tmdb, tvdb, tvrage, season, episode, alter, title, date) for source in sourceDict: threads.append(workers.Thread(self.getEpisodeSource, title, year, imdb, tvdb, season, episode, tvshowtitle, date, re.sub('_mv_tv$|_mv$|_tv$', '', source), __import__(source, globals(), locals(), [], -1).source(), meta)) elif content == 'live': for source in sourceDict:threads.append(workers.Thread(self.getLiveSource,re.sub('_live$', '', source), __import__(source, globals(), locals(), [], -1).source())) try: timeout = int(control.setting('sources_timeout_40')) except: timeout = 40 [i.start() for i in threads] control.idle() sourceLabel = [re.sub('_mv_tv$|_mv$|_tv$|_live$', '', i) for i in sourceDict] sourceLabel = [re.sub('v\d+$', '', i).upper() for i in sourceLabel] self.progressDialog = control.progressDialog self.progressDialog.create(control.addonInfo('name'), '') self.progressDialog.update(0) string1 = control.lang(30512).encode('utf-8') string2 = control.lang(30513).encode('utf-8') string3 = control.lang(30514).encode('utf-8') for i in range(0, timeout * 2): try: if xbmc.abortRequested == True: return sys.exit() try: info = [sourceLabel[int(re.sub('[^0-9]', '', str(x.getName()))) - 1] for x in threads if x.is_alive() == True] except: info = [] if len(info) > 5: info = len(info) self.progressDialog.update(int((100 / float(len(threads))) * len([x for x in threads if x.is_alive() == False])), str('%s: %s %s' % (string1, int(i * 0.5), string2)), str('%s: %s' % (string3, str(info).translate(None, "[]'")))) if self.progressDialog.iscanceled(): break is_alive = [x.is_alive() for x in threads] if all(x == False for x in is_alive): break time.sleep(0.5) except: pass self.progressDialog.close() return self.sources
def getTraktCredentialsInfo(): user = control.setting('trakt.user').strip() token = control.setting('trakt.token') refresh = control.setting('trakt.refresh') if (user == '' or token == '' or refresh == ''): return False return True
def cachesyncTVShows(timeout=0): indicators = cache.get(syncTVShows, timeout, control.setting('trakt.user').strip(), table='trakt') return indicators
def timeoutsyncTVShows(): timeout = cache.timeout(syncTVShows, control.setting('trakt.user').strip(), table='trakt') return timeout
import os,sys,urlparse import time from resources.lib.libraries import control artPath = control.artPath() addonFanart = control.addonFanart() try: action = dict(urlparse.parse_qsl(sys.argv[2].replace('?','')))['action'] except: action = None traktMode = False if control.setting('trakt.user') == '' else True imdbMode = False if control.setting('imdb_user') == '' else True sysaddon = sys.argv[0] class navigator: def __init__(self): movie_library = os.path.join(control.transPath(control.setting('movie_library')),'') tv_library = os.path.join(control.transPath(control.setting('tv_library')),'') tv_downloads = os.path.join(control.transPath(control.setting('tv_downloads')),'') movie_downloads = os.path.join(control.transPath(control.setting('movie_downloads')),'')
def sourcesFilter(self): self.sourcesReset() try: customhdDict = [control.setting('hosthd50001'), control.setting('hosthd50002'), control.setting('hosthd50003'), control.setting('hosthd50004'), control.setting('hosthd50005'), control.setting('hosthd50006'), control.setting('hosthd50007'), control.setting('hosthd50008'), control.setting('hosthd50009'), control.setting('hosthd50010'), control.setting('hosthd50011'), control.setting('hosthd50012'), control.setting('hosthd50013'), control.setting('hosthd50014'), control.setting('hosthd50015'), control.setting('hosthd50016'), control.setting('hosthd50017'), control.setting('hosthd50018'), control.setting('hosthd50019'), control.setting('hosthd50020')] except: customhdDict = [] try: customsdDict = [control.setting('host50001'), control.setting('host50002'), control.setting('host50003'), control.setting('host50004'), control.setting('host50005'), control.setting('host50006'), control.setting('host50007'), control.setting('host50008'), control.setting('host50009'), control.setting('host50010'), control.setting('host50011'), control.setting('host50012'), control.setting('host50013'), control.setting('host50014'), control.setting('host50015'), control.setting('host50016'), control.setting('host50017'), control.setting('host50018'), control.setting('host50019'), control.setting('host50020')] except: customsdDict = [] hd_rank = [] hd_rank += [i for i in self.rdDict if i in self.hostprDict + self.hosthdDict] hd_rank += [i for i in self.pzDict if i in self.hostprDict + self.hosthdDict] hd_rank += customhdDict hd_rank += [i['source'] for i in self.sources if i['quality'] in ['1080p', 'HD'] and not i['source'] in customhdDict + self.hostprDict + self.hosthdDict] hd_rank += self.hosthdDict hd_rank = [i.lower() for i in hd_rank] hd_rank = [x for y,x in enumerate(hd_rank) if x not in hd_rank[:y]] sd_rank = [] sd_rank += [i for i in self.rdDict if i in self.hostprDict + self.hosthqDict] sd_rank += [i for i in self.pzDict if i in self.hostprDict + self.hosthqDict] sd_rank += customsdDict sd_rank += [i['source'] for i in self.sources if i['quality'] == 'SD' and not i['source'] in customsdDict + self.hostprDict + self.hosthqDict + self.hostmqDict + self.hostlqDict] sd_rank += self.hosthqDict + self.hostmqDict + self.hostlqDict sd_rank = [i.lower() for i in sd_rank] sd_rank = [x for y,x in enumerate(sd_rank) if x not in sd_rank[:y]] for i in range(len(self.sources)): self.sources[i]['source'] = self.sources[i]['source'].lower() self.sources = sorted(self.sources, key=lambda k: k['source']) filter = [] for host in hd_rank: filter += [i for i in self.sources if i['quality'] == '1080p' and i['source'] == host] for host in hd_rank: filter += [i for i in self.sources if i['quality'] == 'HD' and i['source'] == host] for host in sd_rank: filter += [i for i in self.sources if i['quality'] == 'SD' and i['source'] == host] if len(filter) < 10: filter += [i for i in self.sources if i['quality'] == 'SCR'] if len(filter) < 10: filter += [i for i in self.sources if i['quality'] == 'CAM'] self.sources = filter try: playback_quality = control.setting('playback_quality') except: playback_quality = '0' if playback_quality == '1': self.sources = [i for i in self.sources if not i['quality'] == '1080p'] elif playback_quality == '2': self.sources = [i for i in self.sources if not i['quality'] in ['1080p', 'HD']] elif playback_quality == '3': self.sources = [i for i in self.sources if not i['quality'] in ['1080p', 'HD'] and i['source'] in self.hostmqDict + self.hostlqDict] elif playback_quality == '4': self.sources = [i for i in self.sources if not i['quality'] in ['1080p', 'HD'] and i['source'] in self.hostlqDict] try: playback_captcha = control.setting('playback_captcha_hosts') except: playback_captcha = 'false' try: playback_1080p = control.setting('playback_1080p_hosts') except: playback_1080p = 'true' try: playback_720p = control.setting('playback_720p_hosts') except: playback_720p = 'true' if playback_captcha == 'false': self.sources = [i for i in self.sources if not i['source'] in self.hostcapDict] if playback_1080p == 'false': self.sources = [i for i in self.sources if not (i['quality'] == '1080p' and i['source'] in self.hosthdDict and not i['source'] in self.rdDict + self.pzDict)] if playback_720p == 'false': self.sources = [i for i in self.sources if not (i['quality'] == 'HD' and i['source'] in self.hosthdDict and not i['source'] in self.rdDict + self.pzDict)] for i in range(len(self.sources)): #control.log("------------------------------ %s | %s " % (self.sources[i]['source'], self.sources[i])) s = self.sources[i]['source'].lower() p = self.sources[i]['provider'] p = re.sub('v\d*$', '', p) q = self.sources[i]['quality'] if q == 'SD' and s in self.hostmqDict: q = 'MQ' elif q == 'SD' and s in self.hostlqDict: q = 'LQ' elif q == 'SD': q = 'HQ' try: d = self.sources[i]['info'] except: d = '' if not d == '': d = ' | [I]%s [/I]' % d if s in self.rdDict: label = '%02d | [B]realdebrid[/B] | ' % int(i+1) elif s in self.pzDict: label = '%02d | [B]premiumize[/B] | ' % int(i+1) else: label = '%02d | [B]%s[/B] | ' % (int(i+1), p) if q in ['1080p', 'HD']: label += '%s%s | [B][I]%s [/I][/B]' % (s, d, q) else: label += '%s%s | [I]%s [/I]' % (s, d, q) self.sources[i]['label'] = label.upper() return self.sources
def get(name, imdb, season, episode): try: langs = [] try: try: langs = langDict[control.setting('sublang1')].split(',') except: langs.append(langDict[control.setting('sublang1')]) except: pass try: try: langs = langs + langDict[control.setting('sublang2')].split(',') except: langs.append(langDict[control.setting('sublang2')]) except: pass try: subLang = xbmc.Player().getSubtitles() except: subLang = '' if subLang == langs[0]: raise Exception() server = xmlrpclib.Server('http://api.opensubtitles.org/xml-rpc', verbose=0) token = server.LogIn('', '', 'en', 'XBMC_Subtitles_v1')['token'] sublanguageid = ','.join(langs) ; imdbid = re.sub('[^0-9]', '', imdb) if not (season == '' or episode == ''): result = server.SearchSubtitles(token, [{'sublanguageid': sublanguageid, 'imdbid': imdbid, 'season': season, 'episode': episode}])['data'] fmt = ['hdtv'] else: result = server.SearchSubtitles(token, [{'sublanguageid': sublanguageid, 'imdbid': imdbid}])['data'] try: vidPath = xbmc.Player().getPlayingFile() except: vidPath = '' fmt = re.split('\.|\(|\)|\[|\]|\s|\-', vidPath) fmt = [i.lower() for i in fmt] fmt = [i for i in fmt if i in quality] filter = [] result = [i for i in result if i['SubSumCD'] == '1'] for lang in langs: filter += [i for i in result if i['SubLanguageID'] == lang and any(x in i['MovieReleaseName'].lower() for x in fmt)] filter += [i for i in result if i['SubLanguageID'] == lang and any(x in i['MovieReleaseName'].lower() for x in quality)] filter += [i for i in result if i['SubLanguageID'] == lang] try: lang = xbmc.convertLanguage(filter[0]['SubLanguageID'], xbmc.ISO_639_1) except: lang = filter[0]['SubLanguageID'] content = [filter[0]['IDSubtitleFile'],] content = server.DownloadSubtitles(token, content) content = base64.b64decode(content['data'][0]['data']) content = str(zlib.decompressobj(16+zlib.MAX_WBITS).decompress(content)) subtitle = xbmc.translatePath('special://temp/') subtitle = os.path.join(subtitle, 'TemporarySubs.%s.srt' % lang) codepage = codePageDict.get(lang, '') if codepage and control.setting('autoconvert_utf8') == 'true': try: content_encoded = codecs.decode(content, codepage) content = codecs.encode(content_encoded, 'utf-8') except: pass file = control.openFile(subtitle, 'w') file.write(str(content)) file.close() xbmc.sleep(1000) xbmc.Player().setSubtitles(subtitle) except: pass
def get(name, imdb, season, episode): try: langs = [] try: try: langs = langDict[control.setting('sublang1')].split(',') except: langs.append(langDict[control.setting('sublang1')]) except: pass try: try: langs = langs + langDict[control.setting('sublang2')].split( ',') except: langs.append(langDict[control.setting('sublang2')]) except: pass try: subLang = xbmc.Player().getSubtitles() except: subLang = '' if subLang == langs[0]: raise Exception() control.log('SUBS XXXXXX:%s' % name) server = xmlrpclib.Server('http://api.opensubtitles.org/xml-rpc', verbose=0) data = server.LogIn( control.setting('OSuser').strip(), control.setting('OSpass').strip(), 'en', subsversion) token = data['token'] if data['status'] != '200 OK': control.log("SUBS: Token %s, Status: %s" % (data['status'], data)) control.infoDialog('Open Subtitles Error: ' + str(data['status']), "Open Subtitles ERROR", time=6000) #control.dialog.ok(control.addonInfo('name'), str('Open Subtitles error[CR]Check login and password in settings[CR][CR]Error: %s'% data['status']), '') sublanguageid = ','.join(langs) imdbid = re.sub('[^0-9]', '', imdb) if not (season == '' or episode == ''): result = server.SearchSubtitles(token, [{ 'sublanguageid': sublanguageid, 'imdbid': imdbid, 'season': season, 'episode': episode }])['data'] fmt = ['hdtv'] else: result = server.SearchSubtitles(token, [{ 'sublanguageid': sublanguageid, 'imdbid': imdbid }])['data'] try: vidPath = xbmc.Player().getPlayingFile() except: vidPath = '' fmt = re.split('\.|\(|\)|\[|\]|\s|\-', vidPath) fmt = [i.lower() for i in fmt] fmt = [i for i in fmt if i in quality] filter = [] result = [i for i in result if i['SubSumCD'] == '1'] for lang in langs: filter += [ i for i in result if i['SubLanguageID'] == lang and any( x in i['MovieReleaseName'].lower() for x in fmt) ] filter += [ i for i in result if i['SubLanguageID'] == lang and any( x in i['MovieReleaseName'].lower() for x in quality) ] filter += [i for i in result if i['SubLanguageID'] == lang] try: lang = xbmc.convertLanguage(filter[0]['SubLanguageID'], xbmc.ISO_639_1) except: lang = filter[0]['SubLanguageID'] content = [ filter[0]['IDSubtitleFile'], ] content = server.DownloadSubtitles(token, content) content = base64.b64decode(content['data'][0]['data']) content = str( zlib.decompressobj(16 + zlib.MAX_WBITS).decompress(content)) subtitle = xbmc.translatePath('special://temp/') subtitle = os.path.join(subtitle, 'TemporarySubs.%s.srt' % lang) codepage = codePageDict.get(lang, '') if codepage and control.setting('autoconvert_utf8') == 'true': try: content_encoded = codecs.decode(content, codepage) content = codecs.encode(content_encoded, 'utf-8') except: pass file = control.openFile(subtitle, 'w') file.write(str(content)) file.close() xbmc.sleep(1000) xbmc.Player().setSubtitles(subtitle) except Exception as e: control.log('SUBS: Error %s' % e) pass
def decode(url, python_dir=None, debug=False, ssl=True, js='openload.js'): output = "" try: url_encode = base64.b64encode(url) PHANTOMJS_PATH = None PHANTOMJS_PLUGIN_CHANNEL_PATH = None PHANTOMJS_USER_DEFINED_PATH = control.setting('control_phantomjs_path') if PHANTOMJS_USER_DEFINED_PATH != None and len( PHANTOMJS_USER_DEFINED_PATH) > 0: bool, md5 = checkBinaryPresence2(PHANTOMJS_USER_DEFINED_PATH) if bool == True: PHANTOMJS_PATH = PHANTOMJS_USER_DEFINED_PATH PHANTOMJS_PLUGIN_CHANNEL_PATH = os.path.dirname( os.path.abspath(__file__)) if PHANTOMJS_PATH == None: PHANTOMJS_PATH = PHANTOMJS_PLUGIN_CHANNEL_PATH if python_dir == None: python_dir = "" if debug: if sys.platform == "win32": file_cmd = [ os.path.join(PHANTOMJS_PATH, 'phantomjs'), os.path.join(PHANTOMJS_PLUGIN_CHANNEL_PATH, js), url, '-debug true' ] elif sys.platform == "darwin": file_cmd = [ os.path.join(PHANTOMJS_PATH, 'phantomjs'), os.path.join(PHANTOMJS_PLUGIN_CHANNEL_PATH, js), url ] else: file_cmd = [ os.path.join(PHANTOMJS_PATH, 'phantomjs'), os.path.join(PHANTOMJS_PLUGIN_CHANNEL_PATH, js), url ] else: if sys.platform == "win32": file_cmd = [ os.path.join(PHANTOMJS_PATH, 'phantomjs'), os.path.join(PHANTOMJS_PLUGIN_CHANNEL_PATH, js), url ] elif sys.platform == "darwin": file_cmd = [ os.path.join(PHANTOMJS_PATH, 'phantomjs'), os.path.join(PHANTOMJS_PLUGIN_CHANNEL_PATH, js), url ] else: file_cmd = [ os.path.join(PHANTOMJS_PATH, 'phantomjs'), os.path.join(PHANTOMJS_PLUGIN_CHANNEL_PATH, js), url ] if ssl == True: file_cmd.insert(1, '--ssl-protocol=any') if sys.platform == "darwin": #print file_cmd PROCESSES[url_encode] = { 'url': url, 'ts': time.time(), 'Completed': False } process = subprocess.Popen(file_cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, close_fds=True) PROCESSES[url_encode].update({'process': process}) ret = process.wait() output = process.stdout.read() #PROCESSES[url_encode].update({'output':output}) else: #print file_cmd PROCESSES[url_encode] = { 'url': url, 'ts': time.time(), 'Completed': False } process = subprocess.Popen(file_cmd, shell=False, cwd=PHANTOMJS_PLUGIN_CHANNEL_PATH, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) PROCESSES[url_encode].update({'process': process}) ret = process.wait() output = process.stdout.read() #PROCESSES[url_encode].update({'output':output}) #print output PROCESSES[url_encode].update({'output': output}) if 'ERROR' in output: raise Exception(output) if len(output) == 0: raise Exception('Empty output received !') if js == 'openload.js': #print "1: %s" % output output = re.findall(r'https://openload.co/stream/.*', output)[0] #print "2: %s" % output output = output.strip().replace('\n', '').encode('utf8').decode('ascii') #print "3: %s" % output PROCESSES[url_encode].update({'Completed': True}) if 'http' in output: return output, True return output, False except Exception as err: log(type='ERROR', err="%s > %s > %s" % (str(err), str(output), str(file_cmd))) return str(err), False
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' import re, os, sys, urllib, urllib2, urlparse, time, threading from resources.lib.libraries import control from resources.lib.libraries import cache import pyxbmct.addonwindow as pyxbmct downloadPath = control.setting('downloadPath') property = control.addonInfo('id') + '.downloader' def downloader(): thumb = control.addonThumb() fanart = control.addonFanart() status = control.window.getProperty(property + '.status') if not downloadPath == '': item = control.item('[COLOR FF00b8ff]Downloads[/COLOR]', iconImage=thumb, thumbnailImage=thumb) item.addContextMenuItems([], replaceItems=True) item.setProperty('fanart_image', fanart)
def specto(self): if traktMode == True: self.addDirectoryItem( 30081, 'movies&url=traktcollection', 'moviesTraktcollection.jpg', 'DefaultMovies.png', context=(30191, 'moviesToLibrary&url=traktcollection')) self.addDirectoryItem( 30082, 'movies&url=traktwatchlist', 'moviesTraktwatchlist.jpg', 'DefaultMovies.png', context=(30191, 'moviesToLibrary&url=traktwatchlist')) self.addDirectoryItem(30083, 'movies&url=traktfeatured', 'movies.jpg', 'DefaultMovies.png') #self.addDirectoryItem(30084, 'movies&url=traktratings', 'movies.jpg', 'DefaultMovies.png') self.addDirectoryItem( 30085, 'tvshows&url=traktcollection', 'tvshowsTraktcollection.jpg', 'DefaultTVShows.png', context=(30191, 'tvshowsToLibrary&url=traktcollection')) self.addDirectoryItem( 30086, 'tvshows&url=traktwatchlist', 'tvshowsTraktwatchlist.jpg', 'DefaultTVShows.png', context=(30191, 'tvshowsToLibrary&url=traktwatchlist')) self.addDirectoryItem(30087, 'tvshows&url=traktfeatured', 'tvshows.jpg', 'DefaultTVShows.png') #self.addDirectoryItem(30088, 'tvshows&url=traktratings', 'tvshows.jpg', 'DefaultTVShows.png') self.addDirectoryItem(30089, 'calendar&url=progress', 'calendarsProgress.jpg', 'DefaultRecentlyAddedEpisodes.png') self.addDirectoryItem(30090, 'calendar&url=mycalendar', 'calendarsMycalendar.jpg', 'DefaultRecentlyAddedEpisodes.png') if imdbMode == True: self.addDirectoryItem( 30091, 'movies&url=imdbwatchlist', 'moviesImdbwatchlist.jpg', 'DefaultMovies.png', context=(30191, 'moviesToLibrary&url=imdbwatchlist')) self.addDirectoryItem( 30092, 'tvshows&url=imdbwatchlist', 'tvshowsImdbwatchlist.jpg', 'DefaultTVShows.png', context=(30191, 'tvshowsToLibrary&url=imdbwatchlist')) if traktMode == True or imdbMode == True: self.addDirectoryItem(30093, 'movieUserlists', 'movieUserlists.jpg', 'DefaultMovies.png') self.addDirectoryItem(30094, 'tvUserlists', 'tvUserlists.jpg', 'DefaultTVShows.png') self.addDirectoryItem(30095, 'movieFavourites', 'movieFavourites.jpg', 'DefaultMovies.png') self.addDirectoryItem(30096, 'episodeFavourites', 'tvFavourites.jpg', 'DefaultTVShows.png') self.addDirectoryItem(30097, 'tvFavourites', 'tvFavourites.jpg', 'DefaultTVShows.png') movie_downloads = control.setting('movie_downloads') tv_downloads = control.setting('tv_downloads') if len(control.listDir(movie_downloads)[0]) > 0 or len( control.listDir(tv_downloads)[0]) > 0: self.addDirectoryItem(30098, 'downloadNavigator', 'downloads.jpg', 'DefaultFolder.png') self.endDirectory()
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 if content == 'live': items = json.loads(source) source, quality = items[0]['source'], items[0]['quality'] meta = items[0]['meta'] else : 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]) 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.0) for x in range(3600): 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.0) 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: client.printException('') pass try: self.progressDialog.close() except: pass raise Exception() except: control.infoDialog(control.lang(30501).encode('utf-8')) client.printException('sources.playItem(content=[%s], name=[%s], year=[%s], imdb=[%s], tvdb=[%s], source=[%s])' % (content, name, year, imdb, tvdb, source)) pass
def getWizjaCredentialsInfo(): user = control.setting('wizja.user').strip() password = control.setting('wizja.pass') if (user == '' or password == ''): return False return True
def channelDirectory(self, items): if items == None or len(items) == 0: return playbackMenu = control.lang(30292).encode('utf-8') if control.setting( 'autoplay') == 'true' else control.lang(30291).encode('utf-8') addonPoster, addonBanner = control.addonPoster(), control.addonBanner() addonFanart = control.addonFanart() sysaddon = sys.argv[0] for i in items: try: label = "[B]%s[/B] : %s" % (i['channel'].upper(), i['name']) sysname = urllib.quote_plus(i['name']) systitle = urllib.quote_plus(i['title']) imdb, tmdb, year = i['imdb'], '0', i['year'] poster, banner = i['poster'], i['poster'] if poster == '0': poster = addonPoster if banner == '0' and poster == '0': banner = addonBanner elif banner == '0': banner = poster meta = dict((k, v) for k, v in i.iteritems() if not v == '0') meta.update({ 'trailer': '%s?action=trailer&name=%s' % (sysaddon, sysname) }) if i['duration'] == '0': meta.update({'duration': '120'}) try: meta.update({'duration': str(int(meta['duration']) * 60)}) except: pass sysmeta = urllib.quote_plus(json.dumps(meta)) url = '%s?action=play&name=%s&title=%s&year=%s&imdb=%s&tmdb=%s&meta=%s&t=%s' % ( sysaddon, sysname, systitle, year, imdb, tmdb, sysmeta, self.systime) sysurl = urllib.quote_plus(url) cm = [] cm.append((playbackMenu, 'RunPlugin(%s?action=alterSources&url=%s&meta=%s)' % (sysaddon, sysurl, sysmeta))) cm.append( (control.lang(30293).encode('utf-8'), 'Action(Info)')) cm.append((control.lang(30294).encode('utf-8'), 'RunPlugin(%s?action=refresh)' % (sysaddon))) cm.append((control.lang(30295).encode('utf-8'), 'RunPlugin(%s?action=openSettings)' % (sysaddon))) cm.append((control.lang(30296).encode('utf-8'), 'RunPlugin(%s?action=openPlaylist)' % (sysaddon))) item = control.item(label=label, iconImage=poster, thumbnailImage=poster) try: item.setArt({'poster': poster, 'banner': banner}) except: pass if not addonFanart == None: item.setProperty('Fanart_Image', addonFanart) item.setInfo(type='Video', infoLabels=meta) item.setProperty('Video', 'true') #item.setProperty('IsPlayable', 'true') item.addContextMenuItems(cm, replaceItems=True) control.addItem(handle=int(sys.argv[1]), url=url, listitem=item, isFolder=False) except: pass control.content(int(sys.argv[1]), 'movies') control.directory(int(sys.argv[1]), cacheToDisc=True)
def checkSources(self, name, title, year, imdb, tmdb, tvdb, tvrage, season, episode, tvshowtitle, alter, date): sourceDict = [] for package, name, is_pkg in pkgutil.walk_packages(__path__): sourceDict.append((name, is_pkg)) sourceDict = [i[0] for i in sourceDict if i[1] == False] content = 'movie' if tvshowtitle == None else 'episode' if content == 'movie': sourceDict = [ i for i in sourceDict if i.endswith(('_mv', '_mv_tv')) ] try: sourceDict = [ (i, control.setting(re.sub('_mv_tv$|_mv$|_tv$', '', i))) for i in sourceDict ] except: sourceDict = [(i, 'true') for i in sourceDict] else: sourceDict = [ i for i in sourceDict if i.endswith(('_tv', '_mv_tv')) ] try: sourceDict = [(i, control.setting( re.sub('_mv_tv$|_mv$|_tv$', '', i) + '_tv')) for i in sourceDict] except: sourceDict = [(i, 'true') for i in sourceDict] threads = [] control.makeFile(control.dataPath) self.sourceFile = control.sourcescacheFile sourceDict = [i[0] for i in sourceDict if i[1] == 'true'] if content == 'movie': title = cleantitle.normalize(title) for source in sourceDict: threads.append( workers.Thread( self.getMovieSource, title, year, imdb, re.sub('_mv_tv$|_mv$|_tv$', '', source), __import__(source, globals(), locals(), [], -1).source())) else: tvshowtitle = cleantitle.normalize(tvshowtitle) season, episode = alterepisode.alterepisode().get( imdb, tmdb, tvdb, tvrage, season, episode, alter, title, date) for source in sourceDict: threads.append( workers.Thread( self.getEpisodeSource, title, year, imdb, tvdb, season, episode, tvshowtitle, date, re.sub('_mv_tv$|_mv$|_tv$', '', source), __import__(source, globals(), locals(), [], -1).source())) try: timeout = int(control.setting('sources_timeout_40')) except: timeout = 40 [i.start() for i in threads] for i in range(0, timeout * 2): try: if xbmc.abortRequested == True: return sys.exit() if len(self.sources) >= 10: break is_alive = [x.is_alive() for x in threads] if all(x == False for x in is_alive): break time.sleep(0.5) except: pass if len(self.sources) >= 10: return True else: return False
def get_sources(self, url, hosthdDict=None, hostDict=None, locDict=None, proxy_options=None, key=None, testing=False): try: sources = [] if control.setting('Provider-%s' % name) == False: log('INFO','get_sources','Provider Disabled by User') return sources if url == None: log('FAIL','get_sources','url == None. Could not find a matching title: %s' % cleantitle.title_from_key(key), dolog=not testing) return sources UA = client.agent() # get TA JSON data from tadata api result = proxies.request(url, proxy_options=proxy_options, use_web_proxy=self.proxyrequired, IPv4=True) resultx = json.loads(str(result)) ta_url = resultx['url'] poster = resultx['image'] if 'image' in resultx else None #print ta_url result = proxies.request(ta_url, proxy_options=proxy_options, use_web_proxy=self.proxyrequired, IPv4=True) # get types of videos available types = {'trailer':'Trailer', 'feature_trailer':'Trailer', 'theatrical_trailer':'Trailer', 'behind_the_scenes':'Behind the scenes', 'deleted_scene':'Deleted Scenes', 'featurette':'Featurette', 'featured_box':'Featurette', 'music_video':'Music Video', 'misc_scene':'Misc.'} quality_maps = {'4k':'4K','2k':'2K','1080p':'1080p', 'HD':'720p', 'M':'480p', 'S':'360p'} extras = [] items = client.parseDOM(result, 'div', attrs = {'id':'featured_c'})[0] m_title = client.parseDOM(items, 'div', attrs = {'class':'movie_info'}) #print m_title fail_bool = False for video in m_title: try: time.sleep(0.1) video = video.replace('rttttttttttt','') video = video.replace('rtttttttttt','') video = video.replace('\r','') video = video.replace('\t','') video = video.replace('\n','') title = client.parseDOM(video, 'a', attrs = {'class':'m_title'})[0] ta_tage_url = client.parseDOM(video, 'a', ret = 'href')[0] if 'http' not in ta_tage_url: ta_tage_url = urlparse.urljoin(self.base_link, ta_tage_url) try: vid_date = client.parseDOM(video, 'span', attrs = {'class':'m_date'})[0] vid_date = vid_date.replace(',','') except: vid_date = '' # Trailers if title.lower() == 'trailer': extra_type = 'trailer' elif title.lower() == 'feature trailer': extra_type = 'feature_trailer' elif title.lower() == 'theatrical trailer': extra_type = 'theatrical_trailer' # Behind the scenes elif 'behind the scenes' in title.lower(): extra_type = 'behind_the_scenes' # Featurette elif 'featurette' in title.lower(): extra_type = 'featurette' # Music Video elif 'music video' in title.lower(): extra_type = 'music_video' # Interview elif 'interview' in title.lower(): extra_type = 'interview' if title.lower().startswith('interview') or title.lower().startswith('generic interview'): title = title.split('nterview - ')[-1].split('nterview- ')[-1] # Deleted scene elif 'deleted scene' in title.lower(): extra_type = 'deleted_scene' # Trailers elif 'trailer' in title.lower(): extra_type = 'trailer' else: extra_type = 'misc_scene' # process ta_tage_url #print ta_tage_url result = proxies.request(ta_tage_url, proxy_options=proxy_options, use_web_proxy=self.proxyrequired, IPv4=True) data = None js = re.findall(r'eval\(function\(w,i,s,e\).*;', result) if len(js) > 0: data = js[0] else: try: jsd = re.findall(r'src="/util/client.js?c=(.*?)"><', result)[0].strip() except: try: jsd = re.findall(r'</style>rttr<!-- (.*?) -->rrttrtt<div id=\"embed_box\">', result)[0].strip() except: jsd = re.findall(r'</style>.*<!-- (.*?) -->.*<div id=\"embed_box\">', result, flags=re.DOTALL)[0].strip() jsd_url = tau % (urllib.quote_plus(jsd), client.b64encode(str(int(time.time()))), client.b64encode(ta_tage_url), client.b64encode(UA), control.setting('ver'), client.b64encode(control.setting('ca'))) data = proxies.request(jsd_url) if data == None: log('ERROR', 'get_sources-1', '%s' % jsd_url, dolog=True) if data != None: if str(data) == '423': fail_bool = True raise Exception("Helper site is currently unavailable !") try: data = unwise2.unwise_process(data) except: raise Exception("unwise2 could not process data") else: raise Exception("URL Post Data Unavailable") files = re.findall(r'source src="([^"]+)"', data) quals = re.findall(r'res=\"(.*?)\"', data) processed = [] for i in range(0, len(files)): v_file = files[i] if quals[i] in quality_maps.keys(): quality = quality_maps[quals[i]] else: quality = '720p' #print extra_type if quality not in processed: #print v_file processed.append(quality) extras.append( {'etype': extra_type, 'date': vid_date, 'type': types[extra_type], 'url' : v_file, 'quality': quality, 'title': title, 'thumb': poster} ) if testing == True and len(extras) > 0: break except Exception as e: log('ERROR', 'get_sources-2', '%s' % e, dolog=True) if fail_bool == True: raise Exception("%s" % e) links = [] #print extras for extra in extras: links = resolvers.createMeta(extra['url'], self.name, self.logo, extra['quality'], links, key, vidtype=extra['type'], testing=testing, txt=extra['title'], poster=extra['thumb']) if testing == True and len(links) > 0: break for i in links: sources.append(i) if len(sources) == 0: log('FAIL','get_sources','Could not find a matching title: %s' % cleantitle.title_from_key(key)) return sources log('SUCCESS', 'get_sources','%s sources : %s' % (cleantitle.title_from_key(key), len(sources)), dolog=not testing) return sources except Exception as e: log('ERROR', 'get_sources', '%s' % e, dolog=not testing) return sources
def get_sources(self, url, hosthdDict=None, hostDict=None, locDict=None, proxy_options=None, key=None, testing=False): try: sources = [] if control.setting('Provider-%s' % name) == False: log('INFO', 'get_sources', 'Provider Disabled by User') return sources if url == None: log('FAIL', 'get_sources', 'url == None. Could not find a matching title: %s' % cleantitle.title_from_key(key), dolog=not testing) return sources url_arr = [] data = urlparse.parse_qs(url) data = dict([(i, data[i][0]) if data[i] else (i, '') for i in data]) if 'episode' in data and 'season' in data: url0 = (data['title'].translate( None, '\/:*?"\'<>|!,')).replace(' ', '-').replace( '--', '-').lower() + "/s%s/e%s" % (data['season'], data['episode']) url_arr.append(url0) else: url1 = (data['title'].translate(None, '\/:*?"\'<>|!,')).replace( ' ', '-').replace('--', '-').lower() url2 = (data['title'].translate( None, '\/:*?"\'<>|!,')).replace(' ', '-').replace( '--', '-').lower() + "-%s" % (data['year']) url_arr.append(url1) url_arr.append(url2) try: title = data['title'] title = title.split(':') title = title[0] url3 = (title.translate(None, '\/:*?"\'<>|!,')).replace( ' ', '-').replace('--', '-').lower() url_arr.append(url3) except: pass if 'episode' in data and 'season' in data: try: url1 = (data['title'].split(':')[0].translate( None, '\/:*?"\'<>|!,')).replace(' ', '-').replace( '--', '-').lower() + "/s%s/e%s" % (data['season'], data['episode']) url_arr.append(url1) except: pass else: try: url4 = (data['title'].split(':')[0].translate( None, '\/:*?"\'<>|!,')).replace(' ', '-').replace('--', '-').lower() url5 = (data['title'].split(':')[0].translate( None, '\/:*?"\'<>|!,')).replace(' ', '-').replace( '--', '-').lower() + "-%s" % (data['year']) url_arr.append(url4) url_arr.append(url5) except: pass url_arr = list(set(url_arr)) links = [] for url in url_arr: try: #print url url = urlparse.urljoin(self.base_link, self.watch_link % url) #print url r = proxies.request(url, output='geturl', proxy_options=proxy_options, use_web_proxy=self.proxyrequired, IPv4=True) #print r if r == None: raise Exception() r = result = proxies.request( url, proxy_options=proxy_options, use_web_proxy=self.proxyrequired, IPv4=True) #print "resp ===== %s" % r quality = '720p' r = re.sub(r'[^\x00-\x7F]+', ' ', r) if 'episode' not in data or 'season' not in data: y = re.findall('Date\s*:\s*.+?>.+?(\d{4})', r) y = y[0] if len(y) > 0 else None #print y if ('year' in data and y != None and data['year'] != y): #print 'year not found' raise Exception() q = client.parseDOM(r, 'title') q = q[0] if len(q) > 0 else None quality = '1080p' if ' 1080' in q else '720p' sub_url = None try: sub_url = urlparse.urljoin( self.base_link, re.findall('\/.*srt', result)[0]) except: pass try: poster = sub_url = urlparse.urljoin( self.base_link, client.parseDOM(result, 'img', ret='src', attrs={'id': 'nameimage'})[0]) except: poster = None #print quality #r = client.parseDOM(r, 'div', attrs = {'id': '5throw'})[0] #r = client.parseDOM(r, 'a', ret='href', attrs = {'rel': 'nofollow'}) try: r = client.parseDOM(r, 'div', attrs={'id': '1strow'})[0] #print r r = client.parseDOM(r, 'a', ret='href', attrs={'id': 'dm1'})[0] #print r links = resolvers.createMeta(r, self.name, self.logo, quality, links, key, poster=poster, vidtype='Movie', sub_url=sub_url, testing=testing) except Exception as e: log('FAIL', 'get_sources-1', e, dolog=False) try: r = self.returnFinalLink(url) if r != None: links = resolvers.createMeta(r, self.name, self.logo, quality, links, key, poster=poster, vidtype='Movie', sub_url=sub_url, testing=testing) except Exception as e: log('FAIL', 'get_sources-2', e, dolog=False) try: r = client.parseDOM(result, 'iframe', ret='src') r2 = [i for i in r if 'g2g' in i or 'ytid' in i] #print r2 for r in r2: try: if 'http' not in r and self.urlhost in r: r = 'http:' + r elif 'http' not in r: r = self.base_link + r #print r r = proxies.request( r, proxy_options=proxy_options, use_web_proxy=self.proxyrequired, IPv4=True) r = re.sub(r'[^\x00-\x7F]+', ' ', r) r = client.parseDOM(r, 'iframe', ret='src')[0] part2 = False if '.php' in r: r = self.base_link + r rx = r.replace('.php', '2.php') r = proxies.request( r, proxy_options=proxy_options, use_web_proxy=self.proxyrequired, IPv4=True) r = re.sub(r'[^\x00-\x7F]+', ' ', r) r = client.parseDOM(r, 'iframe', ret='src')[0] try: rx = proxies.request( rx, proxy_options=proxy_options, use_web_proxy=self.proxyrequired, IPv4=True) rx = re.sub(r'[^\x00-\x7F]+', ' ', rx) rx = client.parseDOM(rx, 'iframe', ret='src')[0] if 'http' not in rx: rx = 'http:' + rx part2 = True except: pass if 'http' not in r: r = 'http:' + r #print r if 'youtube' in r: vidtype = 'Trailer' qualityt = '720p' r = r.replace('?showinfo=0', '') else: vidtype = 'Movie' qualityt = quality if part2: #print '2-part video' links = resolvers.createMeta( r, self.name, self.logo, qualityt, links, key, poster=poster, vidtype=vidtype, txt='Part-1', sub_url=sub_url, testing=testing) links = resolvers.createMeta( rx, self.name, self.logo, qualityt, links, key, poster=poster, vidtype=vidtype, txt='Part-2', sub_url=sub_url, testing=testing) else: links = resolvers.createMeta( r, self.name, self.logo, qualityt, links, key, poster=poster, vidtype=vidtype, sub_url=sub_url, testing=testing) except: pass except Exception as e: log('FAIL', 'get_sources-3', e, dolog=False) except: pass for i in links: sources.append(i) if len(sources) == 0: log( 'FAIL', 'get_sources', 'Could not find a matching title: %s' % cleantitle.title_from_key(key)) return sources log('SUCCESS', 'get_sources', '%s sources : %s' % (cleantitle.title_from_key(key), len(sources)), dolog=not testing) return sources except Exception as e: log('ERROR', 'get_sources', '%s' % e, dolog=not testing) return sources
def checkLibraryUpdates(self): first = True start = time.time() while self._status: if ((time.time() - start) > int(self._scheduled)) or first: first = False start = time.time() control.run(config.CHECKLIBRARYUPDATES, 'service') time.sleep(10) def shutdown(self): self._status = False if __name__ == "__main__": httpPort = int(control.setting('proxyPort')) server = SocketServer.TCPServer(('', httpPort), ProxyHandler) server_thread = threading.Thread(target=server.serve_forever) server_thread.start() xbmc.log('[%s] Service: starting HTTP proxy server on port %s' % (control.addonInfo('name'), httpPort), level=xbmc.LOGNOTICE) libActive = True if control.setting( 'libraryAutoUpdate') == 'true' else False if libActive == True: libChecker = LibraryChecker() libSchedTask = threading.Thread(target=libChecker.checkLibraryUpdates) libSchedTask.start()
def createMeta(self, url, provider, logo, quality, links, key, riptype, vidtype='Movie', lang='en', sub_url=None, txt='', file_ext='.mp4', testing=False, poster=None, headers=None): if testing == True: links.append(url) return links if control.setting('Host-%s' % name) == False: log('INFO', 'createMeta', 'Host Disabled by User') return links urldata = client.b64encode(json.dumps('', encoding='utf-8')) params = client.b64encode(json.dumps('', encoding='utf-8')) orig_url = url online = check(url) files_ret = [] titleinfo = txt fs = 0 try: furl, fs, file_ext = mega.get_mega_dl_link(url) quality = qual_based_on_fs(quality, fs) if int(fs) == 0: fs = client.getFileSize(furl) urldata = createurldata(furl, quality) except Exception as e: online = False log('FAIL', 'createMeta-1', '%s - %s' % (url, e)) try: files_ret.append({ 'source': self.name, 'maininfo': '', 'titleinfo': titleinfo, 'quality': quality, 'vidtype': vidtype, 'rip': riptype, 'provider': provider, 'durl': url, 'url': url, 'urldata': urldata, 'params': params, 'logo': logo, 'allowsDownload': self.allowsDownload, 'resumeDownload': self.resumeDownload, 'allowsStreaming': self.allowsStreaming, 'online': online, 'key': key, 'enabled': True, 'fs': int(fs), 'file_ext': file_ext, 'ts': time.time(), 'lang': lang, 'sub_url': sub_url, 'poster': poster, 'subdomain': self.netloc[0], 'misc': { 'player': 'iplayer', 'gp': False } }) except Exception as e: log('ERROR', 'createMeta-2', '%s - %s' % (url, e)) files_ret.append({ 'source': urlhost, 'maininfo': '', 'titleinfo': titleinfo, 'quality': quality, 'vidtype': vidtype, 'rip': 'Unknown', 'provider': provider, 'durl': url, 'url': url, 'urldata': urldata, 'params': params, 'logo': logo, 'online': online, 'allowsDownload': self.allowsDownload, 'resumeDownload': self.resumeDownload, 'allowsStreaming': self.allowsStreaming, 'key': key, 'enabled': True, 'fs': int(fs), 'file_ext': file_ext, 'ts': time.time(), 'lang': lang, 'sub_url': sub_url, 'poster': poster, 'subdomain': self.netloc[0], 'misc': { 'player': 'iplayer', 'gp': False } }) for fr in files_ret: links.append(fr) log('INFO', 'createMeta', 'Successfully processed %s link >>> %s' % (provider, orig_url), dolog=self.init) return links
def createMeta(self, url, provider, logo, quality, links, key, riptype, vidtype='Movie', lang='en', sub_url=None, txt='', file_ext='.mp4', testing=False, poster=None, headers=None, page_url=None): files_ret = [] orig_url = url if testing == True: links.append(url) return links if control.setting('Host-%s' % name) == False: log('INFO', 'createMeta', 'Host Disabled by User') return links if '#' in url: url = url.split('#')[0] try: online = check(url) vidurls, err, sub_url_t = getAllQuals(url, page_url, online) if vidurls == None: log(type='ERROR', method='createMeta-1', err=u'%s' % err) return links if sub_url_t != None: sub_url = sub_url_t seq = 0 for vv in vidurls: #{'quality':q, 'src':u, 'fs':fs, 'online':online, 'params':params, 'urldata':urldata} durl = url vidurl = vv['src'] if vidurl != None: quality = vv['quality'] fs = int(vv['fs']) online = vv['online'] params = vv['params'] urldata = vv['urldata'] try: log(type='INFO', method='createMeta', err=u'durl:%s ; res:%s; fs:%s' % (durl, quality, fs)) files_ret.append({ 'source': self.name, 'maininfo': '', 'titleinfo': txt, 'quality': quality, 'vidtype': vidtype, 'rip': riptype, 'provider': provider, 'orig_url': orig_url, 'url': vidurl, 'durl': durl, 'urldata': urldata, 'params': params, 'logo': logo, 'online': online, 'allowsDownload': self.allowsDownload, 'resumeDownload': self.resumeDownload, 'allowsStreaming': self.allowsStreaming, 'key': key, 'enabled': True, 'fs': int(fs), 'file_ext': file_ext, 'ts': time.time(), 'lang': lang, 'poster': poster, 'sub_url': sub_url, 'subdomain': client.geturlhost(url), 'page_url': page_url, 'misc': { 'player': 'iplayer', 'gp': True }, 'seq': seq }) except Exception as e: log(type='ERROR', method='createMeta', err=u'%s' % e) files_ret.append({ 'source': urlhost, 'maininfo': '', 'titleinfo': txt, 'quality': quality, 'vidtype': vidtype, 'rip': 'Unknown', 'provider': provider, 'orig_url': orig_url, 'url': vidurl, 'durl': durl, 'urldata': urldata, 'params': params, 'logo': logo, 'online': online, 'allowsDownload': self.allowsDownload, 'resumeDownload': self.resumeDownload, 'allowsStreaming': self.allowsStreaming, 'key': key, 'enabled': True, 'fs': int(fs), 'file_ext': file_ext, 'ts': time.time(), 'lang': lang, 'sub_url': sub_url, 'poster': poster, 'subdomain': client.geturlhost(url), 'page_url': page_url, 'misc': { 'player': 'iplayer', 'gp': True }, 'seq': 0 }) seq += 1 except Exception as e: log('ERROR', 'createMeta', '%s' % e) for fr in files_ret: if fr != None and 'key' in fr.keys(): control.setPartialSource(fr, self.name) links.append(fr) if len(files_ret) > 0: log('SUCCESS', 'createMeta', 'Successfully processed %s link >>> %s' % (provider, orig_url), dolog=self.init) else: log('FAIL', 'createMeta', 'Failed in processing %s link >>> %s' % (provider, orig_url), dolog=self.init) log('INFO', 'createMeta', 'Completed', dolog=self.init) return links
def service(self): try: control.makeFile(control.dataPath) dbcon = database.connect(control.libcacheFile) dbcur = dbcon.cursor() dbcur.execute("CREATE TABLE IF NOT EXISTS service (" "setting TEXT, " "value TEXT, " "UNIQUE(setting)" ");") dbcur.execute("SELECT * FROM service WHERE setting = 'last_run'") fetch = dbcur.fetchone() if fetch == None: serviceProperty = "1970-01-01 23:59:00.000000" dbcur.execute("INSERT INTO service Values (?, ?)", ('last_run', serviceProperty)) dbcon.commit() else: serviceProperty = str(fetch[1]) dbcon.close() except: try: return dbcon.close() except: return try: control.window.setProperty(self.property, serviceProperty) except: return while (not xbmc.abortRequested): try: serviceProperty = control.window.getProperty(self.property) t1 = datetime.timedelta(hours=6) t2 = datetime.datetime.strptime(serviceProperty, '%Y-%m-%d %H:%M:%S.%f') t3 = datetime.datetime.now() check = abs(t3 - t2) > t1 if check == False: raise Exception() if (control.player.isPlaying() or control.condVisibility('Library.IsScanningVideo')): raise Exception() serviceProperty = datetime.datetime.now().strftime( '%Y-%m-%d %H:%M:%S.%f') control.window.setProperty(self.property, serviceProperty) try: dbcon = database.connect(control.libcacheFile) dbcur = dbcon.cursor() dbcur.execute("CREATE TABLE IF NOT EXISTS service (" "setting TEXT, " "value TEXT, " "UNIQUE(setting)" ");") dbcur.execute( "DELETE FROM service WHERE setting = 'last_run'") dbcur.execute("INSERT INTO service Values (?, ?)", ('last_run', serviceProperty)) dbcon.commit() dbcon.close() except: try: dbcon.close() except: pass if not control.setting('service_update') == 'true': raise Exception() info = control.setting('service_notification') or 'true' self.update(None, info=info) except: pass control.sleep(10000)
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.progressDialog = control.progressDialog self.progressDialog.create(control.addonInfo('name'), '') self.progressDialog.update(0, control.lang(30515).encode('utf-8'), str(' ')) self.sources = self.sourcesFilter() infoMenu = control.lang(30502).encode('utf-8') if content == 'movie' else control.lang(30503).encode('utf-8') sysmeta = urllib.quote_plus(meta) sysaddon = sys.argv[0] meta = json.loads(meta) 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() for i in range(len(self.sources)): try: if self.progressDialog.iscanceled(): break self.progressDialog.update(int((100 / float(len(self.sources))) * i)) url, label, provider = self.sources[i]['url'], self.sources[i]['label'], self.sources[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([self.sources[i]])) if i == 0: query = 'action=playItem&content=%s&name=%s&year=%s&imdb=%s&tvdb=%s&source=%s&meta=%s' % (content, sysname, year, imdb, tvdb, syssource, sysmeta) else: query = 'action=playItem&content=%s&name=%s&year=%s&imdb=%s&tvdb=%s&source=%s' % (content, sysname, year, 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.content(int(sys.argv[1]), 'files') control.directory(int(sys.argv[1]), cacheToDisc=True) try: self.progressDialog.close() except: pass except: control.infoDialog(control.lang(30501).encode('utf-8')) try: self.progressDialog.close() except: pass