def clear(table=None): try: control.idle() 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 nanscrapers.clear_cache() control.infoDialog(control.lang(30402).encode('utf-8')) except: pass
def resolve(url): actions = [ ("plugin://plugin.video.yatp/?action=play&torrent=%s", "plugin.video.yatp", "YATP-Yet Another Torrent Player"), ("plugin://plugin.video.quasar/play?uri=%s", "plugin.video.quasar", "Quasar"), ] if not xbmcvfs.exists(os.path.dirname(torrent_path)): try: xbmcvfs.mkdirs(os.path.dirname(torrent_path)) except: os.mkdir(os.path.dirname(torrent_path)) file = urllib2.urlopen(url) output = open(torrent_path, "wb") output.write(file.read()) output.close() choice = int(control.setting("torrentPlayer")) action = actions[choice] if choice == 0: url = torrent_path if addonInstaller.isInstalled(action[1]): return action[0] % url else: control.infoDialog( "Torrent player not installed. Install it or select a different torrent player.", heading=action[2], time=6000, ) return ""
def range(self, url): control.idle() yes = control.yesnoDialog(control.lang(32555).encode('utf-8'), '', '') if not yes: return if not control.condVisibility('Window.IsVisible(infodialog)') and not control.condVisibility('Player.HasVideo'): control.infoDialog(control.lang(32552).encode('utf-8'), time=10000000) self.infoDialog = True from resources.lib.indexers import tvshows items = tvshows.tvshows().get(url, idx=False) if items == None: items = [] for i in items: try: if xbmc.abortRequested == True: return sys.exit() self.add(i['title'], i['year'], i['imdb'], i['tvdb'], range=True) except: pass if self.infoDialog == True: control.infoDialog(control.lang(32554).encode('utf-8'), time=1) if self.library_setting == 'true' and not control.condVisibility('Library.IsScanningVideo'): control.execute('UpdateLibrary(video)')
def range(self, url): control.idle() yes = control.yesnoDialog(control.lang(30425).encode("utf-8"), "", "") if not yes: return if not control.condVisibility("Window.IsVisible(infodialog)") and not control.condVisibility("Player.HasVideo"): control.infoDialog(control.lang(30421).encode("utf-8"), time=10000000) self.infoDialog = True from resources.lib.indexers import movies items = movies.movies().get(url, idx=False) if items == None: items = [] for i in items: try: if xbmc.abortRequested == True: return sys.exit() self.add(i["name"], i["title"], i["year"], i["imdb"], range=True) except: pass if self.infoDialog == True: control.infoDialog(control.lang(30423).encode("utf-8"), time=1) if self.library_setting == "true" and not control.condVisibility("Library.IsScanningVideo"): control.execute("UpdateLibrary(video)")
def addFavourite(meta, content, query): try: item = dict() meta = json.loads(meta) try: id = meta['imdb'] except: id = meta['tvdb'] 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 'imdb' in meta: item['imdb'] = meta['imdb'] 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, id)) dbcur.execute("INSERT INTO %s Values (?, ?)" % content, (id, repr(item))) dbcon.commit() if query == None: control.refresh() control.infoDialog(control.lang(30411).encode('utf-8'), heading=title) except: return
def showPlaybackInfo(self): try: if not control.setting('player.info') == 'true': raise Exception() 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) except: pass
def add(self, tvshowtitle, year, imdb, tvdb, range=False): if not control.condVisibility('Window.IsVisible(infodialog)') and not control.condVisibility('Player.HasVideo'): control.infoDialog(control.lang(32552).encode('utf-8'), time=10000000) self.infoDialog = True from resources.lib.indexers import episodes items = episodes.episodes().get(tvshowtitle, year, imdb, tvdb, idx=False) try: items = [{'title': i['title'], 'year': i['year'], 'imdb': i['imdb'], 'tvdb': i['tvdb'], 'season': i['season'], 'episode': i['episode'], 'tvshowtitle': i['tvshowtitle'], 'premiered': i['premiered']} for i in items] except: items = [] try: if not self.dupe_setting == 'true': raise Exception() if items == []: raise Exception() id = [items[0]['imdb'], items[0]['tvdb']] lib = control.jsonrpc('{"jsonrpc": "2.0", "method": "VideoLibrary.GetTVShows", "params": {"properties" : ["imdbnumber", "title", "year"]}, "id": 1}') lib = unicode(lib, 'utf-8', errors='ignore') lib = json.loads(lib)['result']['tvshows'] lib = [i['title'].encode('utf-8') for i in lib if str(i['imdbnumber']) in id or (i['title'].encode('utf-8') == items[0]['tvshowtitle'] and str(i['year']) == items[0]['year'])][0] lib = control.jsonrpc('{"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodes", "params": {"filter":{"and": [{"field": "tvshow", "operator": "is", "value": "%s"}]}, "properties": ["season", "episode"]}, "id": 1}' % lib) lib = unicode(lib, 'utf-8', errors='ignore') lib = json.loads(lib)['result']['episodes'] lib = ['S%02dE%02d' % (int(i['season']), int(i['episode'])) for i in lib] items = [i for i in items if not 'S%02dE%02d' % (int(i['season']), int(i['episode'])) in lib] except: pass files_added = 0 for i in items: try: if xbmc.abortRequested == True: return sys.exit() if self.check_setting == 'true': if i['episode'] == '1': self.block = True src = lib_tools.check_sources(i['title'], i['year'], i['imdb'], i['tvdb'], i['season'], i['episode'], i['tvshowtitle'], i['premiered']) if src: self.block = False if self.block == True: raise Exception() premiered = i.get('premiered', '0') if (premiered != '0' and int(re.sub('[^0-9]', '', str(premiered))) > int(self.date)) or (premiered == '0' and not self.include_unknown): continue self.strmFile(i) files_added += 1 except: pass if range == True: return if self.infoDialog == True: control.infoDialog(control.lang(32554).encode('utf-8'), time=1) if self.library_setting == 'true' and not control.condVisibility('Library.IsScanningVideo') and files_added > 0: control.execute('UpdateLibrary(video)')
def 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.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') control.infoDialog(control.lang(30491).encode('utf-8'), heading=viewName) except: return
def addFavourite(meta, content): try: item = dict() meta = json.loads(meta) # print "META DUMP FAVOURITES %s" % meta try: id = meta['imdb'] except: id = meta['tvdb'] 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 'imdb' in meta: item['imdb'] = meta['imdb'] 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(dataPath) dbcon = database.connect(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, id)) dbcur.execute("INSERT INTO %s Values (?, ?)" % content, (id, repr(item))) dbcon.commit() control.refresh() control.infoDialog('Added to Watchlist', heading=title) except: return
def clearCache(self): control.idle() yes = control.yesnoDialog(control.lang(32056).encode('utf-8'), '', '') if not yes: return from resources.lib.modules import cache cache.cache_clear() control.infoDialog(control.lang(32057).encode('utf-8'), sound=True, icon='INFO')
def clear(table=None): try: control.idle() if table == None: table = ['rel_list', 'rel_lib'] elif not type(table) == list: table = [table] yes = control.yesnoDialog('Are You Sure?', '', '') 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('Cache.db Cleared') xbmc.executebuiltin('Container.Refresh()') except: pass
def resolve(self,url): try: referer,id = url.split('##') s = requests.Session() s.headers = {'Accept':'application/json, text/javascript, */*; q=0.01','Host':'www.streamgaroo.com','Referer':referer,'X-Requested-With' : 'XMLHttpRequest'} html = s.post('http://www.streamgaroo.com/calls/get/source',data={'h':urllib.unquote(id)}).text s.headers = ({'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8','Host':'www.streamgaroo.com','Referer':referer, 'Accept-Encoding':'gzip, deflate, lzma, sdch'}) link = json.loads(html)['link'] html = s.get(link).text #hls try: url = re.findall('playStream\(.+?,.((?:http|rtmp)[^\"\']+)',html)[0] if 'rtmp' in url: return url else: return url + '|%s' %urllib.urlencode({'X-Requested-With':constants.get_shockwave(),'Referer':link,'User-agent':client.agent()}) except: pass #everything else import liveresolver return liveresolver.resolve(link,html=html) except: control.infoDialog('No stream available!') return ''
def addDownload(name, url, image, resolved=False): if resolved: resolved = url 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('Stavka je već dodana u red čekanja', name) try: if not resolved: import urlresolver resolved = urlresolver.resolve(url) except: return control.infoDialog('Unplayable stream') pass try: u = resolved.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' try: name = name.decode('utf-8') except: pass name=re.sub('[^-a-zA-Z0-9_.() ]+', '', name) name=name.rstrip('.') 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, 'Veličina datoteke je ' + size, 'Nastaviti s preuzimanjem?', name + ' - ' + 'Potvrdi preuzimanje', 'Potvrdi', 'Prekini') if no: return except: return control.infoDialog('Nije moguće preuzeti') 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('Datoteka dodana u red čekanja', name)
def removeDownload(url): try: def download(): return [] result = cache.neptune_download_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.neptune_download_get(download, 0, table='rel_dl') control.refresh() except: control.infoDialog('You need to remove file manually', 'Can not remove from Queue')
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('Morate ručno ukloniti datoteku', 'Nije moguće ukloniti datoteku')
def playItem(url, dialog=None): try: url = resolveUrl(url) if url == None: return control.infoDialog(control.lang(30705).encode('utf-8')) meta = {} for i in ['title', 'originaltitle', 'tvshowtitle', 'year', 'season', 'episode', 'genre', 'rating', 'votes', 'director', 'writer', 'plot', 'tagline']: try: meta[i] = control.infoLabel('listitem.%s' % i) except: pass meta['title'] = cleantitle(meta['title']) meta = dict((k,v) for k, v in meta.iteritems() if not v == '') if not 'title' in meta: meta['title'] = cleantitle(control.infoLabel('listitem.label')) icon = control.infoLabel('listitem.icon') title = meta['title'] try: if not '.f4m'in url: raise Exception() ext = url.split('?')[0].split('&')[0].split('|')[0].rsplit('.')[-1].replace('/', '').lower() if not ext == 'f4m': raise Exception() from resources.lib.modules.f4mproxy.F4mProxy import f4mProxyHelper return f4mProxyHelper().playF4mLink(url, title, None, None, '', icon) except: pass item = control.item(path=url, iconImage=icon, thumbnailImage=icon) try: item.setArt({'icon': icon}) except: pass item.setInfo(type='Video', infoLabels = meta) control.player.play(url, item) except: pass
def addDownload(name, url, image, provider=None): try: def download(): return [] result = cache.bennu_download_get(download, 600000000, table='rel_dl') result = [i['name'] for i in result] except: pass try: if name in result: return control.infoDialog('Item Already In Your Queue', name) except: pass from resources.lib.indexers import bennustreams url = bennustreams.resolver().link(url) if url == None: return 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', 'm4a', 'mp3', 'aac', '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.bennu_download_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.bennu_download_get(download, 0, table='rel_dl') control.infoDialog('Item Added to Queue', name)
def clearSources(self): try: control.idle() yes = control.yesnoDialog(control.lang(30510).encode('utf-8'), '', '') if not yes: return control.makeFile(control.dataPath) dbcon = database.connect(control.providercacheFile) 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 link(self, url): try: url = self.get(url) if url == False: return url = self.process(url) if url == None: return control.infoDialog(control.lang(30705).encode('utf-8')) return url except: pass
def play(self, url, content=None): try: base = url url = resolver().get(url) if url == False: return control.execute('ActivateWindow(busydialog)') url = resolver().process(url) control.execute('Dialog.Close(busydialog)') if url == None: return control.infoDialog(control.lang(30705).encode('utf-8')) if url == False: return meta = {} for i in ['title', 'originaltitle', 'tvshowtitle', 'year', 'season', 'episode', 'genre', 'rating', 'votes', 'director', 'writer', 'plot', 'tagline']: try: meta[i] = control.infoLabel('listitem.%s' % i) except: pass meta = dict((k,v) for k, v in meta.iteritems() if not v == '') if not 'title' in meta: meta['title'] = control.infoLabel('listitem.label') icon = control.infoLabel('listitem.icon') self.name = meta['title'] ; self.year = meta['year'] if 'year' in meta else '0' self.getbookmark = True if (content == 'movies' or content == 'episodes') else False self.offset = bookmarks().get(self.name, self.year) if not 'tvplayer' in url: if not 'itv' in url: f4m = resolver().f4m(url, self.name) if not f4m == None: return item = control.item(path=url, iconImage=icon, thumbnailImage=icon) try: item.setArt({'icon': icon}) except: pass item.setInfo(type='Video', infoLabels = meta) control.player.play(url, item) control.resolve(int(sys.argv[1]), True, item) self.totalTime = 0 ; self.currentTime = 0 for i in range(0, 240): if self.isPlayingVideo(): break control.sleep(1000) while self.isPlayingVideo(): try: self.totalTime = self.getTotalTime() self.currentTime = self.getTime() except: pass control.sleep(2000) control.sleep(5000) except: pass
def download(name, image, url): from resources.lib.modules 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 addView(content): try: 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 manager(name, imdb, tvdb, content): try: user = re.sub('[^a-z0-9]', '-', control.setting('trakt.user').strip().lower()) 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 resolve(url): try: page = url user, password = get_account() try: referer = urlparse.parse_qs(urlparse.urlparse(url).query)['referer'][0] url = url.replace(referer,'').replace('?referer=','').replace('&referer=','') except: referer = url post_data = 'username=%s&password=%s&accessed_by=web&submit=Login'%(user,password) cj = get_cj() result = client.request(url,cj=cj,headers={'referer':'http://www.streamlive.to', 'Content-type':'application/x-www-form-urlencoded', 'Origin': 'http://www.streamlive.to', 'Host':'www.streamlive.to', 'User-agent':client.agent()}) if 'this channel is a premium channel.' in result.lower(): control.infoDialog('Premium channel. Upgrade your account to watch it!', heading='Streamlive.to') return if 'not logged in yet' in result.lower(): #Cookie expired or not valid, request new cookie cj = login(cj,post_data) cj.save (cookieFile,ignore_discard=True) result = client.request(url,cj=cj) token_url = re.compile('getJSON\("(.+?)"').findall(result)[0] r2 = client.request(token_url,referer=referer) token = json.loads(r2)["token"] file = re.compile('(?:[\"\'])?file(?:[\"\'])?\s*:\s*(?:\'|\")(.+?)(?:\'|\")').findall(result)[0].replace('.flv','') rtmp = re.compile('streamer\s*:\s*(?:\'|\")(.+?)(?:\'|\")').findall(result)[0].replace(r'\\','\\').replace(r'\/','/') app = re.compile('.*.*rtmp://[\.\w:]*/([^\s]+)').findall(rtmp)[0] url=rtmp + ' app=' + app + ' playpath=' + file + ' swfUrl=http://www.streamlive.to/ads/streamlive.swf flashver=' + constants.flash_ver() + ' live=1 timeout=15 token=' + token + ' swfVfy=1 pageUrl='+page return url 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 getToken(): username = control.setting('hrti_user') password = control.setting('hrti_pass') if username=='' or password=='': control.infoDialog('Unesite korisničko ime i lozinku za hrti.hr!') return 'x','x' session=requests.Session() headers={} cookies=session.cookies headers['cookies']=cookies headers['User-agent']=client.agent() uuid_url = 'https://hrti.hrt.hr/client_api.php/config/identify/format/json' resp_data = session.post(uuid_url, data = '{"application_publication_id":"all_in_one"}' , headers=headers).content data=json.loads(resp_data) uuid = data['uuid'] put_data = '{"application_publication_id":"all_in_one","uuid":"%s","screen_height":1080,"screen_width":1920,"os":"Windows","os_version":"NT 4.0","device_model_string_id":"chrome 42.0.2311.135","application_version":"1.1"}'%uuid resp_data = session.put(uuid_url, data = put_data , headers=headers).text data=json.loads(resp_data) session_id = data['session_id'] login_data = '{"username":"******","password": "******"}'%(username, password) login_url = 'https://hrti.hrt.hr/client_api.php/user/login/session_id/%s/format/json'%session_id resp = session.post(login_url, data = login_data, headers = headers) data = json.loads(resp.text) try: session_token = data['session_token'] except: control.infoDialog('Provjerite korisničko ime i lozinku za hrti.hr!') return 'x','x' stream_token = data['secure_streaming_token'] user_pin = data['pin_code'] user_id = data['id'] user_bitrate = int(data['bitrate']) subscriber_id = data['subscriber_id'] external_id = data['external_id'] first_name = data['first_name'] last_name = data['last_name'] str_token = stream_token.split('/')[0] expire = stream_token.split('/')[-1] return str_token,expire
def manager(name, imdb, tvdb, content): try: post = {"movies": [{"ids": {"imdb": imdb}}]} if content == 'movie' else {"shows": [{"ids": {"tvdb": tvdb}}]} items = [("Add to [B]Collection[/B]", '/sync/collection')] items += [("Remove from [B]Collection[/B]", '/sync/collection/remove')] items += [("Add to [B]Watchlist[/B]", '/sync/watchlist')] items += [("Remove from [B]Watchlist[/B]", '/sync/watchlist/remove')] items += [("Add to [B]new List[/B]", '/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] = (("Add to [B]%s[/B]" % lists[i][0]), '/users/me/lists/%s/items' % lists[i][1]) for i in range(1, len(lists), 2): lists[i] = (("Remove from [B]%s[/B]" % lists[i][0]), '/users/me/lists/%s/items/remove' % lists[i][1]) items += lists select = control.selectDialog([i[0] for i in items], "Trakt Manager") if select == -1: return elif select == 4: t = "Add to [B]new List[/B]" 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("Trakt Manager", 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("Trakt Manager", heading=str(name), sound=True, icon=icon) except: return
def deleteFavourite(meta, content): try: meta = json.loads(meta) if 'title' in meta: title = meta['title'] if 'tvshowtitle' in meta: title = meta['tvshowtitle'] try: dbcon = database.connect(control.favouritesFile) dbcur = dbcon.cursor() try: dbcur.execute("DELETE FROM %s WHERE id = '%s'" % (content, meta['imdb'])) except: pass try: dbcur.execute("DELETE FROM %s WHERE id = '%s'" % (content, meta['tvdb'])) except: pass dbcon.commit() except: pass control.refresh() control.infoDialog(control.lang(30412).encode('utf-8'), heading=title) except: return
def add(self, name, title, year, imdb, range=False): if not control.condVisibility("Window.IsVisible(infodialog)") and not control.condVisibility("Player.HasVideo"): control.infoDialog(control.lang(30421).encode("utf-8"), time=10000000) self.infoDialog = True try: if not self.dupe_setting == "true": raise Exception() id = imdb lib = control.jsonrpc( '{"jsonrpc": "2.0", "method": "VideoLibrary.GetMovies", "params": {"filter":{"or": [{"field": "year", "operator": "is", "value": "%s"}, {"field": "year", "operator": "is", "value": "%s"}, {"field": "year", "operator": "is", "value": "%s"}]}, "properties" : ["imdbnumber", "originaltitle", "year"]}, "id": 1}' % (year, str(int(year) + 1), str(int(year) - 1)) ) lib = unicode(lib, "utf-8", errors="ignore") lib = json.loads(lib)["result"]["movies"] lib = [ i for i in lib if str(i["imdbnumber"]) in id or (i["originaltitle"].encode("utf-8") == title and str(i["year"]) == year) ][0] except: lib = [] try: if not lib == []: raise Exception() self.strmFile({"name": name, "title": title, "year": year, "imdb": imdb}) except: pass if range == True: return control.infoDialog(control.lang(30423).encode("utf-8"), time=1) if self.library_setting == "true" and not control.condVisibility("Library.IsScanningVideo"): control.execute("UpdateLibrary(video)")
def link(self, url): try: url = self.get(url) if url == False: return control.execute('ActivateWindow(busydialog)') url = self.process(url) control.execute('Dialog.Close(busydialog)') if url == None: return control.infoDialog(control.lang(30705).encode('utf-8')) return url except: pass
def play_vod(self, id, meta): self.retry = 0 control.log("PLAY SEXYHOT - ID: %s" % id) if id is None: return id = self.__get_globo_id(id) control.log('globo_midia_id: %s' % str(id)) if id is None: return meta = json.loads(meta) if 'url' not in meta or meta['url'] is None: return token = self.__get_token(meta['url']) info = self.__get_video_info(id, token) if info is None: return signed_hashes = get_signed_hashes(info['hash']) query_string = re.sub(r'{{(\w*)}}', r'%(\1)s', info['query_string_template']) query_string = query_string % { 'hash': signed_hashes[0], 'key': 'app', 'openClosed': 'F' if info['subscriber_only'] else 'A', 'user': info["user"] if info['subscriber_only'] else '' } self.url = '?'.join([info['url'], query_string]) control.log("live media url: %s" % self.url) meta.update({ "genre": info["category"], }) poster = meta['poster'] if 'poster' in meta else control.addonPoster() thumb = meta['thumb'] if 'thumb' in meta else info["thumbUri"] url, mime_type, stopEvent, cookies = hlshelper.pick_bandwidth(self.url) control.log("Resolved URL: %s" % repr(url)) if self.url is None: if stopEvent: control.log("Setting stop event for proxy player") stopEvent.set() control.infoDialog(control.lang(34100).encode('utf-8'), icon='ERROR') return item = control.item(path=url) item.setArt({'icon': thumb, 'thumb': thumb, 'poster': poster, 'tvshow.poster': poster, 'season.poster': poster}) item.setProperty('IsPlayable', 'true') item.setInfo(type='Video', infoLabels=control.filter_info_labels(meta)) item.setContentLookup(False) if mime_type: item.setMimeType(mime_type) if not cookies: item.setProperty('inputstream.adaptive.manifest_type', 'hls') item.setProperty('inputstreamaddon', 'inputstream.adaptive') # if cookies: # item.setProperty('inputstream.adaptive.stream_headers', 'Cookie=' + cookies) control.resolve(int(sys.argv[1]), id is not None, item) self.stopPlayingEvent = threading.Event() self.stopPlayingEvent.clear() while not self.stopPlayingEvent.isSet(): if control.monitor.abortRequested(): control.log("Abort requested") break control.sleep(100) if stopEvent: control.log("Setting stop event for proxy player") stopEvent.set()
def Search_bb(url): if 'new' == url: keyboard = xbmc.Keyboard() keyboard.setHeading(control.lang(32002).encode('utf-8')) keyboard.doModal() if keyboard.isConfirmed(): _query = keyboard.getText() query = _query.encode('utf-8') try: query = quote_plus(query) referer_link = 'http://search.proxybb.com?s={0}'.format(query) url = 'http://search.proxybb.com/Home/GetPost?phrase={0}&pindex=1&content=true&type=Simple&rad=0.{1}' url = url.format(query, random.randint(33333333333333333, 99999999999999999)) #########save in Database######### if six.PY2: term = unquote_plus(query).decode('utf-8') else: term = unquote_plus(query) dbcon = database.connect(control.searchFile) dbcur = dbcon.cursor() dbcur.execute("DELETE FROM Search WHERE search = ?", (term,)) dbcur.execute("INSERT INTO Search VALUES (?,?)", (url, term)) dbcon.commit() dbcur.close() #########search in website######### headers = {'Referer': referer_link, 'X-Requested-With': 'XMLHttpRequest'} first = client.request(referer_link, headers=headers) xbmc.sleep(10) html = client.request(url, headers=headers) posts = json.loads(html)['results'] posts = [(i['post_name'], i['post_title'], i['post_content'], i['domain']) for i in posts if i] for movieUrl, title, infos, domain in posts: if not 'imdb.com/title' in infos: continue base = BASE_URL if 'old' not in domain else OLD_URL movieUrl = urljoin(base, movieUrl) if not movieUrl.startswith('http') else movieUrl title = title.encode('utf-8') infos = infos.replace('\\', '') try: img = client.parseDOM(infos, 'img', ret='src')[0] img = img.replace('.ru', '.to') except: img = ICON try: fan = client.parseDOM(infos, 'img', ret='src')[1] except: fan = FANART try: # desc = client.parseDOM(infos, 'div', attrs={'class': 'entry-summary'})[0] desc = re.findall(r'>(Plot:.+?)</p>', infos, re.DOTALL)[0] except: desc = 'N/A' desc = Sinopsis(desc) # title = six.python_2_unicode_compatible(six.ensure_str(title)) title = six.ensure_str(title, 'utf-8') name = '[B][COLORgold]{0}[/COLOR][/B]'.format(title) mode = 'GetPack' if re.search(r'\s+S\d+\s+', name) else 'GetLinks' addon.add_directory( {'mode': mode, 'url': movieUrl, 'img': img, 'plot': desc}, {'title': name, 'plot': desc}, [(control.lang(32007).encode('utf-8'), 'RunPlugin(plugin://plugin.video.releaseBB/?mode=settings)',), (control.lang(32008).encode('utf-8'), 'RunPlugin(plugin://plugin.video.releaseBB/?mode=ClearCache)',), (control.lang(32009).encode('utf-8'), 'RunPlugin(plugin://plugin.video.releaseBB/?mode=setviews)',)], img=img, fanart=fan) # if 'olderEntries' in ref_html: pindex = int(re.search('pindex=(\d+)&', url).group(1)) + 1 np_url = re.sub(r'&pindex=\d+&', '&pindex={0}&'.format(pindex), url) rand = random.randint(33333333333333333, 99999999999999999) np_url = re.sub(r'&rand=0\.\d+$', '&rand={}'.format(rand), np_url) addon.add_directory( {'mode': 'search_bb', 'url': np_url + '|Referer={0}|nextpage'.format(referer_link)}, {'title': control.lang(32010).encode('utf-8')}, img=IconPath + 'next_page.png', fanart=FANART) except BaseException: control.infoDialog(control.lang(32022).encode('utf-8'), NAME, ICON, 5000) elif '|nextpage' in url: url, referer_link, np = url.split('|') referer_link = referer_link.split('=', 1)[1] headers = {'Referer': referer_link, 'X-Requested-With': 'XMLHttpRequest'} first = client.request(referer_link, headers=headers) xbmc.sleep(10) html = client.request(url, headers=headers) # xbmc.log('NEXT HTMLLLLL: {}'.format(html)) posts = json.loads(html)['results'] posts = [(i['post_name'], i['post_title'], i['post_content'], i['domain']) for i in posts if i] for movieUrl, title, infos, domain in posts: base = BASE_URL if 'old' not in domain else OLD_URL movieUrl = urljoin(base, movieUrl) if not movieUrl.startswith('http') else movieUrl title = six.ensure_str(title, 'utf-8') infos = infos.replace('\\', '') try: img = client.parseDOM(infos, 'img', ret='src')[0] img = img.replace('.ru', '.to') except: img = ICON try: fan = client.parseDOM(infos, 'img', ret='src')[1] except: fan = FANART try: desc = re.search(r'>(Plot:.+?)</p>', infos, re.DOTALL).group(0) except: desc = 'N/A' desc = Sinopsis(desc) name = '[B][COLORgold]{0}[/COLOR][/B]'.format(title) mode = 'GetPack' if re.search(r'\s+S\d+\s+', name) else 'GetLinks' addon.add_directory( {'mode': mode, 'url': movieUrl, 'img': img, 'plot': desc}, {'title': name, 'plot': desc}, [(control.lang(32007).encode('utf-8'), 'RunPlugin(plugin://plugin.video.releaseBB/?mode=settings)',), (control.lang(32008).encode('utf-8'), 'RunPlugin(plugin://plugin.video.releaseBB/?mode=ClearCache)',), (control.lang(32009).encode('utf-8'), 'RunPlugin(plugin://plugin.video.releaseBB/?mode=setviews)',)], img=img, fanart=fan) # if 'olderEntries' in ref_html: pindex = int(re.search('pindex=(\d+)&', url).groups()[0]) + 1 np_url = re.sub('&pindex=\d+&', '&pindex={0}&'.format(pindex), url) rand = random.randint(33333333333333333, 99999999999999999) np_url = re.sub(r'&rand=0\.\d+$', '&rand={}'.format(rand), np_url) addon.add_directory( {'mode': 'search_bb', 'url': np_url + '|Referer={0}|nextpage'.format(referer_link)}, {'title': control.lang(32010).encode('utf-8')}, img=IconPath + 'next_page.png', fanart=FANART) else: try: url = quote_plus(url) referer_link = 'http://search.proxybb.com?s={0}'.format(url) headers = {'Referer': referer_link, 'X-Requested-With': 'XMLHttpRequest'} # first = scraper.get('http://rlsbb.ru', headers=headers).text xbmc.sleep(10) s_url = 'http://search.proxybb.com/Home/GetPost?phrase={0}&pindex=1&content=true&type=Simple&rad=0.{1}' s_url = s_url.format(url, random.randint(33333333333333333, 99999999999999999)) html = client.request(s_url, headers=headers) posts = json.loads(html)['results'] posts = [(i['post_name'], i['post_title'], i['post_content'], i['domain']) for i in posts if i] for movieUrl, title, infos, domain in posts: base = BASE_URL if 'old' not in domain else OLD_URL movieUrl = urljoin(base, movieUrl) if not movieUrl.startswith('http') else movieUrl title = six.ensure_str(title, 'utf-8') infos = infos.replace('\\', '') try: img = client.parseDOM(infos, 'img', ret='src')[0] img = img.replace('.ru', '.to') except: img = ICON try: fan = client.parseDOM(infos, 'img', ret='src')[1] except: fan = FANART try: desc = re.search(r'>(Plot:.+?)</p>', infos, re.DOTALL).group(0) except: desc = 'N/A' desc = Sinopsis(desc) name = '[B][COLORgold]{0}[/COLOR][/B]'.format(title) mode = 'GetPack' if re.search(r'\s+S\d+\s+', name) else 'GetLinks' addon.add_directory( {'mode': mode, 'url': movieUrl, 'img': img, 'plot': desc}, {'title': name, 'plot': desc}, [(control.lang(32007).encode('utf-8'), 'RunPlugin(plugin://plugin.video.releaseBB/?mode=settings)',), (control.lang(32008).encode('utf-8'), 'RunPlugin(plugin://plugin.video.releaseBB/?mode=ClearCache)',), (control.lang(32009).encode('utf-8'), 'RunPlugin(plugin://plugin.video.releaseBB/?mode=setviews)',)], img=img, fanart=fan) pindex = int(re.search('pindex=(\d+)&', s_url).groups()[0]) + 1 np_url = re.sub('&pindex=\d+&', '&pindex={0}&'.format(pindex), s_url) rand = random.randint(33333333333333333, 99999999999999999) np_url = re.sub(r'&rand=0\.\d+$', '&rand={}'.format(rand), np_url) addon.add_directory( {'mode': 'search_bb', 'url': np_url + '|Referer={0}|nextpage'.format(referer_link)}, {'title': control.lang(32010).encode('utf-8')}, img=IconPath + 'next_page.png', fanart=FANART) except BaseException: control.infoDialog(control.lang(32022).encode('utf-8'), NAME, ICON, 5000) control.content(int(sys.argv[1]), 'videos') control.directory(int(sys.argv[1])) view.setView('videos', {'skin.estuary': 55, 'skin.confluence': 500})
def play(self, url, content=None): try: base = url url = resolver().get(url) if url == False: return control.execute('ActivateWindow(busydialog)') url = resolver().process(url) control.execute('Dialog.Close(busydialog)') if url == None: return control.infoDialog(control.lang(30705).encode('utf-8')) if url == False: return meta = {} for i in [ 'title', 'originaltitle', 'tvshowtitle', 'year', 'season', 'episode', 'genre', 'rating', 'votes', 'director', 'writer', 'plot', 'tagline' ]: try: meta[i] = control.infoLabel('listitem.%s' % i) except: pass meta = dict((k, v) for k, v in meta.iteritems() if not v == '') if not 'title' in meta: meta['title'] = control.infoLabel('listitem.label') icon = control.infoLabel('listitem.icon') self.name = meta['title'] self.year = meta['year'] if 'year' in meta else '0' self.getbookmark = True if (content == 'movies' or content == 'episodes') else False self.offset = bookmarks().get(self.name, self.year) f4m = resolver().f4m(url, self.name) if not f4m == None: return item = control.item(path=url, iconImage=icon, thumbnailImage=icon) try: item.setArt({'icon': icon}) except: pass item.setInfo(type='Video', infoLabels=meta) control.player.play(url, item) control.resolve(int(sys.argv[1]), True, item) self.totalTime = 0 self.currentTime = 0 for i in range(0, 240): if self.isPlayingVideo(): break control.sleep(1000) while self.isPlayingVideo(): try: self.totalTime = self.getTotalTime() self.currentTime = self.getTime() except: pass control.sleep(2000) control.sleep(5000) except: pass
addon.add_video_item({'mode': 'play_special_sport', 'url': event[0],'title':title, 'img': img,'site':site}, {'title': event[1]}, img=img, fanart=fanart, contextmenu_items=context) addon.end_of_directory() else: for event in events: import liveresolver try: resolved = liveresolver.resolve(event[0]) except: resolved = None if resolved: player=xbmc.Player() li = xbmcgui.ListItem(title) li.setThumbnailImage(img) player.play(resolved,listitem=li) break control.infoDialog("No stream found") elif mode[0]=='get_tv_event': url = args['url'][0] title = args['title'][0] site = args['site'][0] img = args['img'][0] exec "from resources.lib.sources.live_tv import %s"%site info = eval(site+".info()") source = eval(site+".main()") events = source.links(url) autoplay = addon.get_setting('autoplay') if autoplay == 'false': for event in events: browser = 'plugin://plugin.program.chrome.launcher/?url=%s&mode=showSite&stopPlayback=no'%(event[0])
def update(self, query=None, info='true'): if not query == None: control.idle() try: items = [] season, episode = [], [] show = [ os.path.join(self.library_folder, i) for i in control.listDir(self.library_folder)[0] ] for s in show: try: season += [ os.path.join(s, i) for i in control.listDir(s)[0] ] except: pass for s in season: try: episode.append([ os.path.join(s, i) for i in control.listDir(s)[1] if i.endswith('.strm') ][-1]) except: pass for file in episode: try: file = control.openFile(file) read = file.read() read = read.encode('utf-8') file.close() if not read.startswith(sys.argv[0]): raise Exception() params = dict(urlparse.parse_qsl(read.replace('?', ''))) try: tvshowtitle = params['tvshowtitle'] except: tvshowtitle = None try: tvshowtitle = params['show'] except: pass if tvshowtitle == None or tvshowtitle == '': raise Exception() year, imdb, tvdb = params['year'], params['imdb'], params[ 'tvdb'] imdb = 'tt' + re.sub('[^0-9]', '', str(imdb)) try: tmdb = params['tmdb'] except: tmdb = '0' items.append({ 'tvshowtitle': tvshowtitle, 'year': year, 'imdb': imdb, 'tmdb': tmdb, 'tvdb': tvdb }) except: pass items = [i for x, i in enumerate(items) if i not in items[x + 1:]] if len(items) == 0: raise Exception() except: return try: lib = control.jsonrpc( '{"jsonrpc": "2.0", "method": "VideoLibrary.GetTVShows", "params": {"properties" : ["imdbnumber", "title", "year"]}, "id": 1}' ) lib = unicode(lib, 'utf-8', errors='ignore') lib = json.loads(lib)['result']['tvshows'] except: return if info == 'true' and not control.condVisibility( 'Window.IsVisible(infodialog)') and not control.condVisibility( 'Player.HasVideo'): control.infoDialog(control.lang(32553).encode('utf-8'), time=10000000) self.infoDialog = True try: control.makeFile(control.dataPath) dbcon = database.connect(control.libcacheFile) dbcur = dbcon.cursor() dbcur.execute("CREATE TABLE IF NOT EXISTS tvshows (" "id TEXT, " "items TEXT, " "UNIQUE(id)" ");") except: return try: from resources.lib.indexers import episodes except: return files_added = 0 # __init__ doesn't get called from services so self.date never gets updated and new episodes are not added to the library self.datetime = (datetime.datetime.utcnow() - datetime.timedelta(hours=5)) self.date = (self.datetime - datetime.timedelta(hours=24)).strftime('%Y%m%d') for item in items: it = None if xbmc.abortRequested == True: return sys.exit() try: dbcur.execute("SELECT * FROM tvshows WHERE id = '%s'" % item['tvdb']) fetch = dbcur.fetchone() it = eval(fetch[1].encode('utf-8')) except: pass try: if not it == None: raise Exception() it = episodes.episodes().get(item['tvshowtitle'], item['year'], item['imdb'], item['tvdb'], idx=False) status = it[0]['status'].lower() it = [{ 'title': i['title'], 'year': i['year'], 'imdb': i['imdb'], 'tvdb': i['tvdb'], 'season': i['season'], 'episode': i['episode'], 'tvshowtitle': i['tvshowtitle'], 'premiered': i['premiered'] } for i in it] if status == 'continuing': raise Exception() dbcur.execute("INSERT INTO tvshows Values (?, ?)", (item['tvdb'], repr(it))) dbcon.commit() except: pass try: id = [item['imdb'], item['tvdb']] if not item['tmdb'] == '0': id += [item['tmdb']] ep = [ x['title'].encode('utf-8') for x in lib if str(x['imdbnumber']) in id or ( x['title'].encode('utf-8') == item['tvshowtitle'] and str(x['year']) == item['year']) ][0] ep = control.jsonrpc( '{"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodes", "params": {"filter":{"and": [{"field": "tvshow", "operator": "is", "value": "%s"}]}, "properties": ["season", "episode"]}, "id": 1}' % ep) ep = unicode(ep, 'utf-8', errors='ignore') ep = json.loads(ep).get('result', {}).get('episodes', {}) ep = [{ 'season': int(i['season']), 'episode': int(i['episode']) } for i in ep] ep = sorted(ep, key=lambda x: (x['season'], x['episode']))[-1] num = [ x for x, y in enumerate(it) if str(y['season']) == str(ep['season']) and str(y['episode']) == str(ep['episode']) ][-1] it = [y for x, y in enumerate(it) if x > num] if len(it) == 0: continue except: continue for i in it: try: if xbmc.abortRequested == True: return sys.exit() premiered = i.get('premiered', '0') if (premiered != '0' and int(re.sub('[^0-9]', '', str(premiered))) > int(self.date)) or (premiered == '0' and not self.include_unknown): continue libtvshows().strmFile(i) files_added += 1 except: pass if self.infoDialog == True: control.infoDialog(control.lang(32554).encode('utf-8'), time=1) if self.library_setting == 'true' and not control.condVisibility( 'Library.IsScanningVideo') and files_added > 0: control.execute('UpdateLibrary(video)')
def manager(imdb, tmdbtvdb, meta, content): try: if DBURL == None or DBURL == '': control.infoDialog('RemoteDB Address is Empty...', time=3000) return HOSTDB = str(DBURL) DBLINK = str(HOSTDB) + "/library.php?action=%s" # #print("DATABASE REMOTE", DBLINK) if imdb == '' or imdb == '0' or imdb == None: raise Exception() actions = ['Add to Library', 'Remove from Library'] meta = json.loads(meta) dbname = meta['title'] if 'title' in meta else '0' # #print("DATABASE REMOTE", dbname) dbposter = meta['poster'] if 'poster' in meta else '0' # #print("DATABASE REMOTE", dbposter) dbfanart = meta['fanart'] if 'fanart' in meta else '0' # #print("DATABASE REMOTE", dbfanart) dbyear = meta['year'] if 'year' in meta else '0' # #print("DATABASE REMOTE", dbyear) dbrating = meta['rating'] if 'rating' in meta else '0' # #print("DATABASE REMOTE", dbrating) dbgenre = meta['genre'] if 'genre' in meta else '0' # #print("DATABASE REMOTE", dbgenre) dbplot = meta['plot'] if 'plot' in meta else '0' # #print("DATABASE REMOTE", dbplot) payload = {'title':dbname, 'imdb':imdb, 'tmdbtvdb': tmdbtvdb, 'poster':dbposter, 'fanart':dbfanart, 'year':dbyear, 'rating':dbrating, 'genre':dbgenre, 'plot':dbplot} # #print ("DATABASE PAYLOAD", payload) select = control.selectDialog(actions, 'Remote Library Manager') if tmdbtvdb == '0' or tmdbtvdb == None or tmdbtvdb == '': tmdbtvdb = imdb if select == -1: return elif select == 0: if content == 'movie': dbcheck = DBLINK % 'movies' check = requests.get(dbcheck).content if imdb in check or tmdbtvdb in check: control.infoDialog('Item already in Library', heading=str(dbname), sound=True) return act = 'addmovie' else: dbcheck = DBLINK % 'tv' check = requests.get(dbcheck).content if imdb in check or tmdbtvdb in check: control.infoDialog('Item already in Library', heading=str(dbname), sound=True) return act = 'addtv' url = DBLINK % act r = requests.post(url, data=payload).content elif select == 1: if content == 'movie': dbcheck = DBLINK % 'movies' check = requests.get(dbcheck).content if not str(imdb) in check: control.infoDialog('Item Not in Library', heading=str(dbname), sound=True) return if not str(tmdbtvdb) in check: control.infoDialog('Item Not in Library', heading=str(dbname), sound=True) return act = 'deletemovie' else: dbcheck = DBLINK % 'tv' check = requests.get(dbcheck).content if not str(imdb) in check: control.infoDialog('Item Not in Library', heading=str(dbname), sound=True) return if not str(tmdbtvdb) in check: control.infoDialog('Item Not in Library', heading=str(dbname), sound=True) return act = 'deletetv' url = DBLINK % act r = requests.post(url, data=payload).content icon = control.infoLabel('ListItem.Icon') if not r == None else 'ERROR' control.infoDialog(r, heading=str(dbname), sound=True, icon=icon) if act == 'deletemovie' or act == 'deletetv': control.refresh() except: return
def movierls(title, year): from resources.lib.modules import client from resources.lib.modules import cleantitle from resources.lib.modules import control import xbmcgui, re try: dvdrls_url = 'https://www.newdvdreleasedates.com' search_url = '/ajaxsearch.php?q=%s' t = title.replace(' ', '%20') query = dvdrls_url + search_url % t r = client.request(query) result = re.findall('(<a.+?>.+?<\/a>)', r) result = [(client.parseDOM(i, 'a')[0], client.parseDOM(i, 'a', ret='href')[0]) for i in result] result = [ i[1] for i in result if cleantitle.get(title) == cleantitle.get(i[0].rsplit( '(%s' % year, 1)[0].strip().encode('utf-8')) and year in i[0] ] if not len(result) == 1: control.infoDialog( u'Nem tal\u00E1lhat\u00F3 inform\u00E1ci\u00F3 a megjelen\u00E9sekr\u0151l', sound=True, icon='INFO') return r1 = client.request(dvdrls_url + result[0]) items_table = client.parseDOM(r1, 'table')[0] items = re.findall( '<span class=\'name\'>([^<>]+)<.+?((?:Digital (?:<\/span>)Download|DVD rental|DVD.+?Blu-ray.+?4K|DVD.+?Blu-ray|DVD|Blu-ray|4K|not available)).+?(\w+\s*\d{1,2},\s*\d{4}).+?<\/tr>', items_table) if items == []: control.infoDialog( u'Nem tal\u00E1lhat\u00F3 inform\u00E1ci\u00F3 a megjelen\u00E9sekr\u0151l', sound=True, icon='INFO') return releases = [] monthDict = { 'January': u'janu\u00E1r', 'February': u'febru\u00E1r', 'March': u'm\u00E1rcius', 'April': u'\u00E1prilis', 'May': u'm\u00E1jus', 'June': u'j\u00FAnius', 'July': u'j\u00FAlius', 'August': 'augusztus', 'September': 'szeptember', 'October': u'okt\u00F3ber', 'November': 'november', 'December': 'december' } for hoster, media, date in items: try: media = re.sub('<.+?>', '', media) if 'dvd' in media.lower() and 'blu-ray' in media.lower( ) and '4k' in media.lower(): media = 'DVD, BLU-RAY, 4K' elif 'dvd' in media.lower() and 'blu-ray' in media.lower( ) and not '4k' in media.lower(): media = 'DVD, BLU-RAY' elif 'digital download' in media.lower(): media = 'VOD' elif 'dvd rental' in media.lower(): media = u'K\u00F6lcs\u00F6n\u00F6zhet\u0151 DVD' elif 'not available' in media.lower(): media = u'Nem el\u00E9rhet\u0151' date = date.replace(',', '').split(' ') month = monthDict[date[0]] date = '%s. %s %s.' % (date[2], month, date[1]) text = u'[B]%s[/B] | %s\nMegjelen\u00E9s: %s' % ( hoster.strip(), media.strip(), date.strip()) releases.append(text) except: control.infoDialog( u'Nem tal\u00E1lhat\u00F3 inform\u00E1ci\u00F3 a megjelen\u00E9sekr\u0151l', sound=True, icon='INFO') return rlstext = '[CR][CR]'.join(releases) try: rlstext = rlstext.encode('utf-8') except: pass rls_dialog = xbmcgui.Dialog() rls_dialog.textviewer(u'Megjelen\u00E9sek', rlstext) return except: control.infoDialog( u'Nem tal\u00E1lhat\u00F3 inform\u00E1ci\u00F3 a megjelen\u00E9sekr\u0151l', sound=True, icon='INFO') return
def addItem(self, title, year, imdb, tvdb, season, episode, tvshowtitle, premiered, meta): try: if 'super.fav' in control.infoLabel('Container.PluginName'): return control.dialog.ok('Exodus', control.lang(30518).encode('utf-8'), '', '') self.sources = self.getSources(title, year, imdb, tvdb, season, episode, tvshowtitle, premiered) 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() trailerMenu = control.lang(30516).encode('utf-8') if tvshowtitle == None else control.lang(30517).encode('utf-8') infoMenu = control.lang(30502).encode('utf-8') if tvshowtitle == None else control.lang(30503).encode('utf-8') downloads = True if control.setting('downloads') == 'true' and not (control.setting('movie.download.path') == '' or control.setting('tv.download.path') == '') else False 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() systitle = urllib.quote_plus('%s (%s)' % (title, year) if tvshowtitle == None or season == None or episode == None else '%s S%02dE%02d' % (tvshowtitle, int(season), int(episode))) sysname = urllib.quote_plus('%s (%s)' % (title, year) if tvshowtitle == None or season == None or episode == None else tvshowtitle) sysimage, sysaddon = urllib.quote_plus(poster), sys.argv[0] for i in range(len(self.sources)): try: #if self.progressDialog.iscanceled(): break self.progressDialog.update(int((100 / float(len(self.sources))) * i)) label = self.sources[i]['label'] syssource = urllib.quote_plus(json.dumps([self.sources[i]])) url = '%s?action=playItem&source=%s' % (sysaddon, syssource) cm = [] cm.append((control.lang(30504).encode('utf-8'), 'RunPlugin(%s?action=queueItem)' % sysaddon)) if downloads == True: cm.append((control.lang(30505).encode('utf-8'), 'RunPlugin(%s?action=download&name=%s&image=%s&source=%s)' % (sysaddon, systitle, sysimage, syssource))) cm.append((trailerMenu, 'RunPlugin(%s?action=trailer&name=%s)' % (sysaddon, sysname))) 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.addContextMenuItems(cm, replaceItems=True) control.addItem(handle=int(sys.argv[1]), url=url, listitem=item, isFolder=False) except: pass 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
def playlive(self, id, meta): if id is None: return info = self.__get_video_info(id) if not info or 'channel' not in info: return encrypted = 'encrypted' in info and info['encrypted'] if encrypted and not control.is_inputstream_available(): control.infoDialog(message=control.lang(34103).encode('utf-8'), icon='Wr') return title = info['channel'] signed_hashes = util.get_signed_hashes(info['hash']) query_string = re.sub(r'{{(\w*)}}', r'%(\1)s', info['query_string_template']) query_string = query_string % { 'hash': signed_hashes[0], 'key': 'app', 'openClosed': 'F' if info['subscriber_only'] else 'A', 'user': info['user'] if info['subscriber_only'] else '' } url = '?'.join([info['url'], query_string]) control.log("live media url: %s" % url) try: meta = json.loads(meta) except: meta = { "playcount": 0, "overlay": 6, "title": title, "thumb": info["thumbUri"], "mediatype": "video", "aired": info["exhibited_at"] } meta.update({ "genre": info["category"], "plot": info["title"], "plotoutline": info["title"] }) poster = meta['poster'] if 'poster' in meta else control.addonPoster() thumb = meta['thumb'] if 'thumb' in meta else info["thumbUri"] self.offset = float(meta['milliseconds_watched'] ) / 1000.0 if 'milliseconds_watched' in meta else 0 self.isLive = 'livefeed' in meta and meta['livefeed'] == 'true' parsed_url = urlparse(url) if parsed_url.path.endswith(".m3u8"): self.url, mime_type, stopEvent, cookies = hlshelper.pick_bandwidth( url) else: self.url = url mime_type, stopEvent, cookies = 'video/mp4', None, None if self.url is None: if stopEvent: control.log("Setting stop event for proxy player") stopEvent.set() control.infoDialog(control.lang(34100).encode('utf-8'), icon='ERROR') return control.log("Resolved URL: %s" % repr(self.url)) item = control.item(path=self.url) item.setArt({ 'icon': thumb, 'thumb': thumb, 'poster': poster, 'tvshow.poster': poster, 'season.poster': poster }) item.setProperty('IsPlayable', 'true') item.setInfo(type='Video', infoLabels=meta) item.setContentLookup(False) if encrypted: licence_url = info['protection_url'] mime_type = 'application/dash+xml' item.setProperty('inputstream.adaptive.manifest_type', 'mpd') # item.setProperty('inputstream.adaptive.manifest_type', 'ism') item.setProperty('inputstreamaddon', 'inputstream.adaptive') item.setProperty('inputstream.adaptive.license_type', 'com.widevine.alpha') # 'com.microsoft.playready' item.setProperty('inputstream.adaptive.license_key', licence_url + "||R{SSM}|") # item.setProperty('inputstream.adaptive.license_data', licence_url) if mime_type: item.setMimeType(mime_type) elif not cookies: item.setProperty('inputstream.adaptive.manifest_type', 'hls') item.setProperty('inputstreamaddon', 'inputstream.adaptive') control.resolve(int(sys.argv[1]), True, item) self.stopPlayingEvent = threading.Event() self.stopPlayingEvent.clear() self.token = auth_helper.get_globosat_token() self.video_id = info['id'] if 'id' in info else None last_time = 0.0 while not self.stopPlayingEvent.isSet(): if control.monitor.abortRequested(): control.log("Abort requested") break if self.isPlaying() and not self.isLive: current_time = self.getTime() if current_time - last_time > 5 or (last_time == 0 and current_time > 1): last_time = current_time self.save_video_progress(self.token, self.video_id, current_time) control.sleep(1000) if stopEvent: control.log("Setting stop event for proxy player") stopEvent.set() control.log("Done playing. Quitting...")
def infoCheck(self, version): try: control.infoDialog('', control.lang(32074).encode('utf-8'), time=5000, sound=False) return '1' except: return '1'
def playItem(self, source): try: f = dict(urlparse.parse_qsl(control.infoLabel('Container.FolderPath').replace('?',''))) meta = f['meta'] if 'meta' in f else None title = f['title'] if 'title' in f else None title = f['tvshowtitle'] if 'tvshowtitle' in f else title year = f['year'] if 'year' in f else None season = f['season'] if 'season' in f else None episode = f['episode'] if 'episode' in f else None imdb = f['imdb'] if 'imdb' in f else None tvdb = f['tvdb'] if 'tvdb' in f else None next = [] ; prev = [] ; total = [] for i in range(1,1000): try: u = control.infoLabel('ListItem(%s).FolderPath' % str(i)) if u in total: raise Exception() total.append(u) u = dict(urlparse.parse_qsl(u.replace('?',''))) u = json.loads(u['source'])[0] next.append(u) except: break for i in range(-1000,0)[::-1]: try: u = control.infoLabel('ListItem(%s).FolderPath' % str(i)) if u in total: raise Exception() total.append(u) u = dict(urlparse.parse_qsl(u.replace('?',''))) u = json.loads(u['source'])[0] prev.append(u) except: break items = json.loads(source) items = [i for i in items+next+prev][:20] self.progressDialog = control.progressDialog self.progressDialog.create(control.addonInfo('name'), '') self.progressDialog.update(0) block = None for i in range(len(items)): try: self.progressDialog.update(int((100 / float(len(items))) * i), str(items[i]['label']), str(' ')) if items[i]['source'] == block: raise Exception() w = workers.Thread(self.sourcesResolve, items[i]) w.start() m = '' for x in range(3600): if self.progressDialog.iscanceled(): return self.progressDialog.close() if xbmc.abortRequested == True: return sys.exit() k = control.condVisibility('Window.IsActive(virtualkeyboard)') if k: m += '1'; m = m[-1] if (w.is_alive() == False or x > 30) and not k: break time.sleep(0.5) for x in range(30): if m == '': break if self.progressDialog.iscanceled(): return self.progressDialog.close() if xbmc.abortRequested == True: return sys.exit() if w.is_alive() == False: break time.sleep(0.5) if w.is_alive() == True: block = items[i]['source'] if self.url == None: raise Exception() try: self.progressDialog.close() except: pass control.sleep(200) from resources.lib.modules.player import player player().run(title, year, season, episode, imdb, tvdb, meta, self.url) return self.url except: pass try: self.progressDialog.close() except: pass raise Exception() except: control.infoDialog(control.lang(30501).encode('utf-8')) pass
def accountCheck(self): if traktCredentials == False and imdbCredentials == False: control.idle() control.infoDialog(control.lang(32042).encode('utf-8'), sound=True, icon='WARNING') sys.exit()
def checkproviders(): from resources.lib.modules import cfscrape from resources.lib.modules import control from resources.lib.modules import log_utils import re, os, requests, traceback, xbmcvfs, xbmc try: scraper = cfscrape.create_scraper() langlist = ['de', 'en', 'es', 'fr', 'gr', 'hu', 'it', 'ko', 'pl', 'ru'] dialogLangs = control.dialog.multiselect( u'Kiszolg\u00E1l\u00F3k ellen\u0151rz\u00E9se', langlist) if not dialogLangs: raise Exception() xbmc.executebuiltin("ActivateWindow(busydialog)") log_utils.log('AZ ELLENORZES ELINDULT', log_utils.LOGNOTICE) langs = [] for i in dialogLangs: langs.append(langlist[i]) for lang in langs: import_path = os.path.join(control.addonPath, 'resources\lib\sources\%s' % lang) fileList = os.listdir(import_path) for fileName in fileList: try: if not '__init__.py' in fileName and fileName.endswith( '.py'): file = xbmcvfs.File(os.path.join( import_path, fileName)) filetext = file.read() file.close() baselink = re.findall( 'self\.base_link\s*\=\s*(?:\'|")([^[\'"]+)(?:\'|")\s*\n', filetext)[0] r = requests.get(baselink) cf = r.status_code if not r.status_code == 200: r1 = scraper.get(baselink) cf = '%s | %s' % (r1.status_code, 'CFSCRAPE') log_utils.log( '%s | %s | %s | %s' % (lang, fileName, r.url, cf), log_utils.LOGNOTICE) except: log_utils.log( '%s | %s | Nem sikerult az ellenorzes ennel a kiszolgalonal' % (lang, fileName), log_utils.LOGNOTICE) pass xbmc.executebuiltin("Dialog.Close(busydialog)") log_utils.log('AZ ELLENORZES BEFEJEZODOTT', log_utils.LOGNOTICE) control.dialog.ok(control.addonInfo('name'), u'Az ellen\u0151rz\u00E9s sikeres volt.', u'R\u00E9szletek a hibanapl\u00F3ban.', '') except: xbmc.executebuiltin("Dialog.Close(busydialog)") log_utils.log('ELLENORZES SIKERTELEN. A HIBA OKA:', log_utils.LOGNOTICE) log_utils.log(traceback.format_exc(), log_utils.LOGNOTICE) control.infoDialog( u'Ellen\u0151rz\u00E9s sikertelen. R\u00E9szletek a hibanapl\u00F3ban.', sound=True, icon='INFO') return
def importproviders(type): from resources.lib.modules import control from resources.lib.modules import log_utils import re, os, requests, traceback, io import zipfile try: if type == 'file': import_file = control.setting('import.providersfile') elif type == 'url': import_file = control.setting('import.providersurl') if import_file == '': raise Exception() import_file1 = import_file.rsplit('\\')[-1] if not import_file1.startswith( 'es_providers_') and not import_file1.endswith('.zip'): raise Exception() lang = import_file1.split('es_providers_')[1][:2] if not any( x in lang for x in ['de', 'en', 'es', 'fr', 'gr', 'hu', 'it', 'ko', 'pl', 'ru']): raise Exception() import_path = os.path.join(control.addonPath, 'resources\lib\sources\%s' % lang) fileList = os.listdir(import_path) for fileName in fileList: if not '__init__.py' in fileName: os.remove(os.path.join(import_path, fileName)) if type == 'file': with zipfile.ZipFile(import_file, "r") as z: z.extractall(import_path) filenames = z.namelist() filenames = [i.split('.py')[0].upper() for i in filenames] text = '%s kiszolgalo importalva (%s) | importalt fajl: ' % ( len(filenames), lang) log_utils.log(text.upper() + import_file1, log_utils.LOGNOTICE) log_utils.log(', '.join(filenames), log_utils.LOGNOTICE) elif type == 'url': r = requests.get(import_file) with zipfile.ZipFile(io.BytesIO(r.content)) as z: z.extractall(import_path) filenames = z.namelist() filenames = [i.split('.py')[0].upper() for i in filenames] text = '%s kiszolgalo importalva (%s) | importalt fajl: ' % ( len(filenames), lang) log_utils.log(text.upper() + import_file1, log_utils.LOGNOTICE) log_utils.log(', '.join(filenames), log_utils.LOGNOTICE) refreshproviders() control.infoDialog( u'Az import\u00E1l\u00E1s sikeres volt. R\u00E9szletek a hibanapl\u00F3ban.', sound=True, icon='INFO') except: log_utils.log('IMPORTALAS SIKERTELEN. A HIBA OKA:', log_utils.LOGNOTICE) log_utils.log(traceback.format_exc(), log_utils.LOGNOTICE) control.infoDialog( u'Import\u00E1l\u00E1s sikertelen. R\u00E9szletek a hibanapl\u00F3ban.', sound=True, icon='INFO') return
def clearCacheAll(self): control.idle() yes = control.yesnoDialog("Sind Sie sicher?", '', '') if not yes: return cache.cache_clear_all() control.infoDialog("Vorgang abgeschlossen", sound=True, icon='INFO')
def __get_video_info(self, id): playlistUrl = 'http://api.globovideos.com/videos/%s/playlist' playlistJson = client.request(playlistUrl % id, headers={"Accept-Encoding": "gzip"}) if not 'videos' in playlistJson or len(playlistJson['videos']) == 0: control.infoDialog(message=control.lang(34101).encode('utf-8'), sound=True, icon='ERROR') return None playlistJson = playlistJson['videos'][0] for node in playlistJson['resources']: if any("android" in s for s in node['players']): resource = node break if resource is None: control.infoDialog(message=control.lang(34102).encode('utf-8'), sound=True, icon='ERROR') return None resource_id = resource['_id'] provider = control.setting('globosat_provider').lower().replace( ' ', '_') username = control.setting('globosat_username') password = control.setting('globosat_password') # authenticate authenticator = getattr(auth, provider)() credentials = authenticator.authenticate(playlistJson["provider_id"], username, password, False) hashUrl = 'https://security.video.globo.com/videos/%s/hash?resource_id=%s&version=1.1.24&player=android' % ( id, resource_id) control.log("HASH URL: %s" % hashUrl) proxy = control.proxy_url proxy = None if proxy is None or proxy == '' else { 'http': proxy, 'https': proxy, } hashJson = client.request(hashUrl, cookie=credentials, mobile=True, headers={"Accept-Encoding": "gzip"}, proxy=proxy) control.log("HASH JSON: %s" % repr(hashJson)) if 'http_status_code' in hashJson and hashJson[ 'http_status_code'] == 403: control.infoDialog(message=str( '%s: %s' % (control.lang(34105).encode('utf-8'), hashJson['message'])), sound=True, icon='ERROR') return None return { "id": playlistJson["id"], "title": playlistJson["title"], "program": playlistJson["program"], "program_id": playlistJson["program_id"], "provider_id": playlistJson["provider_id"], "channel": playlistJson["channel"], "channel_id": playlistJson["channel_id"], "category": playlistJson["category"], "subscriber_only": playlistJson["subscriber_only"], "exhibited_at": playlistJson["exhibited_at"], "player": "android", "url": resource["url"], "query_string_template": resource["query_string_template"], "thumbUri": None, # resource["thumbUri"], "hash": hashJson["hash"], "user": hashJson["user"] if 'user' in hashJson else None }
def add(self, tvshowtitle, year, imdb, tvdb, range=False): if not control.condVisibility( 'Window.IsVisible(infodialog)') and not control.condVisibility( 'Player.HasVideo'): control.infoDialog(control.lang(32552).encode('utf-8'), time=10000000) self.infoDialog = True from resources.lib.indexers import episodes items = episodes.episodes().get(tvshowtitle, year, imdb, tvdb, idx=False) try: items = [{ 'title': i['title'], 'year': i['year'], 'imdb': i['imdb'], 'tvdb': i['tvdb'], 'season': i['season'], 'episode': i['episode'], 'tvshowtitle': i['tvshowtitle'], 'premiered': i['premiered'] } for i in items] except: items = [] try: if not self.dupe_setting == 'true': raise Exception() if items == []: raise Exception() id = [items[0]['imdb'], items[0]['tvdb']] lib = control.jsonrpc( '{"jsonrpc": "2.0", "method": "VideoLibrary.GetTVShows", "params": {"properties" : ["imdbnumber", "title", "year"]}, "id": 1}' ) lib = unicode(lib, 'utf-8', errors='ignore') lib = json.loads(lib)['result']['tvshows'] lib = [ i['title'].encode('utf-8') for i in lib if str(i['imdbnumber']) in id or ( i['title'].encode('utf-8') == items[0]['tvshowtitle'] and str(i['year']) == items[0]['year']) ][0] lib = control.jsonrpc( '{"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodes", "params": {"filter":{"and": [{"field": "tvshow", "operator": "is", "value": "%s"}]}, "properties": ["season", "episode"]}, "id": 1}' % lib) lib = unicode(lib, 'utf-8', errors='ignore') lib = json.loads(lib)['result']['episodes'] lib = [ 'S%02dE%02d' % (int(i['season']), int(i['episode'])) for i in lib ] items = [ i for i in items if not 'S%02dE%02d' % (int(i['season']), int(i['episode'])) in lib ] except: pass files_added = 0 for i in items: try: if xbmc.abortRequested == True: return sys.exit() if self.check_setting == 'true': if i['episode'] == '1': self.block = True src = lib_tools.check_sources(i['title'], i['year'], i['imdb'], i['tvdb'], i['season'], i['episode'], i['tvshowtitle'], i['premiered']) if src: self.block = False if self.block == True: raise Exception() premiered = i.get('premiered', '0') if (premiered != '0' and int(re.sub('[^0-9]', '', str(premiered))) > int( self.date)) or (premiered == '0' and not self.include_unknown): continue self.strmFile(i) files_added += 1 except: pass if range == True: return if self.infoDialog == True: control.infoDialog(control.lang(32554).encode('utf-8'), time=1) if self.library_setting == 'true' and not control.condVisibility( 'Library.IsScanningVideo') and files_added > 0: control.execute('UpdateLibrary(video)')
def __getVideoInfo(self, id): proxy = control.setting('proxy_url') proxy = None if proxy == None or proxy == '' else { 'http': proxy, 'https': proxy, } playlistUrl = 'http://api.globovideos.com/videos/%s/playlist' playlistJson = client.request(playlistUrl % id, headers={"Accept-Encoding": "gzip"}) if not 'videos' in playlistJson or len(playlistJson['videos']) == 0: return control.infoDialog(control.lang(31200).encode('utf-8'), heading=str('Video Info Not Found'), sound=True, icon='ERROR') # raise Exception("Player version not found.") playlistJson = playlistJson['videos'][0] for node in playlistJson['resources']: if any("ios" in s for s in node['players']): resource = node break if (resource or None) == None: return control.infoDialog(control.lang(31200).encode('utf-8'), heading=str('Video Resource Not Found'), sound=True, icon='ERROR') resource_id = resource['_id'] provider = control.setting('globosat_provider').lower().replace( ' ', '_') username = control.setting('globosat_username') password = control.setting('globosat_password') #authenticate authenticator = getattr(auth, provider)() credentials = authenticator.authenticate(playlistJson["provider_id"], username, password) hashUrl = 'https://security.video.globo.com/videos/%s/hash?resource_id=%s&version=1.1.23&player=ios' % ( id, resource_id) hashJson = client.request(hashUrl, cookie=credentials, mobile=True, headers={"Accept-Encoding": "gzip"}, proxy=proxy) if not hashJson or 'message' in hashJson and hashJson['message']: return control.infoDialog(control.lang(31200).encode('utf-8'), heading=hashJson['message'], sound=True, icon='ERROR') return { "id": playlistJson["id"], "title": playlistJson["title"], "program": playlistJson["program"], "program_id": playlistJson["program_id"], "provider_id": playlistJson["provider_id"], "channel": playlistJson["channel"], "channel_id": playlistJson["channel_id"], "category": playlistJson["category"], "subscriber_only": playlistJson["subscriber_only"], "exhibited_at": playlistJson["exhibited_at"], "player": "ios", "url": resource["url"], "query_string_template": resource["query_string_template"], "thumbUri": resource["thumbUri"] if 'thumbUri' in resource else None, "hash": hashJson["hash"], "user": hashJson["user"] if 'user' in hashJson else None, "encrypted": resource['encrypted'] if 'encrypted' in resource else 'false', "credentials": credentials }
rlist[rand]['title']) except: pass else: try: r += '&' + p + '=' + urllib.quote_plus(rlist[rand][p]) except: pass try: r += '&meta=' + urllib.quote_plus(json.dumps(rlist[rand])) except: r += '&meta=' + urllib.quote_plus("{}") if rtype == "movie": try: control.infoDialog(rlist[rand]['title'], control.lang(32536).encode('utf-8'), time=30000) except: pass elif rtype == "episode": try: control.infoDialog(rlist[rand]['tvshowtitle'] + " - Season " + rlist[rand]['season'] + " - " + rlist[rand]['title'], control.lang(32536).encode('utf-8'), time=30000) except: pass control.execute('RunPlugin(%s)' % r) except: control.infoDialog(control.lang(32537).encode('utf-8'), time=8000)
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 __get_video_info(self, video_id): proxy = control.proxy_url proxy = None if proxy is None or proxy == '' else { 'http': proxy, 'https': proxy, } playlist_url = 'http://api.globovideos.com/videos/%s/playlist' playlist_json = client.request(playlist_url % video_id, headers={"Accept-Encoding": "gzip"}) if 'videos' not in playlist_json or len(playlist_json['videos']) == 0: control.infoDialog(message=control.lang(34101).encode('utf-8'), sound=True, icon='ERROR') return None # raise Exception("Player version not found.") playlist_json = playlist_json['videos'][0] resource = None encrypted = False for node in playlist_json['resources']: if 'encrypted' in node and node['encrypted'] and any( 'android_native' in s for s in node['players']) and any( 'widevine' in s for s in node['content_protection']): encrypted = True resource = node break if not resource: for node in playlist_json['resources']: if 'height' in node and node['height'] == 720 and any( 'desktop' in s for s in node['players']): resource = node break if not resource: for node in playlist_json['resources']: if any(PLAYER_SLUG in s for s in node['players']): resource = node break if (resource or None) is None: control.infoDialog(message=control.lang(34102).encode('utf-8'), sound=True, icon='ERROR') return None resource_id = resource['_id'] provider = control.setting('globosat_provider').lower().replace( ' ', '_') username = control.setting('globosat_username') password = control.setting('globosat_password') # authenticate authenticator = getattr(auth, provider)() credentials = authenticator.authenticate(playlist_json["provider_id"], username, password) hash_url = 'https://security.video.globo.com/videos/%s/hash?resource_id=%s&version=%s&player=%s' % ( video_id, resource_id, PLAYER_VERSION, PLAYER_SLUG) hash_json = client.request(hash_url, cookie=credentials, mobile=True, headers={"Accept-Encoding": "gzip"}, proxy=proxy) if not hash_json or 'message' in hash_json and hash_json['message']: control.infoDialog(message=control.lang(34102).encode('utf-8'), sound=True, icon='ERROR') return None return { "id": playlist_json["id"], "title": playlist_json["title"], "program": playlist_json["program"], "program_id": playlist_json["program_id"], "provider_id": playlist_json["provider_id"], "channel": playlist_json["channel"], "channel_id": playlist_json["channel_id"], "category": playlist_json["category"], "subscriber_only": playlist_json["subscriber_only"], "exhibited_at": playlist_json["exhibited_at"], "player": PLAYER_SLUG, "url": resource["url"], "query_string_template": resource["query_string_template"], "thumbUri": resource["thumbUri"] if 'thumbUri' in resource else None, "hash": hash_json["hash"], "user": hash_json["user"] if 'user' in hash_json else None, "encrypted": encrypted, "protection_url": resource['content_protection']['widevine']['server'].replace( '{{deviceId}}', 'NmExZjhkODljZWE5YTZkZWQ3MTIzNmJhNzg3NQ==') if encrypted else None, "protection_type": 'widevine' if encrypted else None, "credentials": credentials }
def errorForSources(self): control.infoDialog(control.lang(32401).encode('utf-8'), sound=False, icon='INFO')
def error(self, msg): control.infoDialog('[%s] %s' % (self.__class__.__name__, msg), 'ERROR')
channels.channels().get() elif action == 'clearCache': navigator.navigator().clearCache() elif action == 'clearProgress': progressFile = os.path.join(datapath, 'progress.db') if os.path.exists(progressFile): if control.yesnoDialog(control.lang(32056).encode('utf-8'), '', ''): try: os.remove(progressFile) dialog.ok('Clear Progress', 'Clear Progress Complete', '', '') except: dialog.ok('Clear Progress', 'There was an error Deleting the Database', '', '') else: control.infoDialog(control.lang2(161).encode('utf-8'), heading='"Progress Database"', sound=False, icon=thumbnail) elif action == 'clearSources': import universalscrapers universalscrapers.clear_cache() elif action == 'deleteFavourite': favourites.deleteFavourite(meta, content) elif action == 'deleteProgress': favourites.deleteProgress(meta, content) elif action == 'download': try: downloader.download( name, image, sources().sourcesResolve(json.loads(source)[0], True)) except: pass
def playlive(self, id, meta, encrypted=False): control.log("TNT Play - play_stream: id=%s | meta=%s" % (id, meta)) if id is None: return try: url = self.geturl(id, encrypted=encrypted) except Exception as ex: control.log(traceback.format_exc(), control.LOGERROR) control.okDialog(u'TNT Play', str(ex)) return if encrypted and not control.is_inputstream_available(): control.okDialog(u'TNT Play', control.lang(34103).encode('utf-8')) return control.log("live media url: %s" % url) try: meta = json.loads(meta) except: meta = { "playcount": 0, "overlay": 6, } poster = meta['poster'] if 'poster' in meta else None thumb = meta['thumb'] if 'thumb' in meta else None self.offset = float(meta['milliseconds_watched'] ) / 1000.0 if 'milliseconds_watched' in meta else 0 self.isLive = not encrypted parsed_url = urlparse(url) if ".m3u8" in parsed_url.path: self.url, mime_type, stopEvent, cookies = hlshelper.pick_bandwidth( url) else: self.url = url mime_type, stopEvent, cookies = None, None, None if self.url is None: if stopEvent: control.log("Setting stop event for proxy player") stopEvent.set() control.infoDialog(control.lang(34100).encode('utf-8'), icon='ERROR') return control.log("Resolved URL: %s" % repr(self.url)) control.log("Parsed URL: %s" % repr(parsed_url)) item = control.item(path=self.url) item.setArt({'icon': thumb, 'thumb': thumb, 'poster': poster}) item.setProperty('IsPlayable', 'true') item.setInfo(type='Video', infoLabels=control.filter_info_labels(meta)) item.setContentLookup(False) manifest_type = 'hls' if parsed_url.path.endswith(".m3u8") else 'mpd' if encrypted: control.log("DRM: com.widevine.alpha") licence_url = 'https://widevine.license.istreamplanet.com/widevine/api/license/7837c2c6-8fe4-4db0-9900-1bd66c21ffa3' item.setProperty('inputstream.adaptive.license_type', 'com.widevine.alpha') item.setProperty('inputstream.adaptive.manifest_type', manifest_type) cookie = get_token() retry = 1 token = '' while retry >= 0: retry = retry - 1 headers = { 'Accept': 'application/json', 'cookie': 'avs_cookie=' + cookie, 'User-Agent': 'Tnt/2.2.13.1908061505 CFNetwork/1107.1 Darwin/19.0.0' } drm_url = 'https://api.tntgo.tv/AGL/1.0/A/{lang}/{platform}/TNTGO_LATAM_BR/CONTENT/GETDRMTOKEN/{id}'.format( lang=LANGUAGE, platform=vod_platform, id=id) control.log('TNT DRM GET %s' % drm_url) control.log(headers) drm_response = requests.get( drm_url, headers=headers, proxies=proxy).json() or {} control.log(drm_response) if drm_response.get('resultCode', 'KO') == u'OK': token = drm_response.get('resultObj') break if drm_response.get('message', '') == 'Token not valid': cookie = get_token(True) else: logout() control.infoDialog(drm_response.get( 'message', u'DRM ERROR'), icon='ERROR') return key_headers = 'x-isp-token=%s&Origin=https://www.tntgo.tv' % token license_key = '%s|%s|R{SSM}|' % (licence_url, key_headers) item.setProperty('inputstream.adaptive.license_key', license_key) else: item.setProperty('inputstream.adaptive.manifest_type', 'hls') # mime_type = 'application/vnd.apple.mpegurl' # item.setProperty('inputstream.adaptive.manifest_update_parameter', 'full') if mime_type: item.setMimeType(mime_type) control.log("MIME TYPE: %s" % repr(mime_type)) if not cookies and control.is_inputstream_available(): item.setProperty('inputstreamaddon', 'inputstream.adaptive') item.setProperty('inputstream', 'inputstream.adaptive') # Kodi 19 control.resolve(int(sys.argv[1]), True, item) control.log("Done playing. Quitting...")
def to_links(url, img, plot): # Get Links try: html = client.request(url, headers=headers) try: # <h1 class="postTitle" rel="bookmark">American Dresser 2018 BRRip XviD AC3-RBG</h1> match = client.parseDOM(html, 'h2')[0] match = re.findall(r'(.+?)\s+(\d{4}|S\d+E\d+|S\d+)', match, re.I)[0] listitem = match except IndexError: match = client.parseDOM(html, 'h2')[0] match = re.sub('<.+?>', '', match) listitem = match name = '%s (%s)' % (listitem[0].replace('.', ' '), listitem[1]) # xbmc.log('SCNSRC-NAME: {}'.format(str(name))) main = client.parseDOM(html, 'div', {'id': 'comment_list'})[0] main = client.parseDOM(main, 'p') # main = [i for i in main if i] # xbmc.log('SCNSRC-MAIN: {}'.format(str(main))) try: comments = dom.parse_dom(html, 'div', {'class': re.compile('content')}) main += [i.content for i in comments if i] except IndexError: pass links = [] import resolveurl for item in main: frames = client.parseDOM(item, 'a', ret='href') for url in frames: host = tools.GetDomain(url) if 'Unknown' in host: continue # ignore .rar files if any(x in url.lower() for x in ['.rar.', '.zip.', '.iso.']) \ or any(url.lower().endswith(x) for x in ['.rar', '.zip', '.iso']): continue if any(x in url.lower() for x in ['sample', 'zippyshare']): continue addon.log('******* %s : %s' % (host, url)) if resolveurl.HostedMediaFile(url=url): addon.log('in GetLinks if loop') title = url.rpartition('/') title = title[2].replace('.html', '') title = title.replace('.htm', '') title = title.replace( '.rar', '[COLOR red][B][I]RAR no streaming[/B][/I][/COLOR]') title = title.replace( 'rar', '[COLOR red][B][I]RAR no streaming[/B][/I][/COLOR]') title = title.replace('www.', '') title = title.replace('DDLValley.me_', ' ') title = title.replace('_', ' ') title = title.replace('.', ' ') title = title.replace( '480p', '[COLOR coral][B][I]480p[/B][/I][/COLOR]') title = title.replace( '540p', '[COLOR coral][B][I]540p[/B][/I][/COLOR]') title = title.replace( '720p', '[COLOR gold][B][I]720p[/B][/I][/COLOR]') title = title.replace( '1080p', '[COLOR orange][B][I]1080p[/B][/I][/COLOR]') title = title.replace( '1080i', '[COLOR orange][B][I]1080i[/B][/I][/COLOR]') title = title.replace( '2160p', '[COLOR cyan][B][I]4K[/B][/I][/COLOR]') title = title.replace( '.4K.', '[COLOR cyan][B][I]4K[/B][/I][/COLOR]') title = title.replace( 'mkv', '[COLOR gold][B][I]MKV[/B][/I][/COLOR] ') title = title.replace( 'avi', '[COLOR pink][B][I]AVI[/B][/I][/COLOR] ') title = title.replace( 'mp4', '[COLOR purple][B][I]MP4[/B][/I][/COLOR] ') host = host.replace( 'youtube.com', '[COLOR red][B][I]Movie Trailer[/B][/I][/COLOR]') if 'railer' in host: title = host + ' : ' + title addon.add_directory( { 'mode': 'PlayVideo', 'url': url, 'img': img, 'title': name, 'plot': plot }, { 'title': title, 'plot': plot }, [( control.lang(32007).encode('utf-8'), 'RunPlugin(plugin://plugin.video.rlshub/?mode=settings)', ), ( control.lang(32008).encode('utf-8'), 'RunPlugin(plugin://plugin.video.rlshub/?mode=ClearCache)', ), ( control.lang(32009).encode('utf-8'), 'RunPlugin(plugin://plugin.video.rlshub/?mode=setviews)', )], img=img, fanart=FANART, is_folder=False) else: links.append((host, title, url, name)) if control.setting('test.links') == 'true': threads = [] for i in links: threads.append(tools.Thread(tools.link_tester, i)) [i.start() for i in threads] [i.join() for i in threads] for item in tools.tested_links: link, title, name = item[0], item[1], item[2] cm = [ ( control.lang(32007).encode('utf-8'), 'RunPlugin(plugin://plugin.video.rlshub/?mode=settings)', ), ( control.lang(32008).encode('utf-8'), 'RunPlugin(plugin://plugin.video.rlshub/?mode=ClearCache)', ), ( control.lang(32009).encode('utf-8'), 'RunPlugin(plugin://plugin.video.rlshub/?mode=setviews)', ) ] downloads = True if control.setting( 'downloads') == 'true' and not ( control.setting('movie.download.path') == '' or control.setting('tv.download.path') == '') else False if downloads: # frame = resolveurl.resolve(link) cm.append((control.lang(32013).encode( 'utf-8' ), 'RunPlugin(plugin://plugin.video.rlshub/?mode=download&title=%s&img=%s&url=%s)' % (name, img, link))) addon.add_directory( { 'mode': 'PlayVideo', 'url': link, 'listitem': listitem, 'img': img, 'title': name, 'plot': plot }, { 'title': title, 'plot': plot }, cm, img=img, fanart=FANART, is_folder=False) else: for item in links: host, title, link, name = item[0], item[1], item[2], item[3] title = '%s - %s' % (host, title) cm = [ ( control.lang(32007).encode('utf-8'), 'RunPlugin(plugin://plugin.video.rlshub/?mode=settings)', ), ( control.lang(32008).encode('utf-8'), 'RunPlugin(plugin://plugin.video.rlshub/?mode=ClearCache)', ), ( control.lang(32009).encode('utf-8'), 'RunPlugin(plugin://plugin.video.rlshub/?mode=setviews)', ) ] downloads = True if control.setting( 'downloads') == 'true' and not ( control.setting('movie.download.path') == '' or control.setting('tv.download.path') == '') else False if downloads: cm.append((control.lang(32013).encode( 'utf-8' ), 'RunPlugin(plugin://plugin.video.rlshub/?mode=download&title=%s&img=%s&url=%s)' % (name, img, link))) addon.add_directory( { 'mode': 'PlayVideo', 'url': link, 'listitem': listitem, 'img': img, 'title': name, 'plot': plot }, { 'title': title, 'plot': plot }, cm, img=img, fanart=FANART, is_folder=False) except BaseException: control.infoDialog( control.lang(32012).encode('utf-8'), NAME, ICON, 5000) control.content(int(sys.argv[1]), 'videos') control.directory(int(sys.argv[1])) view.setView('videos', {'skin.estuary': 55, 'skin.confluence': 500})
def __get_list_item(self, meta, info, pick_bandwidth=True): hash = info['hash'] user = info['user'] title = info['title'] # or meta['title'] if 'title' in meta else None query_string = re.sub(r'{{(\w*)}}', r'%(\1)s', info['query_string_template']) query_string = query_string % { 'hash': hash, 'key': 'app', 'openClosed': 'F' if info['subscriber_only'] else 'A', 'user': user if info['subscriber_only'] else '' } url = '?'.join([info['url'], query_string]) control.log("live media url: %s" % url) meta.update({ "genre": info["category"], "plot": info["title"], "plotoutline": info["title"], "title": title }) poster = meta['poster'] if 'poster' in meta else control.addonPoster() thumb = meta['thumb'] if 'thumb' in meta else info["thumbUri"] parsed_url = urlparse(url) if parsed_url.path.endswith(".m3u8"): if pick_bandwidth: url, mime_type, stopEvent, cookies = hlshelper.pick_bandwidth( url) else: mime_type, stopEvent, cookies = None, None, None else: # self.url = url mime_type, stopEvent, cookies = 'video/mp4', None, None if url is None: if stopEvent: control.log("Setting stop event for proxy player") stopEvent.set() control.infoDialog(message=control.lang(34100).encode('utf-8'), icon='ERROR') return None, None, None control.log("Resolved URL: %s" % repr(url)) item = control.item(path=url) item.setInfo(type='video', infoLabels=meta) item.setArt({ 'icon': thumb, 'thumb': thumb, 'poster': poster, 'tvshow.poster': poster, 'season.poster': poster }) item.setProperty('IsPlayable', 'true') item.setContentLookup(False) if parsed_url.path.endswith(".mpd"): mime_type = 'application/dash+xml' if not control.disable_inputstream_adaptive: control.log("Using inputstream.adaptive MPD") item.setProperty('inputstream.adaptive.manifest_type', 'mpd') item.setProperty('inputstreamaddon', 'inputstream.adaptive') if mime_type: item.setMimeType(mime_type) elif not cookies: item.setMimeType('application/vnd.apple.mpegurl') if not control.disable_inputstream_adaptive: control.log("Using inputstream.adaptive HLS") item.setProperty('inputstream.adaptive.manifest_type', 'hls') item.setProperty('inputstreamaddon', 'inputstream.adaptive') encrypted = 'encrypted' in info and info['encrypted'] if encrypted and not control.is_inputstream_available(): control.okDialog(control.lang(31200), control.lang(34103).encode('utf-8')) return if encrypted: control.log("DRM: %s" % info['drm_scheme']) licence_url = info['protection_url'] item.setProperty('inputstream.adaptive.license_type', info['drm_scheme']) if info['drm_scheme'] == 'com.widevine.alpha' or info[ 'drm_scheme'] == 'com.microsoft.playready': item.setProperty('inputstream.adaptive.license_key', licence_url + "||R{SSM}|") # if self.offset > 0: # duration = float(meta['duration']) if 'duration' in meta else 0 # if duration > 0: # item.setProperty('StartPercent', str((self.offset / duration) * 100)) # if self.offset > 0: # item.setProperty('resumetime', str(self.offset)) # duration = float(meta['duration']) if 'duration' in meta else self.offset # duration = duration * 1000.0 # item.setProperty('totaltime', str(duration)) if 'subtitles' in info and info['subtitles'] and len( info['subtitles']) > 0: item.setSubtitles([sub['url'] for sub in info['subtitles']]) return item, url, stopEvent
def check_subtitle(tvshowtitle, year, season, episode): from resources.lib.modules import client from resources.lib.modules import control import urllib, xbmcgui, json, re try: tvshowtitle = re.sub('(\(\d{4}\))', '', tvshowtitle) tvshowtitle = tvshowtitle.strip() tvshowtitle2 = re.sub('\'', '’', tvshowtitle) titl = urllib.quote_plus(tvshowtitle) titl2 = urllib.quote_plus(tvshowtitle2) t = '%s (%s)' % (tvshowtitle, year) t2 = '%s (%s)' % (tvshowtitle2, year) tvdb_url = 'http://thetvdb.com/api/GetSeries.php?seriesname=%s' % ( titl) supersub_url = 'https://www.feliratok.info' search_url = '/index.php?term=%s&nyelv=0&action=autoname' ssub_url = '/index.php?search=&nyelv=Magyar&sid=%s&complexsearch=true&evad=%s&epizod1=%s&evadpakk=%s&tab=all' subt_url0 = supersub_url + search_url % (titl) r = client.request(subt_url0) if 'Nincs tal\u00e1lat' in r: if not titl == titl2: subt_url0 = supersub_url + search_url % (titl2) r = client.request(subt_url0) if 'Nincs tal\u00e1lat' in r: control.infoDialog( u'Nincs el\u00E9rhet\u0151 magyar felirat', sound=True, icon='INFO') return else: control.infoDialog(u'Nincs el\u00E9rhet\u0151 magyar felirat', sound=True, icon='INFO') return subs = re.findall('\{[^\{\}]+\}', r) tvshow_id = '' for item in subs: name = json.loads(item)['name'] name2 = re.sub('(\s*\([A-Z]{2}\))', '', name) name2 = name2.strip() if name.lower() == t.lower() or name2.lower() == t.lower(): tvshow_id = json.loads(item)['ID'] if name.lower() == t2.lower() or name2.lower() == t2.lower(): tvshow_id = json.loads(item)['ID'] if tvshow_id == '': r = client.request(tvdb_url, timeout='10') r = client.parseDOM(r, 'Series') r = [i for i in r if 'FirstAired>%s' % year in i] if len(r) == 0: control.infoDialog(u'Nincs el\u00E9rhet\u0151 magyar felirat', sound=True, icon='INFO') return try: aliasname = client.parseDOM(r, 'AliasNames')[0] except: control.infoDialog(u'Nincs el\u00E9rhet\u0151 magyar felirat', sound=True, icon='INFO') return t = '%s (%s)' % (aliasname, year) for item in subs: name = json.loads(item)['name'] name2 = re.sub('(\s*\([A-Z]{2}\))', '', name) name2 = name2.strip() if name.lower() == t.lower() or name2.lower() == t.lower(): tvshow_id = json.loads(item)['ID'] if name.lower() == t2.lower() or name2.lower() == t2.lower(): tvshow_id = json.loads(item)['ID'] if tvshow_id == '': control.infoDialog(u'Nincs el\u00E9rhet\u0151 magyar felirat', sound=True, icon='INFO') return subt_url = supersub_url + ssub_url % (tvshow_id, season, episode, '0') subt_r = client.request(subt_url) subt_o = re.findall( '(?s)<div class="eredeti">[^<>]+<\/div>.+?<td align="center"[^<>]+>\s*(.+?)\s*<\/td>\s*<td align[^<>]+>\s*\d{4}-\d{2}-\d{2}', subt_r) subt_m = re.findall('<div class="eredeti">([^"]+)<\/div>', subt_r) if len(subt_m) == 0: subt_url = supersub_url + ssub_url % (tvshow_id, season, episode, 'on') subt_r = client.request(subt_url) subt_o = re.findall( '(?s)<div class="eredeti">[^<>]+<\/div>.+?<td align="center"[^<>]+>\s*(.+?)\s*<\/td>\s*<td align[^<>]+>\s*\d{4}-\d{2}-\d{2}', subt_r) subt_m = re.findall('<div class="eredeti">([^"]+)<\/div>', subt_r) subt_m = [u'[\u00C9vadpakk] ' + i for i in subt_m] if len(subt_m) == 0: control.infoDialog(u'Nincs el\u00E9rhet\u0151 magyar felirat', sound=True, icon='INFO') return subt = ['%s - (%s)' % (i, j) for i, j in zip(subt_m, subt_o)] subtext_r = '[CR]===================================================[CR][B][Magyar felirat][/B] '.join( subt) subtext = u'[COLOR lawngreen][B]%s SuperSubtitles felirat el\u00E9rhet\u0151:[/B][/COLOR][CR][B][Magyar felirat][/B] %s' % ( len(subt), subtext_r) subtext = re.sub('<.+?>', '', subtext) try: subtext = subtext.encode('utf-8') except: pass subtitle_dialog = xbmcgui.Dialog() subtitle_dialog.textviewer('Feliratok', subtext) return 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 = 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