def CheckLinksInLibrary(self): import thread_pool import time self.t_link_delay = int(control.setting('library.service.testlink.delay') or 0) if self.t_link_delay == 0: printuj_linka('[CheckLink]: START and STOP - Do not check library sources') return dirs,files = control.listDir(self.library_folder) self.progressDialogBG = control.progressDialogBG self.progressDialogBG.create('Sprawdzam \xc5\xbar\xc3\xb3d\xc5\x82a biblioteki cda.pl','Ilo\xc5\x9b\xc4\x87 pozycji: %d'%len(dirs)) printuj_linka('[CheckLink]: START Library Folders = %d'%len(dirs)) if not control.condVisibility('Window.IsVisible(infodialog)') and not control.condVisibility('Player.HasVideo'): try: control.infoDialog('Sprawdzam \xc5\xbar\xc3\xb3dla biblioteki cda.pl', time=3) self.infoDialog = True except: self.infoDialog = False pool = thread_pool.ThreadPool(self.fredy) self.res={'checked':0,'skipped':0,'removed':0,'updated':0} N = len(dirs) for idx,folder_ in enumerate(dirs): pool.add_task(self.check_remove, *(folder_,idx,N)) time.sleep(0.1) pool.wait_completion() printuj_linka('[CheckLink]: END Status checked:%d, skipped:%d, removed:%d, updated:%d'%(self.res['checked'],self.res['skipped'],self.res['removed'],self.res['updated'])) self.progressDialogBG.close() if self.infoDialog == True: control.infoDialog('Usuni\xc4\x99to :%d, Zaktualizowano :%d '%(self.res['removed'],self.res['updated']), time=30)
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 = ? AND view_type = ?", ( 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, icon=skinIcon) except: return
def clear(table=None, withyes=True): try: control.idle() if table is None: table = ['rel_list', 'rel_lib'] elif not type(table) == list: table = [table] if withyes: yes = control.yesnoDialog(control.lang(30401).encode('utf-8'), '', '') if not yes: return else: pass 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('DONE!!!') except: pass
def addView(content): try: skin = control.skin skinPath = control.skinPath xml = os.path.join(skinPath,'addon.xml') file = control.openFile(xml) read = file.read().replace('\n','') file.close() try: src = re.compile('defaultresolution="(.+?)"').findall(read)[0] except: src = re.compile('<res.+?folder="(.+?)"').findall(read)[0] src = os.path.join(skinPath, src) src = os.path.join(src, 'MyVideoNav.xml') file = control.openFile(src) read = file.read().replace('\n','') file.close() views = re.compile('<views>(.+?)</views>').findall(read)[0] views = [int(x) for x in views.split(',')] for view in views: label = control.infoLabel('Control.GetLabel(%s)' % (view)) if not (label == '' or label == None): break record = (skin, content, str(view)) control.makeFile(control.dataPath) dbcon = database.connect(control.databaseFile) dbcur = dbcon.cursor() dbcur.execute("CREATE TABLE IF NOT EXISTS views (""skin TEXT, ""view_type TEXT, ""view_id TEXT, ""UNIQUE(skin, view_type)"");") dbcur.execute("DELETE FROM views WHERE skin = '%s' AND view_type = '%s'" % (record[0], record[1])) dbcur.execute("INSERT INTO views Values (?, ?, ?)", record) dbcon.commit() viewName = control.infoLabel('Container.Viewmode') control.infoDialog('This View is now Default', heading=viewName) except: return
def force_update(): add_fusion_source() update = build_conectors_data_system() update = build_conectors_data_remote() xbmc.executebuiltin('UpdateAddonRepos') xbmc.executebuiltin('UpdateLocalAddons') control.infoDialog('Repositorios actualizados!!!')
def __get_token(self): pin = self.pin_edit_control.getText().strip() print("PIN", pin) if pin: try: trakt_api = TraktAPI2(use_https=False, timeout=300) result = trakt_api.get_token(pin=pin) print("---", result) control.set_setting('trakt_oauth_token', result['access_token']) control.set_setting('trakt_refresh_token', result['refresh_token']) TOKEN = result['access_token'] trakt_api = TraktAPI2(TOKEN, use_https=False, timeout=300) profile = trakt_api.get_user_profile(cached=False) print("Profile", profile) print("Profile", profile['username']) control.set_setting('trakt_user', profile['username']) control.infoDialog('Trakt Authorization Success !', 'Trakt Success') return True except Exception as e: print('Trakt Authorization Failed: %s') % (e) control.infoDialog('Trakt Authorization Failed: ' + str(e), 'Trakt ERROR') return False return False
def clear(table=None, withyes=True): try: control.idle() if table == None: table = ['rel_list', 'rel_lib'] elif not type(table) == list: table = [table] if withyes: yes = control.yesnoDialog(control.lang(30401).encode('utf-8'), '', '') if not yes: return else: pass dbcon = database.connect(control.cacheFile) dbcur = dbcon.cursor() for t in table: try: dbcur.execute("DROP TABLE IF EXISTS %s" % t) dbcur.execute("VACUUM") dbcon.commit() except: pass control.infoDialog(control.lang(30402).encode('utf-8')) except: pass
def add2(self, i): if not control.condVisibility('Window.IsVisible(infodialog)') and not control.condVisibility('Player.HasVideo'): try: control.infoDialog('Dodawanie Folderu do Biblioteki ...', time=3) self.infoDialog = True except: self.infoDialog = False files_added = 0 progressDialogBG = control.progressDialogBG progressDialogBG.create('cda.pl','Dodawanie Folderu do Biblioteki') for index, found in enumerate(i): czas_progres = int((index+1)*100.0/(len(i))) fwebId = found.get('_filmweb',False) title = found.get('title','') title = re.sub('\\(\\d{4}\\)','',title).strip() year = found.get('year','') url = found.get('url','') if not ( fwebId and url): continue if self.check_setting == 'true': if lib_tools.get_urlStat(url) != 'OK': progressDialogBG.update(czas_progres,message='martwy link [%s] '%(title)) printuj_linka('[CheckLink]: BAD Source: %s'%title) continue else: printuj_linka('[CheckLink]: OK Source: %s'%title) if self.strmFile(fwebId,title,year,url): files_added += 1 progressDialogBG.update(czas_progres,message='Dodano [%s] '%(title)) progressDialogBG.close() if self.infoDialog == True: control.infoDialog('Dodano %d film\xc3\xb3w'%files_added, time=2) if self.library_setting == 'true' and not control.condVisibility('Library.IsScanningVideo') and files_added > 0: control.execute('UpdateLibrary(video)')
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 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 infoCheck(self, version): try: control.infoDialog('', control.lang(32074).encode('utf-8'), time=5000, sound=False) return '1' except: return '1'
def setPassword(self): keyboard = xbmc.Keyboard('', 'Unesite novu lozinku:', True) keyboard.doModal() if keyboard.isConfirmed(): password = keyboard.getText() self.cur.execute("UPDATE Settings SET Value=? WHERE Name=?",(password,'Parental',)) self.db.commit() control.infoDialog('Lozinka je spremljena.', heading='Roditeljska zastita') return password
def add_subreddit(): reddit = control.get_keyboard('Enter subreddit') if not reddit: control.infoDialog('A problem occured. Try again!',heading='Castaway Lists') return reddit = reddit.replace('https://','').replace('http://','').replace('www.','').replace('reddit.com','').replace('r/','').replace('/','') items = get_subreddits() items.append(reddit) write_subreddits(items)
def clearCacheAll(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_all() control.infoDialog(control.lang(32057).encode('utf-8'), sound=True, icon='INFO')
def login(r): user = control.setting('reddit_user') passw = control.setting('reddit_pass') login = user!='' and passw!='' if login: try: r.login(user, passw) except: control.infoDialog('Please check your Reddit username and password.') return r
def login(r): user = control.setting('reddit_user') passw = control.setting('reddit_pass') login = user != '' and passw != '' if login: try: r.login(user, passw) except: control.infoDialog( 'Please check your Reddit username and password.') return r
def add_subreddit(): reddit = control.get_keyboard('Enter subreddit') if not reddit: control.infoDialog('A problem occured. Try again!', heading='Castaway Lists') return reddit = reddit.replace('https://', '').replace('http://', '').replace( 'www.', '').replace('reddit.com', '').replace('r/', '').replace('/', '') items = get_subreddits() items.append(reddit) write_subreddits(items)
def removeDownload(url): try: def download(): return [] result = cache.get(download, 600000000, table='rel_dl') if result == '': result = [] result = [i for i in result if not i['url'] == url] if result == []: result = '' def download(): return result result = cache.get(download, 0, table='rel_dl') control.refresh() except: control.infoDialog('You need to remove file manually', 'Can not remove from Queue')
def onPlayBackStarted(self): if control.setting('playback_info') == 'true': elapsedTime = '%s %s seconds' % (control.lang(30309).encode('utf-8'), int((time.time() - self.loadingTime))) control.infoDialog(elapsedTime, heading=self.name) try: if self.offset == '0': raise Exception() self.seekTime(float(self.offset)) except: pass try: if not control.setting('subtitles') == 'true': raise Exception() try: subtitle = subtitles.get(self.name, self.imdb, self.season, self.episode) except: subtitle = subtitles.get(self.name, self.imdb, '', '') except: pass
def promptPassword(self): if self.isPasswordSet(): password = self.cur.execute("SELECT Value FROM Settings WHERE Name=?",('Parental',)).fetchall()[0][0] else: control.infoDialog('Prvo postavite lozinku.', heading='Roditeljska zastita') return False keyboard = xbmc.Keyboard('', 'Enter your password:'******'Netocna lozinka', heading='Roditeljska zastita') return False
def delete(dbfile=control.cacheFile, withyes=True): if withyes: yes = control.yesnoDialog("Do you want to Clear Cache?".encode('utf-8'), '', '') if not yes: return else: pass control.deleteFile(dbfile) control.infoDialog('DONE!!!')
def _install_addon(url): ri = AddonInstaller() compressed = ri.download(url) if compressed: addonId = ri.install(compressed) if addonId: xbmc.sleep(100) xbmc.executebuiltin('UpdateLocalAddons') xbmc.sleep(100) try: _N_ = xbmcaddon.Addon(id=addonId) control.infoDialog('Addon installed') return True except: pass return False
def startDownload(): if downloadPath == '': return control.infoDialog( 'You need to set your download folder in addon settings first', 'File Not Downloadable') control.execute('RunPlugin(%s?action=startDownloadThread)' % sys.argv[0])
def delete(dbfile=control.cacheFile, withyes=True): if withyes: yes = control.yesnoDialog(control.lang(30401).encode('utf-8'), '', '') if not yes: return else: pass control.deleteFile(dbfile) control.infoDialog(control.lang(30402).encode('utf-8'))
def addView(content): try: skin = control.skin skinPath = control.skinPath xml = os.path.join(skinPath, 'addon.xml') file = control.openFile(xml) read = file.read().replace('\n', '') file.close() try: src = re.compile('defaultresolution="(.+?)"').findall(read)[0] except: src = re.compile('<res.+?folder="(.+?)"').findall(read)[0] src = os.path.join(skinPath, src) src = os.path.join(src, 'MyVideoNav.xml') file = control.openFile(src) read = file.read().replace('\n', '') file.close() views = re.compile('<views>(.+?)</views>').findall(read)[0] views = [int(x) for x in views.split(',')] for view in views: label = control.infoLabel('Control.GetLabel(%s)' % (view)) if not (label == '' or label == None): break record = (skin, content, str(view)) control.makeFile(control.dataPath) dbcon = database.connect(control.databaseFile) dbcur = dbcon.cursor() dbcur.execute("CREATE TABLE IF NOT EXISTS views (" "skin TEXT, " "view_type TEXT, " "view_id TEXT, " "UNIQUE(skin, view_type)" ");") dbcur.execute( "DELETE FROM views WHERE skin = '%s' AND view_type = '%s'" % (record[0], record[1])) dbcur.execute("INSERT INTO views Values (?, ?, ?)", record) dbcon.commit() viewName = control.infoLabel('Container.Viewmode') control.infoDialog('This View is now Default', heading=viewName) except: return
def onPlayBackStarted(self): for i in range(0, 200): if control.condVisibility('Window.IsActive(busydialog)') == 1: control.idle() else: break control.sleep(100) if control.setting('playback_info') == 'true': elapsedTime = '%s %s %s' % (control.lang(30464).encode('utf-8'), int((time.time() - self.loadingTime)), control.lang(30465).encode('utf-8')) control.infoDialog(elapsedTime, heading=self.title) try: if self.offset == '0': raise Exception() self.seekTime(float(self.offset)) except Exception, e: print str(e) pass
def manager(name, imdb, tvdb, content): try: post = {"movies": [{"ids": {"imdb": imdb}}]} if content == 'movie' else {"shows": [{"ids": {"tvdb": tvdb}}]} items = [(control.lang(32516).encode('utf-8'), '/sync/collection')] items += [(control.lang(32517).encode('utf-8'), '/sync/collection/remove')] items += [(control.lang(32518).encode('utf-8'), '/sync/watchlist')] items += [(control.lang(32519).encode('utf-8'), '/sync/watchlist/remove')] items += [(control.lang(32520).encode('utf-8'), '/users/me/lists/%s/items')] result = getTraktAsJson('/users/me/lists') lists = [(i['name'], i['ids']['slug']) for i in result] lists = [lists[i//2] for i in range(len(lists)*2)] for i in range(0, len(lists), 2): lists[i] = ((control.lang(32521) % lists[i][0]).encode('utf-8'), '/users/me/lists/%s/items' % lists[i][1]) for i in range(1, len(lists), 2): lists[i] = ((control.lang(32522) % lists[i][0]).encode('utf-8'), '/users/me/lists/%s/items/remove' % lists[i][1]) items += lists select = control.selectDialog([i[0] for i in items], control.lang(32515).encode('utf-8')) if select == -1: return elif select == 4: t = control.lang(32520).encode('utf-8') k = control.keyboard('', t) ; k.doModal() new = k.getText() if k.isConfirmed() else None if (new == None or new == ''): return result = __getTrakt('/users/me/lists', post={"name": new, "privacy": "private"})[0] try: slug = utils.json_loads_as_str(result)['ids']['slug'] except: return control.infoDialog(control.lang(32515).encode('utf-8'), heading=str(name), sound=True, icon='ERROR') result = __getTrakt(items[select][1] % slug, post=post)[0] else: result = __getTrakt(items[select][1], post=post)[0] icon = control.infoLabel('ListItem.Icon') if not result == None else 'ERROR' control.infoDialog(control.lang(32515).encode('utf-8'), heading=str(name), sound=True, icon=icon) except: return
def add(self, found): fwebId = found.get('_filmweb',False) title = found.get('title','') title = re.sub('\\(\\d{4}\\)','',title).strip() year = found.get('year','') url = found.get('url','') if not ( fwebId and url): return False if self.check_setting == 'true': if lib_tools.get_urlStat(url) != 'OK': return False if not control.condVisibility('Window.IsVisible(infodialog)') and not control.condVisibility('Player.HasVideo'): control.infoDialog('Dodawanie do Biblioteki ...', time=3) self.infoDialog = True files_added = 0 if self.strmFile(fwebId,title,year,url): files_added += 1 if self.infoDialog == True: control.infoDialog('Zako\xc5\x84czono', time=2) if self.library_setting == 'true' and not control.condVisibility('Library.IsScanningVideo') and files_added > 0: control.execute('UpdateLibrary(video)')
def clear(table=None, notify=False): 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("Process complete") except: pass
def clear(table=None,notify=False): 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("Process complete") except: pass
def clear(table=None): try: 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 control.makeFile(control.dataPath) 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('Process Complete') except: pass
def GetNewMovies(self): from cdapl import searchCDA import thread_pool import time self.check_setting = 'false' url = 'https://www.cda.pl/video/show/cale_filmy_or_caly_film_or_lektor_or_pl_or_dubbing_or_napisy_or_fps_or_odc/p%d?duration=dlugie§ion=&quality=720p§ion=&s=date§ion=' if not control.condVisibility('Window.IsVisible(infodialog)') and not control.condVisibility('Player.HasVideo'): try: control.infoDialog('Szukam nowych film\xc3\xb3w ...', time=3) self.infoDialog = True except: self.infoDialog = False self.progressDialogBG = control.progressDialogBG self.progressDialogBG.create('cda.pl','Szukam nowych film\xc3\xb3w ...') items=[] control.setSetting('library.service.last.run', datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')) for stronkaX in range(int(control.setting('library.service.pages') or 1)): stronkaX +=1 printuj_linka('[AddMovie]: Searching cda.pl, page [%d]'%stronkaX) nowy_link,next=searchCDA(url%(stronkaX),False,False) items.extend(nowy_link) self.progressDialogBG.update(0,message='Znalaz\xc5\x82em pozycji [%d] '%(len(items))) self.progressDialogBG.update(0,message='Indentyfikuje %d film\xc3\xb3w w %d w\xc4\x85tkach ...'%(len(items),self.fredy)) items = [x for x in items if x.get('code','')!= ''] printuj_linka('[AddMovie]: Found Total %d videos ... '%(len(items))) pool = thread_pool.ThreadPool(self.fredy) self.out=[] N=len(items) for idx,one in enumerate(items): pool.add_task(self.dod_Movies, *(one,idx,N)) time.sleep(0.1) pool.wait_completion() printuj_linka('[AddMovie]: (After Threading) Found Total %d Movies ... '%(len(self.out))) self.out.reverse() self.progressDialogBG.close() self.add2( self.out ) control.setSetting('library.service.last.run', datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
def __get_token(self): pin = self.pin_edit_control.getText().strip() print("PIN",pin) if pin: try: trakt_api = TraktAPI2(use_https=False, timeout=300) result = trakt_api.get_token(pin=pin) print("---",result) control.set_setting('trakt_oauth_token', result['access_token']) control.set_setting('trakt_refresh_token', result['refresh_token']) TOKEN = result['access_token'] trakt_api = TraktAPI2(TOKEN, use_https=False, timeout=300) profile = trakt_api.get_user_profile(cached=False) print("Profile",profile) print("Profile",profile['username']) control.set_setting('trakt_user', profile['username']) control.infoDialog('Trakt Authorization Success !', 'Trakt Success') return True except Exception as e: print('Trakt Authorization Failed: %s') % (e) control.infoDialog('Trakt Authorization Failed: '+str(e), 'Trakt ERROR') return False return False
def download(name, image, url, dest=addon.getSetting('download_path')): try: xbmc.executebuiltin("ActivateWindow(busydialog)") import control if url == None: return control.infoDialog(control.lang(30501).encode('utf-8')) headers = ("Authorization", "Bearer " + str(xbmcaddon.Addon().getSetting('rd_access'))) url = url.split('|')[0] content = re.compile('(.+?)\sS(\d*)E\d*$').findall(name) transname = name.translate('\/:*?"<>|').strip('.') levels = ['../../../..', '../../..', '../..', '..'] 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, os.path.splitext(transname)[0]) control.makeFile(dest) dest = os.path.join(dest, transname) 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) except: xbmc.executebuiltin("Dialog.Close(busydialog)") util.notify(ADDON_ID, "Error Downloading")
def onClick(self, control2): print 'onClick: %s' % (control2) if control2 == AUTH_BUTTON: if not self.__get_token(): control.infoDialog('Trakt PIN Authorization Failed.', 'Trakt ERROR') return self.auth = True self.close() if control2 == LATER_BUTTON: control.infoDialog(control.lang(32157) + control.lang(32150)) control.set_setting('last_reminder', str(int(time.time()))) if control == NEVER_BUTTON: control.infoDialog(control.lang(32157) + control.lang(32151)) control.set_setting('last_reminder', '-1') if control in [AUTH_BUTTON, LATER_BUTTON, NEVER_BUTTON]: self.close()
def startDownload(): if downloadPath == '': return control.infoDialog('You need to set your download folder in addon settings first', 'File Not Downloadable') control.execute('RunPlugin(%s?action=startDownloadThread)' % sys.argv[0])
else: #use existing response pass if control.window.getProperty(property + '.status') == 'stop': control.infoDialog('Process Complete', 'Downloads', time=5000) return self.clear() self.clear() control.infoDialog(self.name + ' Completed', 'Download Complete', self.image, time=5000) removeDownload(self.url) control.infoDialog('Process Complete', 'Downloads', time=5000) return def kill(self): control.window.setProperty(property + '.status', 'stop') def clear(self): control.window.clearProperty(property + '.status') control.window.clearProperty(property + '.name') control.window.clearProperty(property + '.image') control.window.clearProperty(property + '.percent') control.window.clearProperty(property + '.speed') control.window.clearProperty(property + '.size') control.refresh()
def run(self): def download(): return [] result = cache.get(download, 600000000, table='rel_dl') for item in result: self.name = item['name'] ; self.image = item['image'] ; self.url = item['url'] sysname = self.name.translate(None, '\/:*?"<>|').strip('.') url = self.url.split('|')[0] try: headers = dict(urlparse.parse_qsl(self.url.rsplit('|', 1)[1])) except: headers = dict('') ext = os.path.splitext(urlparse.urlparse(url).path)[1][1:].lower() if not ext in ['mp4', 'mkv', 'flv', 'avi', 'mpg']: ext = 'mp4' hdlr = re.compile('.+? ([(]\d{4}[)]|S\d*E\d*)$').findall(self.name) if len(hdlr) == 0: self.content = 'Uncategorised' hdlr = re.compile('.+? (S\d*E\d*)$').findall(self.name) if len(hdlr) > 0: self.content = 'TVShows' hdlr = re.compile('.+? [(](\d{4})[)]$').findall(self.name) if len(hdlr) > 0: self.content = 'Movies' if self.content == 'Movies': dest = os.path.join(downloadPath, 'Movies') control.makeFile(dest) dest = os.path.join(dest, sysname) control.makeFile(dest) elif self.content == 'TVShows': d = re.compile('(.+?) S(\d*)E(\d*)$').findall(sysname)[0] dest = os.path.join(downloadPath, 'TVShows') control.makeFile(dest) dest = os.path.join(dest, d[0]) control.makeFile(dest) dest = os.path.join(dest, 'Season %01d' % int(d[1])) control.makeFile(dest) else: dest = os.path.join(downloadPath, 'Uncategorised') control.makeFile(dest) dest = os.path.join(dest, sysname + '.' + ext) control.infoDialog(self.name + ' Is Downloading', 'Downloads Started', self.image, time=7000) try: req = urllib2.Request(url, headers=headers) resp = urllib2.urlopen(req, timeout=30) except Exception,e: removeDownload(self.url) print '%s ERROR - File Failed To Open' % (dest) continue try: self.size = int(resp.headers['Content-Length']) except: self.size = 0 if self.size < 1: removeDownload(self.url) print '%s Unknown filesize - Unable to download' % (dest) continue try: resumable = 'bytes' in resp.headers['Accept-Ranges'].lower() except: resumable = False size = 1024 * 1024 if self.size < size: size = self.size gb = '%.2f GB' % (float(self.size) / 1073741824) start = time.clock() total = 0 ; notify = 0 ; errors = 0 ; count = 0 ; resume = 0 ; sleep = 0 self.clear() control.window.setProperty(property + '.status', 'downloading') control.window.setProperty(property + '.name', str(self.name)) control.window.setProperty(property + '.image', str(self.image)) control.window.setProperty(property + '.size', str(gb)) f = control.openFile(dest, 'wb') chunk = None chunks = [] while True: downloaded = total for c in chunks: downloaded += len(c) percent = min(100 * downloaded / self.size, 100) self.speed = str(int((downloaded / 1024) / (time.clock() - start))) + ' KB/s' self.percent = str(percent) + '%' control.window.setProperty(property + '.percent', str(self.percent)) control.window.setProperty(property + '.speed', str(self.speed)) if percent >= notify: control.infoDialog('Downloaded %s' % self.percent, self.name, self.image, time=5000) notify += 10 chunk = None error = False try: chunk = resp.read(size) if not chunk: if self.percent < 99: error = True else: while len(chunks) > 0: c = chunks.pop(0) f.write(c) del c f.close() print '%s download complete' % (dest) break except Exception, e: print str(e) error = True sleep = 10 errno = 0 if hasattr(e, 'errno'): errno = e.errno if errno == 10035: # 'A non-blocking socket operation could not be completed immediately' pass if errno == 10054: #'An existing connection was forcibly closed by the remote host' errors = 10 #force resume sleep = 30 if errno == 11001: # 'getaddrinfo failed' errors = 10 #force resume sleep = 30 if chunk: errors = 0 chunks.append(chunk) if len(chunks) > 5: c = chunks.pop(0) f.write(c) total += len(c) del c if error: errors += 1 count += 1 print '%d Error(s) whilst downloading %s' % (count, dest) control.sleep(sleep*1000) if (resumable and errors > 0) or errors >= 10: if (not resumable and resume >= 50) or resume >= 500: #Give up! print '%s download canceled - too many error whilst downloading' % (dest) break resume += 1 errors = 0 if resumable: chunks = [] #create new response print 'Download resumed (%d) %s' % (resume, dest) h = headers ; h['Range'] = 'bytes=%d-' % int(total) try: resp = urllib2.urlopen(urllib2.Request(url, headers=h), timeout=10) except: resp = None else: #use existing response pass if control.window.getProperty(property + '.status') == 'stop': control.infoDialog('Process Complete', 'Downloads', time=5000) return self.clear()
def addDownload(name, url, image, provider=None): try: def download(): return [] result = cache.get(download, 600000000, table='rel_dl') result = [i['name'] for i in result] except: pass if name in result: return control.infoDialog('Item Already In Your Queue', name) try: if not provider == None: from modules.sources import sources url = sources().sourcesResolve(url, provider) if url == None: raise Exception() #legacy issue, will be removed later if 'afdah.org' in url and not '</source>' in url: url += '<source>afdah</source>' if '</source>' in url: source = re.compile('<source>(.+?)</source>').findall(url)[0] url = re.compile('(.+?)<source>').findall(url)[0] for i in ['_mv', '_tv', '_mv_tv']: try: call = __import__('modules.sources.%s%s' % (source, i), globals(), locals(), ['object'], -1).source() except: pass from modules import sources ; d = sources.sources() url = call.get_sources(url, d.hosthdfullDict, d.hostsdfullDict, d.hostlocDict) if type(url) == list: url = sorted(url, key=lambda k: k['quality']) url = url[0]['url'] url = call.resolve(url) from modules import resolvers url = resolvers.request(url) if type(url) == list: url = sorted(url, key=lambda k: k['quality']) url = url[0]['url'] if url == None: raise Exception() except: return control.infoDialog('Unplayable stream') pass try: u = url.split('|')[0] try: headers = dict(urlparse.parse_qsl(url.rsplit('|', 1)[1])) except: headers = dict('') ext = os.path.splitext(urlparse.urlparse(u).path)[1][1:].lower() if ext == 'm3u8': raise Exception() #if not ext in ['mp4', 'mkv', 'flv', 'avi', 'mpg']: ext = 'mp4' dest = name + '.' + ext req = urllib2.Request(u, headers=headers) resp = urllib2.urlopen(req, timeout=30) size = int(resp.headers['Content-Length']) size = ' %.2f GB' % (float(size) / 1073741824) no = control.yesnoDialog(dest, 'Complete file is' + size, 'Continue with download?', name + ' - ' + 'Confirm Download', 'Confirm', 'Cancel') if no: return except: return control.infoDialog('Unable to download') pass def download(): return [{'name': name, 'url': url, 'image': image}] result = cache.get(download, 600000000, table='rel_dl') result = [i for i in result if not i['url'] == url] def download(): return result + [{'name': name, 'url': url, 'image': image}] result = cache.get(download, 0, table='rel_dl') control.infoDialog('Item Added to Queue', name)
def run(self): def download(): return [] result = cache.get(download, 600000000, table='rel_dl') for item in result: self.name = item['name'] self.image = item['image'] self.url = item['url'] sysname = self.name.translate(None, '\/:*?"<>|').strip('.') url = self.url.split('|')[0] try: headers = dict(urlparse.parse_qsl(self.url.rsplit('|', 1)[1])) except: headers = dict('') ext = os.path.splitext(urlparse.urlparse(url).path)[1][1:].lower() if not ext in ['mp4', 'mkv', 'flv', 'avi', 'mpg']: ext = 'mp4' hdlr = re.compile('.+? ([(]\d{4}[)]|S\d*E\d*)$').findall(self.name) if len(hdlr) == 0: self.content = 'Uncategorised' hdlr = re.compile('.+? (S\d*E\d*)$').findall(self.name) if len(hdlr) > 0: self.content = 'TVShows' hdlr = re.compile('.+? [(](\d{4})[)]$').findall(self.name) if len(hdlr) > 0: self.content = 'Movies' if self.content == 'Movies': dest = os.path.join(downloadPath, 'Movies') control.makeFile(dest) dest = os.path.join(dest, sysname) control.makeFile(dest) elif self.content == 'TVShows': d = re.compile('(.+?) S(\d*)E(\d*)$').findall(sysname)[0] dest = os.path.join(downloadPath, 'TVShows') control.makeFile(dest) dest = os.path.join(dest, d[0]) control.makeFile(dest) dest = os.path.join(dest, 'Season %01d' % int(d[1])) control.makeFile(dest) else: dest = os.path.join(downloadPath, 'Uncategorised') control.makeFile(dest) dest = os.path.join(dest, sysname + '.' + ext) control.infoDialog(self.name + ' Is Downloading', 'Downloads Started', self.image, time=7000) try: req = urllib2.Request(url, headers=headers) resp = urllib2.urlopen(req, timeout=30) except Exception, e: removeDownload(self.url) print '%s ERROR - File Failed To Open' % (dest) continue try: self.size = int(resp.headers['Content-Length']) except: self.size = 0 if self.size < 1: removeDownload(self.url) print '%s Unknown filesize - Unable to download' % (dest) continue try: resumable = 'bytes' in resp.headers['Accept-Ranges'].lower() except: resumable = False size = 1024 * 1024 if self.size < size: size = self.size gb = '%.2f GB' % (float(self.size) / 1073741824) start = time.clock() total = 0 notify = 0 errors = 0 count = 0 resume = 0 sleep = 0 self.clear() control.window.setProperty(property + '.status', 'downloading') control.window.setProperty(property + '.name', str(self.name)) control.window.setProperty(property + '.image', str(self.image)) control.window.setProperty(property + '.size', str(gb)) f = control.openFile(dest, 'wb') chunk = None chunks = [] while True: downloaded = total for c in chunks: downloaded += len(c) percent = min(100 * downloaded / self.size, 100) self.speed = str( int((downloaded / 1024) / (time.clock() - start))) + ' KB/s' self.percent = str(percent) + '%' control.window.setProperty(property + '.percent', str(self.percent)) control.window.setProperty(property + '.speed', str(self.speed)) if percent >= notify: control.infoDialog('Downloaded %s' % self.percent, self.name, self.image, time=5000) notify += 10 chunk = None error = False try: chunk = resp.read(size) if not chunk: if self.percent < 99: error = True else: while len(chunks) > 0: c = chunks.pop(0) f.write(c) del c f.close() print '%s download complete' % (dest) break except Exception, e: print str(e) error = True sleep = 10 errno = 0 if hasattr(e, 'errno'): errno = e.errno if errno == 10035: # 'A non-blocking socket operation could not be completed immediately' pass if errno == 10054: #'An existing connection was forcibly closed by the remote host' errors = 10 #force resume sleep = 30 if errno == 11001: # 'getaddrinfo failed' errors = 10 #force resume sleep = 30 if chunk: errors = 0 chunks.append(chunk) if len(chunks) > 5: c = chunks.pop(0) f.write(c) total += len(c) del c if error: errors += 1 count += 1 print '%d Error(s) whilst downloading %s' % (count, dest) control.sleep(sleep * 1000) if (resumable and errors > 0) or errors >= 10: if (not resumable and resume >= 50) or resume >= 500: #Give up! print '%s download canceled - too many error whilst downloading' % ( dest) break resume += 1 errors = 0 if resumable: chunks = [] #create new response print 'Download resumed (%d) %s' % (resume, dest) h = headers h['Range'] = 'bytes=%d-' % int(total) try: resp = urllib2.urlopen(urllib2.Request(url, headers=h), timeout=10) except: resp = None else: #use existing response pass if control.window.getProperty(property + '.status') == 'stop': control.infoDialog('Process Complete', 'Downloads', time=5000) return self.clear()
def get_pin(): AUTH_BUTTON = 200 LATER_BUTTON = 201 NEVER_BUTTON = 202 ACTION_PREVIOUS_MENU = 10 ACTION_BACK = 92 INSTRUCTION_LABEL = 203 CENTER_Y = 6 CENTER_X = 2 logger = logging.getLogger(__name__) class PinAuthDialog(xbmcgui.WindowXMLDialog): auth = False def onInit(self): self.pin_edit_control = self.__add_editcontrol(30, 240, 40, 450) self.setFocus(self.pin_edit_control) auth = self.getControl(AUTH_BUTTON) never = self.getControl(NEVER_BUTTON) #instuction = self.getControl(INSTRUCTION_LABEL) #instuction.setLabel( "1) " + control.lang(32159).encode('utf-8').format("[COLOR red]http://trakt.tv/pin/999[/COLOR]") + "\n2) " + control.lang(32160).encode('utf-8') + "\n3) " + control.lang(32161).encode('utf-8') + "\n\n" + control.lang(32162).encode('utf-8')) self.pin_edit_control.controlUp(never) self.pin_edit_control.controlLeft(never) self.pin_edit_control.controlDown(auth) self.pin_edit_control.controlRight(auth) auth.controlUp(self.pin_edit_control) auth.controlLeft(self.pin_edit_control) never.controlDown(self.pin_edit_control) never.controlRight(self.pin_edit_control) def onAction(self, action): if action == ACTION_PREVIOUS_MENU or action == ACTION_BACK: self.close() def onControl(self, control2): pass def onFocus(self, control2): pass def onClick(self, control2): print 'onClick: %s' % (control2) if control2 == AUTH_BUTTON: if not self.__get_token(): control.infoDialog('Trakt PIN Authorization Failed.', 'Trakt ERROR') return self.auth = True self.close() if control2 == LATER_BUTTON: control.infoDialog(control.lang(32157) + control.lang(32150)) control.set_setting('last_reminder', str(int(time.time()))) if control == NEVER_BUTTON: control.infoDialog(control.lang(32157) + control.lang(32151)) control.set_setting('last_reminder', '-1') if control in [AUTH_BUTTON, LATER_BUTTON, NEVER_BUTTON]: self.close() def __get_token(self): pin = self.pin_edit_control.getText().strip() print("PIN",pin) if pin: try: trakt_api = TraktAPI2(use_https=False, timeout=300) result = trakt_api.get_token(pin=pin) print("---",result) control.set_setting('trakt_oauth_token', result['access_token']) control.set_setting('trakt_refresh_token', result['refresh_token']) TOKEN = result['access_token'] trakt_api = TraktAPI2(TOKEN, use_https=False, timeout=300) profile = trakt_api.get_user_profile(cached=False) print("Profile",profile) print("Profile",profile['username']) control.set_setting('trakt_user', profile['username']) control.infoDialog('Trakt Authorization Success !', 'Trakt Success') return True except Exception as e: print('Trakt Authorization Failed: %s') % (e) control.infoDialog('Trakt Authorization Failed: '+str(e), 'Trakt ERROR') return False return False # have to add edit controls programatically because getControl() (hard) crashes XBMC on them def __add_editcontrol(self, x, y, height, width): media_path = os.path.join(control.addonPath, 'resources', 'skins', 'Default', 'media') temp = xbmcgui.ControlEdit(0, 0, 0, 0, '', font='font12', textColor='0xFFFFFFFF', focusTexture=os.path.join(media_path, 'button-focus2.png'), noFocusTexture=os.path.join(media_path, 'button-nofocus.png'), _alignment=CENTER_Y | CENTER_X) temp.setPosition(x, y) temp.setHeight(height) temp.setWidth(width) self.addControl(temp) return temp #dialog = PinAuthDialog(os.path.join(control.addonPath, 'resources', 'media', 'trakt', 'script-trakt-PinAuthDialog.xml'), control.addonPath) dialog = PinAuthDialog('TraktPinAuthDialog.xml',os.path.join(control.addonPath)) dialog.doModal() if dialog.auth: control.infoDialog(control.lang(32157), control.lang(32152), 3000) del dialog
def download(name, image, url, image2): 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) p=re.compile("(\[[A-Za-z0-9-_\ \.]+\])") transname = p.match(name.encode("utf-8")).group(1).replace("[", "").replace("]", "") levels =['../../../..', '../../..', '../..', '..'] dest = addon.getSetting('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) """ if "/" in dest: fo = codecs.open(dest+"/"+transname+".nfo", "a", "utf-8") else: fo = codecs.open(dest+"\"+transname+".nfo", "a", "utf-8") fo.write(u'<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>\n<movie>\n<title>'+name+'</title>\n<genre>JAV</genre>\n</movie>'); # Close opend file fo.close()""" f =xbmcvfs.File (dest+"/"+transname+".nfo", 'w') f.write('<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>\n<movie>\n<title>'+name.encode('utf-8')+'</title>\n<genre>JAV</genre>\n</movie>'.encode('utf-8')) f.close() #f = open(dest+"/fanart.jpg",'wb') f =xbmcvfs.File (dest+"/fanart.jpg", 'w') f.write(getIMAGE(image2).read()) f.close() f =xbmcvfs.File (dest+"/poster.jpg", 'w') #f = open(dest+"/poster.jpg",'wb') f.write(getIMAGE(image).read()) f.close() 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.decode('utf-8') + '.' + ext) sysheaders = urllib.quote_plus(json.dumps(headers)) sysurl = urllib.quote_plus(url) systitle = urllib.quote_plus(name.encode('utf-8')) 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 __call_trakt(self, url, method=None, data=None, params=None, auth=True, cache_limit=0.25, cached=True): res_headers = {} # if not cached: cache_limit = 0 # db_cache_limit = cache_limit if cache_limit > 8 else 8 json_data = json.dumps(data) if data else None headers = {"Content-Type": "application/json", "trakt-api-key": V2_API_KEY, "trakt-api-version": 2} url = "%s%s%s" % (self.protocol, BASE_URL, url) if params: url = url + "?" + urllib.urlencode(params) # db_connection = DB_Connection() # created, cached_headers, cached_result = db_connection.get_cached_url(url, json_data, db_cache_limit) # if cached_result and (time.time() - created) < (60 * 60 * cache_limit): # result = cached_result # res_headers = dict(cached_headers) # log_utils.log('Got cached result for: %s' % (url), log_utils.LOGDEBUG) auth_retry = False while True: try: if auth: headers.update({"Authorization": "Bearer %s" % (self.token)}) print("Trakt Call: %s, header: %s, data: %s cache_limit: %s cached: %s") % ( url, headers, data, cache_limit, cached, ) request = urllib2.Request(url, data=json_data, headers=headers) if method is not None: request.get_method = lambda: method.upper() response = urllib2.urlopen(request, timeout=self.timeout) result = "" while True: data = response.read() if not data: break result += data res_headers = dict(response.info().items()) # db_connection.cache_url(url, result, json_data, response.info().items()) break except (ssl.SSLError, socket.timeout) as e: control.infoDialog("Temporary Trakt Error: " + str(e), "Trakt ERROR") raise TransientTraktError("Temporary Trakt Error: " + str(e)) except urllib2.URLError as e: if isinstance(e, urllib2.HTTPError): if e.code in TEMP_ERRORS: control.infoDialog("Temporary Trakt Error: " + str(e), "Trakt ERROR") raise TransientTraktError("Temporary Trakt Error: " + str(e)) elif e.code == 401 or e.code == 405: # token is fine, profile is private if e.info().getheader("X-Private-User") == "true": control.infoDialog("Object is No Longer Available (%s)" % (e.code), "Trakt ERROR") raise TraktAuthError("Object is No Longer Available (%s)" % (e.code)) # auth failure retry or a token request elif auth_retry or url.endswith("/token"): self.token = None control.set_setting("trakt_oauth_token", "") control.set_setting("trakt_refresh_token", "") control.infoDialog("Trakt Call Authentication Failed (%s)" % (e.code), "Trakt ERROR") raise TraktAuthError("Trakt Call Authentication Failed (%s)" % (e.code)) # first try token fail, try to refresh token else: result = self.get_token() self.token = result["access_token"] control.set_setting("trakt_oauth_token", result["access_token"]) control.set_setting("trakt_refresh_token", result["refresh_token"]) auth_retry = True elif e.code == 404: control.infoDialog("Object Not Found (%s)" % (e.code), "Trakt ERROR") raise TraktNotFoundError("Object Not Found (%s)" % (e.code)) else: raise elif isinstance(e.reason, socket.timeout) or isinstance(e.reason, ssl.SSLError): control.infoDialog("Temporary Trakt Error: " + str(e), "Trakt ERROR") raise TransientTraktError("Temporary Trakt Error: " + str(e)) else: control.infoDialog("Trakt Error: " + str(e), "Trakt ERROR") raise TraktError("Trakt Error: " + str(e)) except: raise try: js_data = json.loads(result) if "x-sort-by" in res_headers and "x-sort-how" in res_headers: js_data = utils2.sort_list(res_headers["x-sort-by"], res_headers["x-sort-how"], js_data) except ValueError: js_data = "" if result: print("Invalid JSON Trakt API Response: %s - |%s|" % (url, js_data)) print("Trakt Response: %s" % (response)) return js_data