def play(self, name, url=None, windowedtrailer=0): try: url = self.worker(name, url) if not url: return title = control.infoLabel('listitem.title') if not title: title = control.infoLabel('listitem.label') icon = control.infoLabel('listitem.icon') item = control.item(path=url, iconImage=icon, thumbnailImage=icon) try: item.setArt({'icon': icon}) except: pass item.setInfo(type='Video', infoLabels={'title': title}) control.player.play(url, item, windowedtrailer) if windowedtrailer == 1: # The call to the play() method is non-blocking. So we delay further script execution to keep the script alive at this spot. # Otherwise this script will continue and probably already be garbage collected by the time the trailer has ended. control.sleep(1000) # Wait until playback starts. Less than 900ms is too short (on my box). Make it one second. while control.player.isPlayingVideo(): control.sleep(1000) # Close the dialog. # Same behaviour as the fullscreenvideo window when : # the media plays to the end, # or the user pressed one of X, ESC, or Backspace keys on the keyboard/remote to stop playback. control.execute("Dialog.Close(%s, true)" % control.getCurrentDialogId) except: pass
def run(self, anime_id, ep_id, url): control.sleep(200) self.anime_id = int(anime_id) self.episode_id = int(ep_id) item = control.item(path=url) try: c = cache.get(masterani.get_anime_details, 3, self.anime_id) ctype = c['type'] ctype = 'video' if int(ctype) is 2 else 'episode' tvshowtitle = c['title'] poster = c['poster'] print poster genre = c['genre'] print genre coverlink = "http://cdn.masterani.me/poster/" + poster print coverlink item.setArt({'icon': coverlink, 'thumb': coverlink, 'poster': coverlink, 'tvshow.poster': coverlink, 'season.poster': coverlink}) e = c['episodes'][self.episode_id] title = e['info']['title'] season = 1 if season is None: season = 1 episode = e['info']['episode'] if ctype is 'video': title = c['title'] if title is None: title = "Episode %s" % episode year = e['info']['aired'] year = year.split("-", 1)[0] print year plot = e['info']['description'] print plot item.setInfo(type="video", infoLabels={'tvshowtitle': title, 'title': tvshowtitle, 'episode': int(episode), 'season': int(season), 'mediatype': ctype, 'genre': genre, 'year': year, 'plot': plot}) except: pass item.setProperty('Video', 'true') item.setProperty('IsPlayable', 'true') self.play(url, item) self.playback_checker() pass
def resolve(self, url): try: control.sleep(5000) url = urlparse.urljoin(self.base_link, url) url = client.request(url, output='geturl') if self.base_link not in url: return url except: return
def run(self, url): title = control.infoLabel('ListItem.Label') image = control.infoLabel('ListItem.Icon') item = control.item(path=url, iconImage=image, thumbnailImage=image) item.setInfo(type='Video', infoLabels = {'title': title}) control.player.play(url, item) for i in range(0, 240): if self.isPlayingVideo(): break control.sleep(1000)
def idleForPlayback(self): for i in range(0, 200): if control.condVisibility('Window.IsActive(busydialog)') == 1: control.idle(); else: break; control.sleep(100);
def sources(self, url, hostDict, hostprDict): sources = [] try: if not url: return sources r = client.request(urlparse.urljoin(self.base_link, url)) links = dom_parser.parse_dom(r, 'table') links = [i.content for i in links if dom_parser.parse_dom(i, 'span', attrs={'class': re.compile('linkSearch(-a)?')})] links = re.compile('(<a.+?/a>)', re.DOTALL).findall(''.join(links)) links = [dom_parser.parse_dom(i, 'a', req='href') for i in links if re.findall('(.+?)\s*\(\d+\)\s*<', i)] links = [i[0].attrs['href'] for i in links if i] url = re.sub('/streams-\d+', '', url) for link in links: if '/englisch/' in link: continue control.sleep(3000) if link != url: r = client.request(urlparse.urljoin(self.base_link, link)) quality = 'SD' info = [] detail = dom_parser.parse_dom(r, 'th', attrs={'class': 'thlink'}) detail = [dom_parser.parse_dom(i, 'a', req='href') for i in detail] detail = [(i[0].attrs['href'], i[0].content.replace('▶', '').strip()) for i in detail if i] if detail: quality, info = source_utils.get_release_quality(detail[0][1]) r = client.request(urlparse.urljoin(self.base_link, detail[0][0])) r = dom_parser.parse_dom(r, 'table') r = [dom_parser.parse_dom(i, 'a', req=['href', 'title']) for i in r if not dom_parser.parse_dom(i, 'table')] r = [(l.attrs['href'], l.attrs['title']) for i in r for l in i if l.attrs['title']] info = ' | '.join(info) for stream_link, hoster in r: valid, hoster = source_utils.is_host_valid(hoster, hostDict) if not valid: continue direct = False if hoster.lower() == 'gvideo': direct = True sources.append({'source': hoster, 'quality': quality, 'language': 'de', 'url': stream_link, 'info': info, 'direct': direct, 'debridonly': False, 'checkquality': True}) return sources except: return sources
def play(self, title, year, imdb, tvdb, season, episode, tvshowtitle, premiered, meta, select): try: sysloc = [urlparse.urlparse(sys.argv[0]).netloc, '', 'plugin.video.live.streamspro', 'plugin.video.tinklepad'] sysplg = True if control.infoLabel('Container.PluginName') in sysloc else False syslib = False #True if '.strm' in str(control.infoLabel('ListItem.FileName')) else False items = self.getSources(title, year, imdb, tvdb, season, episode, tvshowtitle, premiered) select = control.setting('hosts.mode') if select == None else select title = tvshowtitle if not tvshowtitle == None else title url = None if syslib == True or sysplg == False: items = [] if control.window.getProperty('PseudoTVRunning') == 'True': return control.resolve(int(sys.argv[1]), True, control.item(path=str(self.sourcesDirect(items)))) if len(items) > 0: if select == '1' and 'plugin' in control.infoLabel('Container.PluginName'): control.window.clearProperty(self.itemProperty) control.window.setProperty(self.itemProperty, json.dumps(items)) control.window.clearProperty(self.metaProperty) control.window.setProperty(self.metaProperty, meta) control.sleep(200) return control.execute('Container.Update(%s?action=addItem&title=%s)' % (sys.argv[0], urllib.quote_plus(title.encode('utf-8')))) elif select == '0' or select == '1': url = self.sourcesDialog(items) else: url = self.sourcesDirect(items) if url == None: return self.errorForSources() meta = json.loads(meta) from resources.lib.modules.player import player player().run(title, year, season, episode, imdb, tvdb, url, meta) except: pass
def resolve(self, url): try: control.sleep(5000) url = urlparse.urljoin(self.base_link, url) url = client.request(url, redirect=False, output='extended') if url and url[2]['Location'].strip(): url = url[2]['Location'] if self.base_link not in url: if 'google' in url: return self.__google(url) return url except: return
def auth_loop(self): control.sleep(self.auth_step * 1000) url = 'client_id=%s&code=%s' % (self.client_ID, self.device_code) url = oauth_base_url + credentials_url % url response = requests.get(url) if 'error' in response.text: return control.okDialog(title='default', message=40019) else: try: response = response.json() control.progressDialog.close() self.client_ID = response['client_id'] self.secret = response['client_secret'] except: log_utils.error() control.okDialog(title='default', message=40019) return
def sourcesDirect(self, items): filter = [i for i in items if i['source'].lower() in self.hostcapDict and i['debrid'] == ''] items = [i for i in items if not i in filter] filter = [i for i in items if i['source'].lower() in self.hostblockDict and i['debrid'] == ''] items = [i for i in items if not i in filter] items = [i for i in items if ('autoplay' in i and i['autoplay'] == True) or not 'autoplay' in i] if control.setting('autoplay.sd') == 'true': items = [i for i in items if not i['quality'] in ['4K', '1440p', '1080p', 'HD']] u = None header = control.addonInfo('name') header2 = header.upper() try: control.sleep(1000) progressDialog = control.progressDialog if control.setting('progress.dialog') == '0' else control.progressDialogBG progressDialog.create(header, '') progressDialog.update(0) except: pass for i in range(len(items)): try: if progressDialog.iscanceled(): break progressDialog.update(int((100 / float(len(items))) * i), str(items[i]['label']), str(' ')) except: progressDialog.update(int((100 / float(len(items))) * i), str(header2), str(items[i]['label'])) try: if xbmc.abortRequested == True: return sys.exit() url = self.sourcesResolve(items[i]) if u == None: u = url if not url == None: break except: pass try: progressDialog.close() except: pass return u
def get_request(url): try: try: response = requests.get(url) except requests.exceptions.SSLError: response = requests.get(url, verify=False) except requests.exceptions.ConnectionError: return control.notification(message=32024) if '200' in str(response): return response.json() elif 'Retry-After' in response.headers: # API REQUESTS ARE BEING THROTTLED, INTRODUCE WAIT TIME (TMDb removed rate-limit on 12-6-20) throttleTime = response.headers['Retry-After'] control.notification(message='TMDB Throttling Applied, Sleeping for %s seconds' % throttleTime) control.sleep((int(throttleTime) + 1) * 1000) return get_request(url) else: log_utils.log('Get request failed to TMDB URL: %s\n msg : TMDB Response: %s' % (url, response.text), __name__, log_utils.LOGDEBUG) return None
def sourcesDirect(self, items): # filter = [i for i in items if i['source'].lower() in self.hostcapDict and i['debrid'] == ''] # items = [i for i in items if not i in filter] # filter = [i for i in items if i['source'].lower() in self.hostblockDict and i['debrid'] == ''] items = [i for i in items] # items = [i for i in items if ('autoplay' in i and i['autoplay'] == True) or not 'autoplay' in i] if control.setting('autoplay.sd') == 'true': items = [i for i in items if not i['quality'] in ['1080p', 'HD']] u = None header = control.addonInfo('name') header2 = header.upper() try: control.sleep(1000) progressDialog = control.progressDialog if control.setting('progress.dialog') == '0' else control.progressDialogBG progressDialog.create(header, '') progressDialog.update(0) except: pass for i in range(len(items)): try: if progressDialog.iscanceled(): break progressDialog.update(int((100 / float(len(items))) * i), str(items[i]['label']), str(' ')) except: progressDialog.update(int((100 / float(len(items))) * i), str(header2), str(items[i]['label'])) try: if xbmc.abortRequested == True: return sys.exit() url = self.sourcesResolve(items[i]) if u == None: u = url if not url == None: break except: pass try: progressDialog.close() except: pass return u
def play(self, title, year, imdb, tvdb, season, episode, tvshowtitle, premiered, meta, select): try: url = None control.moderator() items = self.getSources(title, year, imdb, tvdb, season, episode, tvshowtitle, premiered) select = control.setting('hosts.mode') if select == None else select title = tvshowtitle if not tvshowtitle == None else title if control.window.getProperty('PseudoTVRunning') == 'True': return control.resolve(int(sys.argv[1]), True, control.item(path=str(self.sourcesDirect(items)))) if len(items) > 0: if select == '1' and 'plugin' in control.infoLabel('Container.PluginName'): control.window.clearProperty(self.itemProperty) control.window.setProperty(self.itemProperty, json.dumps(items)) control.window.clearProperty(self.metaProperty) control.window.setProperty(self.metaProperty, meta) control.sleep(200) return control.execute('Container.Update(%s?action=addItem&title=%s)' % (sys.argv[0], urllib.quote_plus(title))) elif select == '0' or select == '1': url = self.sourcesDialog(items) else: url = self.sourcesDirect(items) if url == None: return self.errorForSources() try: meta = json.loads(meta) except: pass from resources.lib.modules.player import player player().run(title, year, season, episode, imdb, tvdb, url, meta) except: pass
def run(self, title, year, season, episode, imdb, tvdb, url, meta): try: control.sleep(200) self.totalTime = 0 self.currentTime = 0 self.content = 'movie' if season is None or episode is None else 'episode' self.title = title self.year = year self.name = urllib.quote_plus(title) + urllib.quote_plus(' (%s)' % year) if self.content == 'movie' else urllib.quote_plus( title) + urllib.quote_plus(' S%02dE%02d' % (int(season), int(episode))) self.name = urllib.unquote_plus(self.name) self.season = '%01d' % int(season) if self.content == 'episode' else None self.episode = '%01d' % int(episode) if self.content == 'episode' else None self.DBID = None self.imdb = imdb if imdb is not None else '0' self.tvdb = tvdb if tvdb is not None else '0' self.ids = {'imdb': self.imdb, 'tvdb': self.tvdb} self.ids = dict((k, v) for k, v in self.ids.iteritems() if not v == '0') self.offset = bookmarks().get(self.name, self.year) poster, thumb, meta = self.getMeta(meta) item = control.item(path=url) item.setArt({'icon': thumb, 'thumb': thumb, 'poster': poster, 'tvshow.poster': poster, 'season.poster': poster}) item.setInfo(type='Video', infoLabels=meta) if 'plugin' in control.infoLabel('Container.PluginName'): control.player.play(url, item) control.resolve(int(sys.argv[1]), True, item) control.window.setProperty('script.trakt.ids', json.dumps(self.ids)) self.keepPlaybackAlive() control.window.clearProperty('script.trakt.ids') except Exception: return
def list_update(self): contains = lib_tools.ckKodiSources() try: dbcon = database.connect(control.libcacheFile) dbcur = dbcon.cursor() dbcur.execute("SELECT * FROM lists WHERE type='tvshows'") results = dbcur.fetchall() if results is None: dbcon.close() return dbcon.close() except: log_utils.error() try: dbcon.close() except: return for list in results: url = list[2] from resources.lib.menus import tvshows items = tvshows.TVshows().get(url, idx=False) if items is None or items == []: return if service_notification and not control.condVisibility('Window.IsVisible(infodialog)') and not control.condVisibility('Player.HasVideo'): control.notification(title = 'default', message = 32552, icon = 'default', time = 1000, sound = notificationSound) total_added = 0 for i in items: try: if xbmc.abortRequested is True: return sys.exit() files_added = self.add(i['title'], i['year'], i['imdb'], i['tvdb'], range=True) if general_notification and files_added > 0: control.notification(title = i['title'], message = 32554, icon = 'default', time = 1000, sound = notificationSound) total_added += 1 except: log_utils.error() pass if self.library_update == 'true' and not control.condVisibility('Library.IsScanningVideo') and total_added > 0: if contains: control.sleep(10000) control.execute('UpdateLibrary(video)') elif service_notification: control.notification(title = 'default', message = 'strm files written but library cannot be updated', icon = 'default', time = 2000, sound = notificationSound)
def setView(content, viewDict=None): for i in range(0, 200): if control.condVisibility('Container.Content(%s)' % content): try: skin = control.skin record = (skin, content) dbcon = database.connect(control.viewsFile) dbcur = dbcon.cursor() dbcur.execute("SELECT * FROM views WHERE skin = '%s' AND view_type = '%s'" % (record[0], record[1])) view = dbcur.fetchone() view = view[2] if view == None: raise Exception() return control.execute('Container.SetViewMode(%s)' % str(view)) except: try: return control.execute('Container.SetViewMode(%s)' % str(viewDict[skin])) except: return control.sleep(100)
def setView(content, viewDict=None): for i in range(0, 200): if control.condVisibility('Container.Content(%s)' % convertView(content)): try: skin = control.skin record = (skin, content) dbcon = database.connect(control.viewsFile) dbcur = dbcon.cursor() dbcur.execute("SELECT * FROM views WHERE skin = '%s' AND view_type = '%s'" % (record[0], record[1])) view = dbcur.fetchone() view = view[2] if view == None: raise Exception() return control.execute('Container.SetViewMode(%s)' % str(view)) except: try: return control.execute('Container.SetViewMode(%s)' % str(viewDict[skin])) except: return control.sleep(100)
def get(): changelogfile = os.path.join(control.addonPath, 'changelog.txt') r = open(changelogfile) text = r.read() id = 10147 control.execute('ActivateWindow(%d)' % id) control.sleep(500) win = xbmcgui.Window(id) retry = 50 while (retry > 0): try: control.sleep(10) retry -= 1 win.getControl(1).setLabel(' [COLOR gold] Marauder [/COLOR]v%s Changelog' % (control.addonInfo('version'))) win.getControl(5).setText(text) return except: pass
def get_request(url): # API calls are rate limited to allow at least 20 calls every 10 seconds per IP address try: try: response = requests.get(url, timeout=10) except requests.exceptions.SSLError: response = requests.get(url, verify=False) except requests.exceptions.ConnectionError: return notification(message=32024) if '200' in str(response): return response.json() elif 'Retry-After' in response.headers: # API REQUESTS ARE BEING THROTTLED, INTRODUCE WAIT TIME throttleTime = response.headers['Retry-After'] notification(message='TVMAZE Throttling Applied, Sleeping for %s seconds' % throttleTime) sleep((int(throttleTime) + 0.5) * 1000) return get_request(url) else: log_utils.log('Get request failed to TVMAZE URL: %s\n msg : TVMAZE Response: %s' % (url, response.text), __name__, log_utils.LOGDEBUG) return None
def run(self, meta): try: control.sleep(200); self.totalTime = 0; self.currentTime = 0; self.offset = '0'; self.content = meta['content']; self.ids = meta['ids']; self.show_id = meta['show_id']; self.asset_id = meta['asset_id']; if(meta['continueplayback'] == 0): self.offset = meta['progress']; self.item = control.item(path=meta['url']); self.item.setArt(meta['art']); self.item.setInfo(type='Video', infoLabels = meta['infoLabels']); if 'plugin' in control.infoLabel('Container.PluginName'): control.player.play(meta['url'], self.item); control.resolve(int(sys.argv[1]), True, self.item); control.window.setProperty('script.trakt.ids', json.dumps(self.ids)); self.keepPlaybackAlive(); control.window.clearProperty('script.trakt.ids'); except Exception as inst: logger.error(inst); return;
def RESTOREFAV(): if os.path.exists(FAVfile): choice = control.yesnoDialog(AddonTitle, 'Do you want to Restore your favorites?', '', '', yeslabel='[B]Yes[/B]', nolabel='[B]No[/B]') if choice == 0: return elif choice == 1: dp.create(AddonTitle, "Restoring", '', 'Please Wait') shutil.copy(FAVfile, USERDATAPATH) control.sleep(5) dp.close() dialog.ok(AddonTitle, '[B]COMPLETE[/B]', 'Your favorites are Restored.', '') else: Notify("[B]%s[/B]" % (AddonTitle), '[B]No Backup found![/B]')
def play(self, type='', name='', year='', url='', imdb='', windowedtrailer=0): try: url = self.worker(type, name, year, url, imdb) if not url: return title = control.infoLabel('ListItem.Title') if not title: title = control.infoLabel('ListItem.Label') icon = control.infoLabel('ListItem.Icon') item = control.item(label=title, iconImage=icon, thumbnailImage=icon, path=url) item.setInfo(type="video", infoLabels={'title': title}) item.setProperty('IsPlayable', 'true') control.refresh() control.resolve(handle=int(argv[1]), succeeded=True, listitem=item) if windowedtrailer == 1: control.sleep(1000) while control.player.isPlayingVideo(): control.sleep(1000) control.execute("Dialog.Close(%s, true)" % control.getCurrentDialogId) except: log_utils.error()
def play(self, name, url=None, windowedtrailer=0): try: url = self.worker(name, url) if not url: return title = control.infoLabel('listitem.title') if not title: title = control.infoLabel('listitem.label') icon = control.infoLabel('listitem.icon') item = control.item(path=url, iconImage=icon, thumbnailImage=icon) try: item.setArt({'icon': icon}) except Exception: pass item.setInfo(type='video', infoLabels={ 'title': title, 'trailer': url }) item.setProperty('IsPlayable', 'true') # Switching over to resolvedUrl like Documentary Indexers and other areas are being moved to control.resolve(handle=int(sys.argv[1]), succeeded=True, listitem=item) if windowedtrailer == 1: # The call to the play() method is non-blocking. So we delay further script execution to keep the script alive at this spot. # Otherwise this script will continue and probably already be garbage collected by the time the trailer has ended. # Wait until playback starts. Less than 900ms is too short (on my box). Make it one second. control.sleep(1000) while control.player.isPlayingVideo(): control.sleep(1000) # Close the dialog. # Same behaviour as the fullscreenvideo window when : # the media plays to the end, # or the user pressed one of X, ESC, or Backspace keys on the keyboard/remote to stop playback. control.execute("Dialog.Close(%s, true)" % control.getCurrentDialogId) except Exception: pass
def get(): import os, xbmcgui from resources.lib.modules import control changelogfile = os.path.join(control.addonPath, 'changelog.txt') r = open(changelogfile) text = r.read() id = 10147 control.execute('ActivateWindow(%d)' % id) control.sleep(500) win = xbmcgui.Window(id) retry = 50 while (retry > 0): try: control.sleep(10) retry -= 1 win.getControl(1).setLabel('--[ [COLOR darkorange] v%s [/COLOR]ChangeLog ]--' %(control.addonInfo('version'))) win.getControl(5).setText(text) return except: pass
def BACKUPFAV(): if not os.path.exists(FAVdest): os.makedirs(FAVdest) if os.path.exists(FAVOURITES): choice = control.yesnoDialog(AddonTitle, 'Do you want to Back-up your favorites?', '', '', yeslabel='[B]Yes[/B]', nolabel='[B]No[/B]') if choice == 0: return elif choice == 1: dp.create(AddonTitle, "Backing Up Favourites", '', 'Please Wait') shutil.copy(FAVOURITES, FAVdest) control.sleep(10) dp.close() dialog.ok(AddonTitle, '[B]COMPLETE[/B]', 'Your favorites are Backed up.', '') else: Notify("[B]%s[/B]" % (AddonTitle), '[B]You have no Favourites![/B]')
def auth_loop(self): control.sleep(5000) response = requests.get(self.check_url, timeout=self.timeout).json() response = response['data'] if 'error' in response: self.token = 'failed' control.notification(message=40021) log_utils.log(40021, __name__, log_utils.LOGWARNING) return if response['activated']: try: control.progressDialog.close() self.token = str(response['apikey']) control.setSetting('alldebrid.token', self.token) except: self.token = 'failed' control.notification(message=40021) log_utils.log(40021, __name__, log_utils.LOGWARNING) return return
def run(self, anime_id, ep_id, url): control.sleep(200) self.anime_id = int(anime_id) self.episode_id = int(ep_id) item = control.item(path=url) try: c = cache.get(masterani.get_anime_details, 3, self.anime_id) ctype = c['type'] ctype = 'video' if int(ctype) is 2 else 'episode' tvshowtitle = c['title'] poster = c['poster'][0] item.setArt({'thumb': poster, 'poster': poster, 'tvshow.poster': poster, 'season.poster': poster}) e = c['episodes'][self.episode_id] title = e['info']['title'] season = 1 if season is None: season = 1 episode = e['info']['episode'] if ctype is 'video': title = c['title'] if title is None: title = "Episode %s" % episode item.setInfo(type="video", infoLabels={'tvshowtitle': title, 'title': tvshowtitle, 'episode': int(episode), 'season': int(season), 'mediatype': ctype}) except: pass item.setProperty('Video', 'true') item.setProperty('IsPlayable', 'true') self.play(url, item) self.playback_checker() pass
def run(self, title, url, xbmc_id, content): try: control.sleep(200) self.content = 'movie' if content == 'movie' else 'episode' self.title = title self.DBID = xbmc_id self.imdb = '' self.name = cleantitle.get(title) + str(self.DBID) #print ("PREMIUMIZE PLAYER", self.title, self.DBID, self.content, url) poster, thumb, fanart, meta = self.getMeta() #print ("PREMIUMIZE PLAYER 2", url, self.title, self.DBID, poster, thumb, fanart, meta) if self.content == 'movie': self.ids = {'imdb': self.imdb} else: self.ids = {'imdb': self.imdb, 'tvdb': self.imdb} self.ids = dict( (k, v) for k, v in self.ids.iteritems() if not v == '0') item = control.item(path=url) item.setArt({ 'icon': thumb, 'thumb': thumb, 'poster': thumb, 'fanart': thumb }) item.setInfo(type='Video', infoLabels=meta) control.resolve(int(sys.argv[1]), True, item) control.window.setProperty('script.trakt.ids', json.dumps(self.ids)) self.keepPlaybackAlive() control.window.clearProperty('script.trakt.ids') except: return
def run(self, title, url, meta): try: control.sleep(200) self.totalTime = 0 self.currentTime = 0 self.name = '%s' % title poster = meta['poster'].encode( 'utf-8') if 'poster' in meta else '0' title = meta['title'].encode( 'utf-8') if 'title' in meta else self.name print("PLAYER ITEMS", title, url, poster) if url.startswith('http') and '.m3u8' in url: url = url elif "|directplay" in url: url = url.split('|')[0] else: hmf = urlresolver.HostedMediaFile(url=url, include_disabled=True, include_universal=True) url = hmf.resolve() #control.do_block_check(False) item = control.item(path=url) item.setArt({ 'icon': poster, 'thumb': poster, 'poster': poster, 'tvshow.poster': poster, 'season.poster': poster }) item.setInfo(type='Video', infoLabels={"Title": title}) print("PLAYER ITEMS 2", title, url, meta) if 'plugin' in control.infoLabel('Container.PluginName'): control.player.play(url, item) control.resolve(int(sys.argv[1]), True, item) except: return
def sourcesDirect(self, items, progress=True): filter = [i for i in items if i['source'].lower() in self.hostcapDict and i['debrid'] == ''] items = [i for i in items if not i in filter] items = [i for i in items if ('autoplay' in i and i['autoplay'] == True) or not 'autoplay' in i] if control.setting('autoplay.sd') == 'true': items = [i for i in items if not i['quality'] in ['1080p', 'HD']] u = None try: if not progress == True: raise Exception() control.sleep(1000) self.progressDialog = control.progressDialog self.progressDialog.create(control.addonInfo('name'), '') self.progressDialog.update(0) except: pass for i in range(len(items)): try: if not progress == True: raise Exception() self.progressDialog.update(int((100 / float(len(items))) * i), str(items[i]['label']), str(' ')) if self.progressDialog.iscanceled(): break except: pass try: if xbmc.abortRequested == True: return sys.exit() url = self.sourcesResolve(items[i]) if u == None: u = url if not url == None: break except: pass try: self.progressDialog.close() except: pass return u
def play(self, imdb, name, tmdb='', season='', episode='', windowedtrailer=0): try: if not imdb or imdb == '0': raise Exception() item_dict = self.get_items(imdb, name) if not item_dict: raise Exception('IMDb_trailer failed, trying TMDb') elif item_dict == 'canceled': return url, title, plot = item_dict['video'], item_dict[ 'title'], item_dict['description'] icon = control.infoLabel('ListItem.Icon') item = control.item(label=title, path=url) item.setArt({'icon': icon, 'thumb': icon, 'poster': icon}) item.setInfo(type='video', infoLabels={ 'title': title, 'plot': plot }) item.setProperty('IsPlayable', 'true') control.resolve(handle=int(sys.argv[1]), succeeded=True, listitem=item) if windowedtrailer == 1: control.sleep(1000) while control.player.isPlayingVideo(): control.sleep(1000) control.execute('Dialog.Close(%s, true)' % control.getCurrentDialogId) except: log_utils.log('IMDb_trailer fail', 1) TMDb_trailer().play(tmdb, imdb, season, episode)
def auth(self): self.token = '' url = base_url + 'pin/get?agent=%s' % user_agent response = requests.get(url, timeout=self.timeout).json() response = response['data'] control.progressDialog.create(control.lang(40056)) control.progressDialog.update(-1, control.lang(32513) % 'https://alldebrid.com/pin/', control.lang(32514) % response['pin']) self.check_url = response.get('check_url') control.sleep(2000) while not self.token: if control.progressDialog.iscanceled(): control.progressDialog.close() break self.auth_loop() if self.token in (None, '', 'failed'): return control.sleep(2000) account_info = self._get('user') control.notification(title='default', message=40010, icon=pm_icon)
def check_for_addon_update(): try: if control.setting('general.checkAddonUpdates') == 'false': return import re import requests repo_xml = requests.get('https://raw.githubusercontent.com/123Venom/zips/master/addons.xml') if not repo_xml.status_code == 200: log_utils.log('Could not connect to repo XML, status: %s' % repo_xml.status_code, log_utils.LOGNOTICE) return repo_version = re.findall(r'<addon id=\"plugin.video.venom\" version=\"(\d*.\d*.\d*)\"', repo_xml.text)[0] local_version = control.getVenomVersion() if control.check_version_numbers(local_version, repo_version): while control.condVisibility('Library.IsScanningVideo'): control.sleep(10000) log_utils.log('A newer version of Venom is available. Installed Version: v%s, Repo Version: v%s' % (local_version, repo_version), log_utils.LOGNOTICE) control.notification(title = 'default', message = control.lang(35523) % repo_version, icon = 'default', time=5000, sound=False) except: pass
def auth(self): data = {'client_id': CLIENT_ID, 'response_type': 'device_code'} token = requests.post('https://www.premiumize.me/token', data=data, timeout=15).json() expiry = float(token['expires_in']) token_ttl = token['expires_in'] poll_again = True success = False line = '%s\n%s' progressDialog = control.progressDialog progressDialog.create(control.lang(40054)) progressDialog.update(-1, line % (control.lang(32513) % token['verification_uri'], control.lang(32514) % token['user_code'])) while poll_again and not token_ttl <= 0 and not progressDialog.iscanceled(): poll_again, success = self.poll_token(token['device_code']) progress_percent = 100 - int((float((expiry - token_ttl) / expiry) * 100)) progressDialog.update(progress_percent) control.sleep(token['interval'] * 1000) token_ttl -= int(token['interval']) progressDialog.close() if success: control.notification(message=40052, icon=pm_icon) log_utils.log('Premiumize.me Successfully Authorized', __name__, log_utils.LOGDEBUG)
def run(self, title, year, season, episode, imdb, tvdb, url, meta): try: control.sleep(200) self.totalTime = 0 ; self.currentTime = 0 self.content = 'movie' if season == None or episode == None else 'episode' self.title = title ; self.year = year self.name = urllib.quote_plus(title) + urllib.quote_plus(' (%s)' % year) if self.content == 'movie' else urllib.quote_plus(title) + urllib.quote_plus(' S%02dE%02d' % (int(season), int(episode))) self.name = urllib.unquote_plus(self.name) self.season = '%01d' % int(season) if self.content == 'episode' else None self.episode = '%01d' % int(episode) if self.content == 'episode' else None self.DBID = None self.imdb = imdb if not imdb == None else '0' self.tvdb = tvdb if not tvdb == None else '0' self.ids = {'imdb': self.imdb, 'tvdb': self.tvdb} self.ids = dict((k,v) for k, v in self.ids.iteritems() if not v == '0') self.offset = bookmarks().get(self.name, self.year) poster, thumb, meta = self.getMeta(meta) item = control.item(path=url) item.setArt({'icon': thumb, 'thumb': thumb, 'poster': poster, 'tvshow.poster': poster, 'season.poster': poster}) item.setInfo(type='Video', infoLabels = meta) if 'plugin' in control.infoLabel('Container.PluginName'): control.player.play(url, item) control.resolve(int(sys.argv[1]), True, item) control.window.setProperty('script.trakt.ids', json.dumps(self.ids)) self.keepPlaybackAlive() control.window.clearProperty('script.trakt.ids') except: return
def run(self, meta): try: control.sleep(200) self.totalTime = 0 self.currentTime = 0 self.offset = '0' self.content = meta['content'] self.ids = meta['ids'] self.show_id = meta['show_id'] self.asset_id = meta['asset_id'] if (meta['continueplayback'] == 0): self.offset = meta['progress'] self.item = control.item(path=meta['url']) self.item.setArt(meta['art']) self.item.setInfo(type='Video', infoLabels=meta['infoLabels']) if 'plugin' in control.infoLabel('Container.PluginName'): control.player.play(meta['url'], self.item) control.resolve(int(sys.argv[1]), True, self.item) control.window.setProperty('script.trakt.ids', json.dumps(self.ids)) self.keepPlaybackAlive() control.window.clearProperty('script.trakt.ids') except Exception as inst: logger.error(inst) return
def add(self, name, title, year, imdb, tmdb, range=False): try: contains = lib_tools().ckKodiSources() if general_notification: if not control.condVisibility('Window.IsVisible(infodialog)') and not control.condVisibility('Player.HasVideo'): control.notification(title=name, message=32552) try: if not self.dupe_chk == 'true': raise Exception() id = [imdb, tmdb] if tmdb != '0' else [imdb] lib = control.jsonrpc('{"jsonrpc": "2.0", "method": "VideoLibrary.GetMovies", "params": {"filter":{"or": [{"field": "year", "operator": "is", "value": "%s"}, {"field": "year", "operator": "is", "value": "%s"}, {"field": "year", "operator": "is", "value": "%s"}]}, "properties" : ["imdbnumber", "title", "originaltitle", "year"]}, "id": 1}' % (year, str(int(year)+1), str(int(year)-1))) lib = py_tools.ensure_text(lib, errors='ignore') lib = jsloads(lib)['result']['movies'] # lib = [i for i in lib if str(i['imdbnumber']) in id or (cleantitle.get(title) in [cleantitle.get(i['title'].encode('utf-8')), cleantitle.get(i['originaltitle'].encode('utf-8'))] and str(i['year']) == year)] lib = [i for i in lib if str(i['imdbnumber']) in id or (cleantitle.get(title) in [cleantitle.get(i['title']), cleantitle.get(i['originaltitle'])] and str(i['year']) == year)] except: lib = [] files_added = 0 try: if lib != []: raise Exception() if self.check_setting == 'true': src = lib_tools.check_sources(title, year, imdb, None, None, None, None, None) if not src: raise Exception() self.strmFile({'name': name, 'title': title, 'year': year, 'imdb': imdb, 'tmdb': tmdb}) files_added += 1 except: pass if files_added == 0 and general_notification: control.notification(title=name, message=32652) if range: return files_added if self.library_update == 'true' and not control.condVisibility('Library.IsScanningVideo') and files_added > 0: if contains: if general_notification: control.notification(title=name, message=32554) control.sleep(10000) control.execute('UpdateLibrary(video)') elif general_notification: control.notification(title=name, message=32104) except: pass
def create_transfer(self, media_id, folder_id=0): try: data = {'src': media_id, 'folder_id': folder_id} response = self._post(transfer_create, data=data) if response: if response.get('status') == 'success': control.notification( title='default', message= 'Transfer successfully started to the Premiumize.me cloud', icon='default') percent_list = [25, 50, 75] while True: control.sleep(10 * 1000 * 60) # 10min item = self.id_transfer_status(response.get('id')) if item.get('status') == 'running': for i in percent_list: if item.get('progress') * 100 >= i: percent_list.remove(i) control.notification( title='default', message='PM stransfer = ' + str(item.get('progress') * 100) + '% complete', icon='default') if item.get('status') == 'seeding': control.notification( title='default', message='PM stransfer complete', icon='default') break # self.clear_finished_transfers() # PM issue with doing this return else: return except: log_utils.error() pass return
def play(self, title, year, imdb, tvdb, season, episode, tvshowtitle, premiered, meta, url): try: if not control.addonInfo('id').lower() == control.infoLabel('Container.PluginName').lower(): progress = True if control.setting('progress.dialog') == '1' else False else: control.resolve(int(sys.argv[1]), True, control.item(path='')) control.execute('Dialog.Close(okdialog)') progress = True if 'super.fav' in control.infoLabel('Container.PluginName'): return control.dialog.ok('Exodus', control.lang(30518).encode('utf-8'), '', '') self.sources = self.getSources(title, year, imdb, tvdb, season, episode, tvshowtitle, premiered, progress=progress) self.sources = self.sourcesFilter() if control.window.getProperty('PseudoTVRunning') == 'True': return control.resolve(int(sys.argv[1]), True, control.item(path=str(self.sourcesDirect(progress=progress)))) if self.sources == []: raise Exception() if url == 'direct://': url = self.sourcesDirect(progress=progress) elif url == 'dialog://': url = self.sourcesDialog(progress=progress) elif control.setting('autoplay') == 'false': url = self.sourcesDialog(progress=progress) else: url = self.sourcesDirect(progress=progress) if url == None: raise Exception() if url == 'close://': return control.sleep(200) if not tvshowtitle == None: title = tvshowtitle from resources.lib.modules.player import player player().run(title, year, season, episode, imdb, tvdb, meta, url) return url except: control.infoDialog(control.lang(30501).encode('utf-8'))
def run(self, title, year, season, episode, imdb, tvdb, url, meta): try: control.sleep(200) self.totalTime = 0 ; self.currentTime = 0 self.original_meta = meta self.content = 'movie' if season == None or episode == None else 'episode' self.title = title ; self.year = year self.name = '%s (%s)' % (title, year) if self.content == 'movie' else '%s S%02dE%02d' % (title, int(season), int(episode)) self.season = '%01d' % int(season) if self.content == 'episode' else None self.episode = '%01d' % int(episode) if self.content == 'episode' else None self.imdb = imdb if not imdb == None else '0' self.tvdb = tvdb if not tvdb == None else '0' self.ids = {'imdb': self.imdb, 'tvdb': self.tvdb} self.ids = dict((k,v) for k, v in self.ids.iteritems() if not v == '0') self.offset = bookmarks().get(self.name, self.year) poster, thumb, meta = self.getMeta(meta) item = control.item(path=url) item.setArt({'icon': thumb, 'thumb': thumb, 'poster': poster, 'tvshow.poster': poster, 'season.poster': poster}) item.setInfo(type='Video', infoLabels = meta) # control.do_block_check(False) if 'plugin' in control.infoLabel('Container.PluginName'): control.player.play(url, item) control.resolve(int(sys.argv[1]), True, item) self.keepPlaybackAlive() except: return
def play(self, title, year, imdb, tmdb, tvdb, season, episode, tvshowtitle, premiered, meta, url): try: if not control.addonInfo('id').lower() == control.infoLabel('Container.PluginName').lower(): progress = True if control.setting('progress.dialog') == '1' else False else: control.resolve(int(sys.argv[1]), True, control.item(path='')) control.execute('Dialog.Close(okdialog)') progress = True if 'super.fav' in control.infoLabel('Container.PluginName'): return control.dialog.ok('Exodus', control.lang(30518).encode('utf-8'), '', '') self.sources = self.getSources(title, year, imdb, tmdb, tvdb, season, episode, tvshowtitle, premiered, progress=progress) self.sources = self.sourcesFilter() if control.window.getProperty('PseudoTVRunning') == 'True': return control.resolve(int(sys.argv[1]), True, control.item(path=str(self.sourcesDirect(progress=progress)))) if self.sources == []: raise Exception() if url == 'direct://': url = self.sourcesDirect(progress=progress) elif url == 'dialog://': url = self.sourcesDialog(progress=progress) elif control.setting('autoplay') == 'false': url = self.sourcesDialog(progress=progress) else: url = self.sourcesDirect(progress=progress) if url == None: raise Exception() if url == 'close://': return control.sleep(200) if not tvshowtitle == None: title = tvshowtitle from resources.lib.modules.player import player player().run(title, year, season, episode, imdb, tmdb, tvdb, meta, url) return url except: control.infoDialog(control.lang(30501).encode('utf-8'))
def setView(content, viewDict=None): for i in range(0, 200): if control.condVisibility('Container.Content(%s)' % content): try: skin = control.skin record = (skin, content) dbcon = db.connect(control.viewsFile) dbcur = dbcon.cursor() view = dbcur.execute('''SELECT * FROM views WHERE (skin=? AND view_type=?)''', (record[0], record[1])).fetchone() if not view: raise Exception() view = view[2] return control.execute('Container.SetViewMode(%s)' % str(view)) except: try: if skin not in viewDict: return else: return control.execute('Container.SetViewMode(%s)' % str(viewDict[skin])) except: from resources.lib.modules import log_utils log_utils.error() return finally: dbcur.close() ; dbcon.close() control.sleep(100)
def play(self, url, content=None): try: base = url url = resolver().get(url) if url is False: return control.execute('ActivateWindow(busydialog)') url = resolver().process(url) control.execute('Dialog.Close(busydialog)') if url is None: return control.notification(title='default', message=30705, icon='default', sound=(control.setting('notification.sound') == 'true')) if url is 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 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 is 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 debrid_check_dialog(self): progressDialog = control.progressDialogBG timeout = 20 progressDialog.create('Checking debrid cache, please wait..') #progressDialog.update(0) start_time = time.time() end_time = start_time + timeout while not progressDialog.isFinished(): try: if control.monitor.abortRequested(): return sys.exit() alive_threads = [ x.getName() for x in self.main_threads if x.is_alive() is True ] remaining_debrids = [ x[1] for x in self.starting_debrids_display if x[0] in alive_threads ] current_time = time.time() current_progress = current_time - start_time try: percent = int((current_progress / float(timeout)) * 100) msg = 'Remaining Debrid Checks: %s' % ', '.join( remaining_debrids).upper() progressDialog.update(percent, message=msg) except: pass time.sleep(0.1) if len(alive_threads) == 0: break if current_time > end_time: break except Exception: pass try: progressDialog.close() except Exception: pass control.sleep(200)
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 run(self, url, selectGame ,side): if selectGame == None or side == None: return control.resolve(int(sys.argv[1]), True, control.item(path=url)) if not control.setting('droid') == 'true': command = ['java','-jar',jarFile,selectGame,side] startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW self.process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, startupinfo=startupinfo) if os.name == 'posix': success = False success, output = FuckNeulionClient.request_proxy_hack(selectGame,side) else: if os.name == 'posix': success = False control.sleep(1000) control.resolve(int(sys.argv[1]), True, control.item(path=url)) for i in range(0, 240): if self.isPlayingVideo(): break control.sleep(1000) while self.isPlayingVideo(): control.sleep(1000) control.sleep(5000)
def playItem(self, title, source): try: meta = control.window.getProperty(self.metaProperty) meta = json.loads(meta) year = meta['year'] if 'year' in meta else None season = meta['season'] if 'season' in meta else None episode = meta['episode'] if 'episode' in meta else None imdb = meta['imdb'] if 'imdb' in meta else None tvdb = meta['tvdb'] if 'tvdb' in meta else None next = [] ; prev = [] ; total = [] for i in range(1,1000): try: u = control.infoLabel('ListItem(%s).FolderPath' % str(i)) if u in total: raise Exception() total.append(u) u = dict(urlparse.parse_qsl(u.replace('?',''))) u = json.loads(u['source'])[0] next.append(u) except: break for i in range(-1000,0)[::-1]: try: u = control.infoLabel('ListItem(%s).FolderPath' % str(i)) if u in total: raise Exception() total.append(u) u = dict(urlparse.parse_qsl(u.replace('?',''))) u = json.loads(u['source'])[0] prev.append(u) except: break items = json.loads(source) items = [i for i in items+next+prev][:20] header = control.addonInfo('name') header2 = header.upper() progressDialog = control.progressDialog if control.setting('progress.dialog') == '0' else control.progressDialogBG progressDialog.create(header, '') progressDialog.update(0) block = None for i in range(len(items)): try: try: if progressDialog.iscanceled(): break progressDialog.update(int((100 / float(len(items))) * i), str(items[i]['label']), str(' ')) except: progressDialog.update(int((100 / float(len(items))) * i), str(header2), str(items[i]['label'])) if items[i]['source'] == block: raise Exception() w = workers.Thread(self.sourcesResolve, items[i]) w.start() m = '' for x in range(3600): try: if xbmc.abortRequested == True: return sys.exit() if progressDialog.iscanceled(): return progressDialog.close() except: pass k = control.condVisibility('Window.IsActive(virtualkeyboard)') if k: m += '1'; m = m[-1] if (w.is_alive() == False or x > 30) and not k: break k = control.condVisibility('Window.IsActive(yesnoDialog)') if k: m += '1'; m = m[-1] if (w.is_alive() == False or x > 30) and not k: break time.sleep(0.5) for x in range(30): try: if xbmc.abortRequested == True: return sys.exit() if progressDialog.iscanceled(): return progressDialog.close() except: pass if m == '': break if w.is_alive() == False: break time.sleep(0.5) if w.is_alive() == True: block = items[i]['source'] if self.url == None: raise Exception() try: progressDialog.close() except: pass control.sleep(200) control.execute('Dialog.Close(virtualkeyboard)') control.execute('Dialog.Close(yesnoDialog)') from resources.lib.modules.player import player player().run(title, year, season, episode, imdb, tvdb, self.url, meta) return self.url except: pass try: progressDialog.close() except: pass self.errorForSources() except: pass
def resolve(self, url): try: m3u8 = [ [ '#EXTM3U', '', '#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH={bandwidth},NAME="{stream_name}"', '{video_stream}' ], [ '#EXTM3U', '#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="{audio_group}",DEFAULT=YES,AUTOSELECT=YES,NAME="Stream 1",URI="{audio_stream}"', '', '#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH={bandwidth},NAME="{stream_name}",AUDIO="{audio_group}"', '{video_stream}' ] ] query = urlparse.parse_qs(url) query = dict([(key, query[key][0]) if query[key] else (key, '') for key in query]) for i in m3u8: try: content = ('\n'.join(i)).format(**query) except: pass auth = query['video_stream'] r = client.request(auth, headers={'User-Agent': 'Lavf/56.40.101'}) try: url = json.loads(r)['url'] except: url = None if not url == None: def dialog(url): try: self.disableScraper = control.yesnoDialog('To watch this video visit from any device', '[COLOR skyblue]%s[/COLOR]' % url, '', 'Torba', 'Cancel', 'Settings') except: pass workers.Thread(dialog, url).start() control.sleep(3000) for i in range(100): try: if not control.condVisibility('Window.IsActive(yesnoDialog)'): break r = client.request(auth, headers={'User-Agent': 'Lavf/56.40.101'}) try: url = json.loads(r)['url'] except: url = None if url == None: break workers.Thread(dialog, url).start() control.sleep(3000) except: pass if self.disableScraper: control.openSettings(query='2.0') return '' control.execute('Dialog.Close(yesnoDialog)') if not url == None: return path = os.path.join(control.dataPath, 'torbase.m3u8') control.makeFile(control.dataPath) ; control.deleteFile(path) file = control.openFile(path, 'w') ; file.write(content) ; file.close() return path except: return
def playItem(self, source): try: f = dict(urlparse.parse_qsl(control.infoLabel('Container.FolderPath').replace('?',''))) meta = f['meta'] if 'meta' in f else None title = f['title'] if 'title' in f else None title = f['tvshowtitle'] if 'tvshowtitle' in f else title year = f['year'] if 'year' in f else None season = f['season'] if 'season' in f else None episode = f['episode'] if 'episode' in f else None imdb = f['imdb'] if 'imdb' in f else None tvdb = f['tvdb'] if 'tvdb' in f else None next = [] ; prev = [] ; total = [] for i in range(1,1000): try: u = control.infoLabel('ListItem(%s).FolderPath' % str(i)) if u in total: raise Exception() total.append(u) u = dict(urlparse.parse_qsl(u.replace('?',''))) u = json.loads(u['source'])[0] next.append(u) except: break for i in range(-1000,0)[::-1]: try: u = control.infoLabel('ListItem(%s).FolderPath' % str(i)) if u in total: raise Exception() total.append(u) u = dict(urlparse.parse_qsl(u.replace('?',''))) u = json.loads(u['source'])[0] prev.append(u) except: break items = json.loads(source) items = [i for i in items+next+prev][:20] self.progressDialog = control.progressDialog self.progressDialog.create(control.addonInfo('name'), '') self.progressDialog.update(0) block = None for i in range(len(items)): try: self.progressDialog.update(int((100 / float(len(items))) * i), str(items[i]['label']), str(' ')) if items[i]['source'] == block: raise Exception() w = workers.Thread(self.sourcesResolve, items[i]) w.start() m = '' for x in range(3600): if self.progressDialog.iscanceled(): return self.progressDialog.close() if xbmc.abortRequested == True: return sys.exit() k = control.condVisibility('Window.IsActive(virtualkeyboard)') if k: m += '1'; m = m[-1] if (w.is_alive() == False or x > 30) and not k: break k = control.condVisibility('Window.IsActive(yesnoDialog)') if k: m += '1'; m = m[-1] if (w.is_alive() == False or x > 30) and not k: break time.sleep(0.5) for x in range(30): if m == '': break if self.progressDialog.iscanceled(): return self.progressDialog.close() if xbmc.abortRequested == True: return sys.exit() if w.is_alive() == False: break time.sleep(0.5) if w.is_alive() == True: block = items[i]['source'] if self.url == None: raise Exception() try: self.progressDialog.close() except: pass control.sleep(200) control.execute('Dialog.Close(virtualkeyboard)') control.execute('Dialog.Close(yesnoDialog)') from resources.lib.modules.player import player player().run(title, year, season, episode, imdb, tvdb, meta, self.url) return self.url except: pass try: self.progressDialog.close() except: pass raise Exception() except: control.infoDialog(control.lang(30501).encode('utf-8')) pass
def onPlayBackStarted(self): control.sleep(200) control.idle()
def service(self): try: lib_tools.create_folder(os.path.join(control.transPath(control.setting('library.movie')), '')) lib_tools.create_folder(os.path.join(control.transPath(control.setting('library.tv')), '')) except: pass try: control.makeFile(control.dataPath) dbcon = database.connect(control.libcacheFile) dbcur = dbcon.cursor() dbcur.execute("CREATE TABLE IF NOT EXISTS service (""setting TEXT, ""value TEXT, ""UNIQUE(setting)"");") dbcur.execute("SELECT * FROM service WHERE setting = 'last_run'") fetch = dbcur.fetchone() if fetch == None: serviceProperty = "1970-01-01 23:59:00.000000" dbcur.execute("INSERT INTO service Values (?, ?)", ('last_run', serviceProperty)) dbcon.commit() else: serviceProperty = str(fetch[1]) dbcon.close() except: try: return dbcon.close() except: return try: control.window.setProperty(self.property, serviceProperty) except: return while not xbmc.abortRequested: try: serviceProperty = control.window.getProperty(self.property) t1 = datetime.timedelta(hours=6) t2 = datetime.datetime.strptime(serviceProperty, '%Y-%m-%d %H:%M:%S.%f') t3 = datetime.datetime.now() check = abs(t3 - t2) > t1 if check == False: raise Exception() if (control.player.isPlaying() or control.condVisibility('Library.IsScanningVideo')): raise Exception() serviceProperty = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f') control.window.setProperty(self.property, serviceProperty) try: dbcon = database.connect(control.libcacheFile) dbcur = dbcon.cursor() dbcur.execute("CREATE TABLE IF NOT EXISTS service (""setting TEXT, ""value TEXT, ""UNIQUE(setting)"");") dbcur.execute("DELETE FROM service WHERE setting = 'last_run'") dbcur.execute("INSERT INTO service Values (?, ?)", ('last_run', serviceProperty)) dbcon.commit() dbcon.close() except: try: dbcon.close() except: pass if not control.setting('library.service.update') == 'true': raise Exception() info = control.setting('library.service.notification') or 'true' self.update(info=info) except: pass control.sleep(10000)
def run(self, anime_id, ep_id, url, synop, start_date, start_year, gen, epnum, epcount, eplink): control.sleep(200) self.anime_id = int(anime_id) self.episode_id = int(ep_id) item = control.item(path=url) try: c = cache.get(masterani.get_anime_details, 3, self.anime_id) ctype = c['type'] ctype = 'movie' if int(ctype) is 2 else 'episode' tvshowtitle = c['title'] poster = c['poster'] coverlink = "http://cdn.masterani.me/poster/" + poster print coverlink item.setArt({'icon': coverlink, 'thumb': coverlink, 'poster': coverlink, 'tvshow.poster': coverlink, 'season.poster': coverlink}) e = c['episodes'][self.episode_id] title = e['info']['title'] season2options = [': Season 2', ' Season 2', ': 2nd Season', ': Second Season', ' 2nd Season', ' Second Season', ': Part 2', ' Part 2', ': Part II', ' Part II'] season3options = [': Season 3', ' Season 3', ': 3rd Season', ': Third Season', ' 3rd Season', ' Third Season', ': Part 3', ' Part 3', ': Part III', ' Part III'] season4options = [': Season 4', ' Season 4', ': 4th Season', ': Fourth Season', ' 4th Season', ' Fourth Season', ': Part 4', ' Part 4', ': Part IV', ' Part IV'] season5options = [': Season 5', ' Season 5', ': 5th Season', ': Fifth Season', ' 5th Season', ' Fifth Season', ': Part 5', ' Part 5', ': Part V', ' Part V'] season = 1 for option in season2options: if option in tvshowtitle: tvshowtitle = tvshowtitle.replace(option, "") season = 2 for option in season3options: if option in tvshowtitle: tvshowtitle = tvshowtitle.replace(option, "") season = 3 for option in season4options: if option in tvshowtitle: tvshowtitle = tvshowtitle.replace(option, "") season = 4 for option in season5options: if option in tvshowtitle: tvshowtitle = tvshowtitle.replace(option, "") season = 5 episode = e['info']['episode'] if ctype is 'video': title = c['title'] if title is None: title = "Episode %s" % episode item.setInfo(type="video", infoLabels={'tvshowtitle': title, 'title': tvshowtitle, 'episode': int(episode), 'season': int(season), 'mediatype': ctype}) #year = e['info']['aired'].split("-", 1)[0] #plot = e['info']['description'] if 'movie' in ctype: year = start_year plot = synop genre = gen item.setInfo(type="video", infoLabels={'year': year, 'plot': plot, 'genre': genre}) else: year = e['info']['aired'].split("-", 1)[0] plot = e['info']['description'] item.setInfo(type="video", infoLabels={'year': year, 'plot': plot, 'genre': gen}) except: pass item.setProperty('Video', 'true') item.setProperty('IsPlayable', 'true') trackyesno = control.getSetting("track.yesno") tracktype = control.getSetting("track.type") if trackyesno == "true" and tracktype == 'Kitsu': kitsu.KitsuScrobbler().kitsu_initScrobble(tvshowtitle, start_date, epnum, epcount) else: pass self.play(url, item) self.playback_checker(self.anime_id, eplink) pass
def run(self, anime_id, ep_id, url, synop, start, gen, epnum, epcount): control.sleep(200) self.anime_id = int(anime_id) self.episode_id = int(ep_id) item = control.item(path=url) try: c = cache.get(masterani.get_anime_details, 3, self.anime_id) ctype = c['type'] ctype = 'movie' if int(ctype) is 2 else 'episode' tvshowtitle = c['title'] poster = c['poster'] coverlink = "http://cdn.masterani.me/poster/" + poster print coverlink item.setArt({'icon': coverlink, 'thumb': coverlink, 'poster': coverlink, 'tvshow.poster': coverlink, 'season.poster': coverlink}) e = c['episodes'][self.episode_id] title = e['info']['title'] season2options = [' Season 2', ' 2nd Season', ' Second Season', ': Season 2', ': 2nd Season', ': Second Season', ' II ', ': II '] season3options = [' Season 3', ' 3rd Season', ' Third Season', ': Season 3', ': 3rd Season', ': Third Season', ' III ', ': III '] season4options = [' Season 4', ' 4th Season', ' Fourth Season', ': Season 4', ': 4th Season', ': Fourth Season', ' IV ', ': IV '] season5options = [' Season 5', ' 5th Season', ' Fifth Season', ': Season 5', ': 5th Season', ': Fifth Season', ' V ', ': V '] season = 1 if ctype = 'episode': if "Lupin III" not in tvshowtitle: for option in season2options: if option in tvshowtitle: tvshowtitle = tvshowtitle.replace(option, "") season = 2 for option in season3options: if option in tvshowtitle: tvshowtitle = tvshowtitle.replace(option, "") season = 3 for option in season4options: if option in tvshowtitle: tvshowtitle = tvshowtitle.replace(option, "") season = 4 for option in season5options: if option in tvshowtitle: tvshowtitle = tvshowtitle.replace(option, "") season = 5 episode = e['info']['episode'] if ctype is 'video': title = c['title'] if title is None: title = "Episode %s" % episode item.setInfo(type="video", infoLabels={'tvshowtitle': title, 'title': tvshowtitle, 'episode': int(episode), 'season': int(season), 'mediatype': ctype}) #year = e['info']['aired'].split("-", 1)[0] #plot = e['info']['description'] if 'movie' in ctype: year = start plot = synop genre = gen item.setInfo(type="video", infoLabels={'year': year, 'plot': plot, 'genre': genre}) else: year = e['info']['aired'].split("-", 1)[0] plot = e['info']['description'] item.setInfo(type="video", infoLabels={'year': year, 'plot': plot, 'genre': gen})
def resolve(self, url): try: m3u8 = [ '#EXTM3U', '#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="audio",DEFAULT=YES,AUTOSELECT=YES,NAME="Stream 1",URI="{audio_stream}"', '', '#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=0,NAME="{stream_name}",AUDIO="audio"', '{video_stream}' ] query = urlparse.parse_qs(url) query = dict([(key, query[key][0]) if query[key] else (key, '') for key in query]) auth = 'http://streamtorrent.tv/api/torrent/%s/%s.m3u8?json=true' % (query['vid_id'], query['stream_id']) r = client.request(auth) r = json.loads(r) try: url = r['url'] except: url = None if not url == None: def dialog(url): try: self.disableScraper = control.yesnoDialog('Torba requires you visit, on any device, the following url to watch this video:', '[COLOR skyblue]%s[/COLOR]' % url, '', 'Torba', 'Cancel', 'Settings') except: pass workers.Thread(dialog, url).start() control.sleep(3000) for i in range(100): try: if not control.condVisibility('Window.IsActive(yesnoDialog)'): break r = client.request(auth) r = json.loads(r) try: url = r['url'] except: url = None if url == None: break workers.Thread(dialog, url).start() control.sleep(3000) except: pass if self.disableScraper: control.openSettings(query='2.0') return '' control.execute('Dialog.Close(yesnoDialog)') if not url == None: return stream_name = '%sp' % (query['height']) video_stream = r[stream_name] if not 'audio' in r: return video_stream audio_stream = r['audio'] content = ('\n'.join(m3u8)).format(**{'audio_stream': audio_stream, 'stream_name': stream_name, 'video_stream': video_stream}) path = os.path.join(control.dataPath, 'torbase.m3u8') control.makeFile(control.dataPath) ; control.deleteFile(path) file = control.openFile(path, 'w') ; file.write(content) ; file.close() return path except: return
def service(self): try: control.makeFile(control.dataPath) dbcon = database.connect(control.libcacheFile) dbcur = dbcon.cursor() dbcur.execute("CREATE TABLE IF NOT EXISTS service (" "setting TEXT, " "value TEXT, " "UNIQUE(setting)" ");") dbcur.execute("SELECT * FROM service WHERE setting = 'last_run'") fetch = dbcur.fetchone() if fetch == None: serviceProperty = "1970-01-01 23:59:00.000000" dbcur.execute("INSERT INTO service Values (?, ?)", ("last_run", serviceProperty)) dbcon.commit() else: serviceProperty = str(fetch[1]) dbcon.close() except: try: return dbcon.close() except: return try: control.window.setProperty(self.property, serviceProperty) except: return while not xbmc.abortRequested: try: serviceProperty = control.window.getProperty(self.property) t1 = datetime.timedelta(hours=6) t2 = datetime.datetime.strptime(serviceProperty, "%Y-%m-%d %H:%M:%S.%f") t3 = datetime.datetime.now() check = abs(t3 - t2) > t1 if check == False: raise Exception() if control.player.isPlaying() or control.condVisibility("Library.IsScanningVideo"): raise Exception() serviceProperty = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f") control.window.setProperty(self.property, serviceProperty) try: dbcon = database.connect(control.libcacheFile) dbcur = dbcon.cursor() dbcur.execute( "CREATE TABLE IF NOT EXISTS service (" "setting TEXT, " "value TEXT, " "UNIQUE(setting)" ");" ) dbcur.execute("DELETE FROM service WHERE setting = 'last_run'") dbcur.execute("INSERT INTO service Values (?, ?)", ("last_run", serviceProperty)) dbcon.commit() dbcon.close() except: try: dbcon.close() except: pass if not control.setting("service_update") == "true": raise Exception() info = control.setting("service_notification") or "true" self.update(None, info=info) except: pass control.sleep(10000)
def play(anime_id, episode_id): # try: # content = cache.get(masterani.get_anime_details(anime_id), 2) l1 = "Fetching video" progressDialog.create(heading="MasterAni", line1="Fetching video") progressDialog.update(0, line1=l1, line3="Loading hosts") hosts = client.request("http://www.masterani.me/api/hosts") hosts = json.loads(hosts) progressDialog.update(25, line1=l1, line3="Loading episodes urls") videos = client.request("http://www.masterani.me/api/episode/%s?videos=1" % episode_id) videos = json.loads(videos)['videos'] progressDialog.update(50, line1=l1, line3="Picking nose") hostlist = [] videos = sorted(videos, key=lambda k: (int(k['quality']), int(k['type'])), reverse=True) autoplay = control.setting("autoplay.enabled") maxq = control.setting("autoplay.maxquality") subdub = control.setting("autoplay.subdub") for video in videos: hostname = [x['name'] for x in hosts if int(x['id']) == int(video['host_id'])][0] subs = 'Sub' if video['type'] is 1 else 'Dub' quality = video['quality'] if 'true' in autoplay: if subdub in subs and int(quality) <= int(maxq): hostlist.append("%s | %s | %s" % (quality, subs, hostname)) else: hostlist.append("%s | %s | %s" % (quality, subs, hostname)) if autoplay in 'false': hostdialog = control.dialog.select("Select host", hostlist) else: if len(hostlist) is 0: progressDialog.close() xbmcgui.Dialog().ok("Masterani", "No hosts found for autoplay.", "Change addon settings and try again.") hostdialog = -1 else: hostdialog = 0 if hostdialog == -1: progressDialog.close() control.execute('Dialog.Close(okdialog)') return host_id = videos[hostdialog]['host_id'] embed_id = videos[hostdialog]['embed_id'] if host_id is '': return prefix = "" suffix = "" for host in hosts: if str(host_id) in str(host['id']): prefix = host['embed_prefix'] suffix = host['embed_suffix'] break try: if suffix is not None: url = prefix + embed_id + suffix else: url = prefix + embed_id except: pass progressDialog.update(75, line1=l1, line3="Loading video") if 'moe' in host['name']: content = base64.b64decode(re.compile("atob\('(.+?)'\)").findall(client.request(url))[0]) mp4 = re.compile("source src=\"(.+?)\"").findall(content)[0] if 'MP4Upload' in host['name']: mp4 = re.compile("\"file\": \"(.+?)\"").findall(client.request(url))[0] if 'Bakavideo' in host['name']: content = re.compile("go\((.+?)\)").findall(client.request(url))[0] content = content.replace("'", "").replace(", ", "/") content = "https://bakavideo.tv/" + content content = client.request(content) content = json.loads(content) content = content['content'] content = base64.b64decode(content) mp4 = client.parseDOM(content, 'source', ret='src')[0] if 'BETA' in host['name']: mp4 = embed_id if 'Vidstream' in host['name']: mp4 = re.compile("source src='(.+?)'").findall(client.request(url))[0] if 'Aniupload' in host['name']: mp4 = re.compile("\(\[\{src: \"(.+?)\"").findall(client.request(url))[0] if 'Drive.g' in host['name']: mp4 = re.compile("url_encoded_fmt_stream_map\",\"(.+?)\"\]").findall(client.request(url))[0] mp4 = mp4.split(",")[0] mp4 = mp4[mp4.find("https"):] mp4 = urllib.unquote(mp4) progressDialog.close() control.sleep(100) MAPlayer().run(anime_id, episode_id, mp4)
def run(self): def download(): return [] result = cache.neptune_download_get(download, 600000000, table='rel_dl') for item in result: self.name = item['name'] ; self.image = item['image'] ; self.url = item['url'] sysname = self.name.translate(None, '\/:*?"<>|').strip('.') url = self.url.split('|')[0] try: headers = dict(urlparse.parse_qsl(self.url.rsplit('|', 1)[1])) except: headers = dict('') ext = os.path.splitext(urlparse.urlparse(url).path)[1][1:].lower() hdlr = re.compile('.+? ([(]\d{4}[)]|S\d*E\d*)$').findall(self.name) if len(hdlr) == 0: self.content = 'Uncategorised' if ext in ['m4a', 'mp3', 'aac']: self.content = 'Music' hdlr = re.compile('.+? (S\d*E\d*)$').findall(self.name) if len(hdlr) > 0: self.content = 'TVShows' hdlr = re.compile('.+? [(](\d{4})[)]$').findall(self.name) if len(hdlr) > 0: self.content = 'Movies' if self.content == 'Movies': dest = os.path.join(downloadPath, self.content) control.makeFile(dest) dest = os.path.join(dest, sysname) control.makeFile(dest) elif self.content == 'TVShows': d = re.compile('(.+?) S(\d*)E(\d*)$').findall(sysname)[0] dest = os.path.join(downloadPath, self.content) control.makeFile(dest) dest = os.path.join(dest, d[0]) control.makeFile(dest) dest = os.path.join(dest, 'Season %01d' % int(d[1])) control.makeFile(dest) else: dest = os.path.join(downloadPath, self.content) control.makeFile(dest) if not ext in ['mp4', 'm4a', 'mp3', 'aac', 'mkv', 'flv', 'avi', 'mpg']: ext = 'mp4' dest = os.path.join(dest, sysname + '.' + ext) control.infoDialog(self.name + ' Is Downloading', 'Downloads Started', self.image, time=7000) try: req = urllib2.Request(url, headers=headers) resp = urllib2.urlopen(req, timeout=30) except Exception,e: removeDownload(self.url) print '%s ERROR - File Failed To Open' % (dest) continue try: self.size = int(resp.headers['Content-Length']) except: self.size = 0 if self.size < 1: removeDownload(self.url) print '%s Unknown filesize - Unable to download' % (dest) continue try: resumable = 'bytes' in resp.headers['Accept-Ranges'].lower() except: resumable = False size = 1024 * 1024 if self.size < size: size = self.size gb = '%.2f GB' % (float(self.size) / 1073741824) start = time.clock() total = 0 ; notify = 0 ; errors = 0 ; count = 0 ; resume = 0 ; sleep = 0 self.clear() control.window.setProperty(property + '.status', 'downloading') control.window.setProperty(property + '.name', str(self.name)) control.window.setProperty(property + '.image', str(self.image)) control.window.setProperty(property + '.size', str(gb)) f = control.openFile(dest, 'wb') chunk = None chunks = [] while True: downloaded = total for c in chunks: downloaded += len(c) percent = min(100 * downloaded / self.size, 100) self.speed = str(int((downloaded / 1024) / (time.clock() - start))) + ' KB/s' self.percent = str(percent) + '%' control.window.setProperty(property + '.percent', str(self.percent)) control.window.setProperty(property + '.speed', str(self.speed)) if percent >= notify: control.infoDialog('Downloaded %s' % self.percent, self.name, self.image, time=5000) notify += 10 chunk = None error = False try: chunk = resp.read(size) if not chunk: if self.percent < 99: error = True else: while len(chunks) > 0: c = chunks.pop(0) f.write(c) del c f.close() print '%s download complete' % (dest) break except Exception, e: print str(e) error = True sleep = 10 errno = 0 if hasattr(e, 'errno'): errno = e.errno if errno == 10035: # 'A non-blocking socket operation could not be completed immediately' pass if errno == 10054: #'An existing connection was forcibly closed by the remote host' errors = 10 #force resume sleep = 30 if errno == 11001: # 'getaddrinfo failed' errors = 10 #force resume sleep = 30 if chunk: errors = 0 chunks.append(chunk) if len(chunks) > 5: c = chunks.pop(0) f.write(c) total += len(c) del c if error: errors += 1 count += 1 print '%d Error(s) whilst downloading %s' % (count, dest) control.sleep(sleep*1000) if (resumable and errors > 0) or errors >= 10: if (not resumable and resume >= 50) or resume >= 500: #Give up! print '%s download canceled - too many error whilst downloading' % (dest) break resume += 1 errors = 0 if resumable: chunks = [] #create new response print 'Download resumed (%d) %s' % (resume, dest) h = headers ; h['Range'] = 'bytes=%d-' % int(total) try: resp = urllib2.urlopen(urllib2.Request(url, headers=h), timeout=10) except: resp = None else: #use existing response pass if control.window.getProperty(property + '.status') == 'stop': control.infoDialog('Process Complete', 'Downloads', time=5000) return self.clear()