def addView(content): try: skin = control.skin record = (skin, content, str(control.getCurrentViewId())) control.makeFile(control.dataPath) dbcon = database.connect(control.viewsFile) dbcur = dbcon.cursor() dbcur.execute("CREATE TABLE IF NOT EXISTS views (" "skin TEXT, " "view_type TEXT, " "view_id TEXT, " "UNIQUE(skin, view_type)" ");") dbcur.execute( "DELETE FROM views WHERE skin = '%s' AND view_type = '%s'" % (record[0], record[1])) dbcur.execute("INSERT INTO views Values (?, ?, ?)", record) dbcon.commit() viewName = control.infoLabel('Container.Viewmode') skinName = control.addon(skin).getAddonInfo('name') skinIcon = control.addon(skin).getAddonInfo('icon') control.infoDialog(viewName, heading=skinName, sound=True, icon=skinIcon) except: return
def deleteBookmark(name, imdb='0'): try: idFile = hashlib.md5() for i in name: idFile.update(str(i)) for i in imdb: idFile.update(str(i)) idFile = str(idFile.hexdigest()) control.makeFile(control.dataPath) dbcon = database.connect(control.databaseFile) dbcur = dbcon.cursor() dbcur.execute("CREATE TABLE IF NOT EXISTS bookmark (""idFile TEXT, ""timeInSeconds TEXT, ""UNIQUE(idFile)"");") dbcur.execute("DELETE FROM bookmark WHERE idFile = '%s'" % idFile) dbcon.commit() except: pass
def create_folder(folder): try: folder = xbmc.makeLegalFilename(folder) control.makeFile(folder) try: if not 'ftp://' in folder: raise Exception() from ftplib import FTP ftparg = re.compile( 'ftp://(.+?):(.+?)@(.+?):?(\d+)?/(.+/?)').findall(folder) ftp = FTP(ftparg[0][2], ftparg[0][0], ftparg[0][1]) try: ftp.cwd(ftparg[0][4]) except: ftp.mkd(ftparg[0][4]) ftp.quit() except: pass except: pass
def insert(data): try: control.makeFile(control.dataPath) cacheFile = os.path.join(control.dataPath, 'regex.db') dbcon = database.connect(cacheFile) dbcur = dbcon.cursor() dbcur.execute("CREATE TABLE IF NOT EXISTS regex (" "regex TEXT, " "response TEXT, " "UNIQUE(regex)" ");") for i in data: try: dbcur.execute("INSERT INTO regex Values (?, ?)", (i['regex'], i['response'])) except: pass dbcon.commit() except: return
def reset(self, currentTime, totalTime, name, year='0'): try: if not control.setting('bookmarks') == 'true': raise Exception() timeInSeconds = str(currentTime) ok = int(currentTime) > 180 and (currentTime / totalTime) <= .92 idFile = hashlib.md5() for i in name: idFile.update(str(i)) for i in year: idFile.update(str(i)) idFile = str(idFile.hexdigest()) control.makeFile(control.dataPath) dbcon = database.connect(control.bookmarksFile) dbcur = dbcon.cursor() dbcur.execute("CREATE TABLE IF NOT EXISTS bookmark (""idFile TEXT, ""timeInSeconds TEXT, ""UNIQUE(idFile)"");") dbcur.execute("DELETE FROM bookmark WHERE idFile = '%s'" % idFile) if ok: dbcur.execute("INSERT INTO bookmark Values (?, ?)", (idFile, timeInSeconds)) dbcon.commit() except: pass
def addFavourite(meta, content, query): try: item = dict() meta = json.loads(meta) try: id = meta['imdb'] except: id = meta['tvdb'] if 'title' in meta: title = item['title'] = meta['title'] if 'originaltitle' in meta: title = item['originaltitle'] = meta['originaltitle'] if 'tvshowtitle' in meta: title = item['title'] = meta['tvshowtitle'] if 'year' in meta: item['year'] = meta['year'] if 'poster' in meta: item['poster'] = meta['poster'] if 'fanart' in meta: item['fanart'] = meta['fanart'] if 'imdb' in meta: item['imdb'] = meta['imdb'] if 'tmdb' in meta: item['tmdb'] = meta['tmdb'] if 'tvdb' in meta: item['tvdb'] = meta['tvdb'] if 'tvrage' in meta: item['tvrage'] = meta['tvrage'] control.makeFile(control.dataPath) dbcon = database.connect(control.favouritesFile) dbcur = dbcon.cursor() dbcur.execute("CREATE TABLE IF NOT EXISTS %s (" "id TEXT, " "items TEXT, " "UNIQUE(id)" ");" % content) dbcur.execute("DELETE FROM %s WHERE id = '%s'" % (content, id)) dbcur.execute("INSERT INTO %s Values (?, ?)" % content, (id, repr(item))) dbcon.commit() if query == None: control.refresh() control.infoDialog(control.lang(30411).encode('utf-8'), heading=title) except: return
def insert(meta): try: control.makeFile(control.dataPath) dbcon = database.connect(control.metacacheFile) dbcur = dbcon.cursor() dbcur.execute("CREATE TABLE IF NOT EXISTS meta (" "imdb TEXT, " "tvdb TEXT, " "lang TEXT, " "user TEXT, " "item TEXT, " "time TEXT, " "UNIQUE(imdb, tvdb, lang, user)" ");") t = int(time.time()) for m in meta: try: if not "user" in m: m["user"] = '' if not "lang" in m: m["lang"] = 'en' i = repr(m['item']) try: dbcur.execute( "DELETE * FROM meta WHERE (imdb = '%s' and lang = '%s' and user = '******' and not imdb = '0') or (tvdb = '%s' and lang = '%s' and user = '******' and not tvdb = '0')" % (m['imdb'], m['lang'], m['user'], m['tvdb'], m['lang'], m['user'])) except: pass dbcur.execute( "INSERT INTO meta Values (?, ?, ?, ?, ?, ?)", (m['imdb'], m['tvdb'], m['lang'], m['user'], i, t)) except: pass dbcon.commit() except: return
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 update(self, query=None, info='true'): if not query == None: control.idle() try: items = [] season, episode = [], [] show = [ os.path.join(self.library_folder, i) for i in control.listDir(self.library_folder)[0] ] for s in show: try: season += [ os.path.join(s, i) for i in control.listDir(s)[0] ] except: pass for s in season: try: episode.append([ os.path.join(s, i) for i in control.listDir(s)[1] if i.endswith('.strm') ][-1]) except: pass for file in episode: try: file = control.openFile(file) read = file.read() read = read.encode('utf-8') file.close() if not read.startswith(sys.argv[0]): raise Exception() params = dict(urlparse.parse_qsl(read.replace('?', ''))) try: tvshowtitle = params['tvshowtitle'] except: tvshowtitle = None try: tvshowtitle = params['show'] except: pass if tvshowtitle == None or tvshowtitle == '': raise Exception() year, imdb, tvdb = params['year'], params['imdb'], params[ 'tvdb'] imdb = 'tt' + re.sub('[^0-9]', '', str(imdb)) try: tmdb = params['tmdb'] except: tmdb = '0' items.append({ 'tvshowtitle': tvshowtitle, 'year': year, 'imdb': imdb, 'tmdb': tmdb, 'tvdb': tvdb }) except: pass items = [i for x, i in enumerate(items) if i not in items[x + 1:]] if len(items) == 0: raise Exception() except: return try: lib = control.jsonrpc( '{"jsonrpc": "2.0", "method": "VideoLibrary.GetTVShows", "params": {"properties" : ["imdbnumber", "title", "year"]}, "id": 1}' ) lib = unicode(lib, 'utf-8', errors='ignore') lib = json.loads(lib)['result']['tvshows'] except: return if info == 'true' and not control.condVisibility( 'Window.IsVisible(infodialog)') and not control.condVisibility( 'Player.HasVideo'): control.infoDialog(control.lang(32553).encode('utf-8'), time=10000000) self.infoDialog = True try: control.makeFile(control.dataPath) dbcon = database.connect(control.libcacheFile) dbcur = dbcon.cursor() dbcur.execute("CREATE TABLE IF NOT EXISTS tvshows (" "id TEXT, " "items TEXT, " "UNIQUE(id)" ");") except: return try: from resources.lib.indexers import episodes except: return files_added = 0 # __init__ doesn't get called from services so self.date never gets updated and new episodes are not added to the library self.datetime = (datetime.datetime.utcnow() - datetime.timedelta(hours=5)) self.date = (self.datetime - datetime.timedelta(hours=24)).strftime('%Y%m%d') for item in items: it = None if xbmc.abortRequested == True: return sys.exit() try: dbcur.execute("SELECT * FROM tvshows WHERE id = '%s'" % item['tvdb']) fetch = dbcur.fetchone() it = eval(fetch[1].encode('utf-8')) except: pass try: if not it == None: raise Exception() it = episodes.episodes().get(item['tvshowtitle'], item['year'], item['imdb'], item['tvdb'], idx=False) status = it[0]['status'].lower() it = [{ 'title': i['title'], 'year': i['year'], 'imdb': i['imdb'], 'tvdb': i['tvdb'], 'season': i['season'], 'episode': i['episode'], 'tvshowtitle': i['tvshowtitle'], 'premiered': i['premiered'] } for i in it] if status == 'continuing': raise Exception() dbcur.execute("INSERT INTO tvshows Values (?, ?)", (item['tvdb'], repr(it))) dbcon.commit() except: pass try: id = [item['imdb'], item['tvdb']] if not item['tmdb'] == '0': id += [item['tmdb']] ep = [ x['title'].encode('utf-8') for x in lib if str(x['imdbnumber']) in id or ( x['title'].encode('utf-8') == item['tvshowtitle'] and str(x['year']) == item['year']) ][0] ep = control.jsonrpc( '{"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodes", "params": {"filter":{"and": [{"field": "tvshow", "operator": "is", "value": "%s"}]}, "properties": ["season", "episode"]}, "id": 1}' % ep) ep = unicode(ep, 'utf-8', errors='ignore') ep = json.loads(ep).get('result', {}).get('episodes', {}) ep = [{ 'season': int(i['season']), 'episode': int(i['episode']) } for i in ep] ep = sorted(ep, key=lambda x: (x['season'], x['episode']))[-1] num = [ x for x, y in enumerate(it) if str(y['season']) == str(ep['season']) and str(y['episode']) == str(ep['episode']) ][-1] it = [y for x, y in enumerate(it) if x > num] if len(it) == 0: continue except: continue for i in it: try: if xbmc.abortRequested == True: return sys.exit() premiered = i.get('premiered', '0') if (premiered != '0' and int(re.sub('[^0-9]', '', str(premiered))) > int(self.date)) or (premiered == '0' and not self.include_unknown): continue libtvshows().strmFile(i) files_added += 1 except: pass if self.infoDialog == True: control.infoDialog(control.lang(32554).encode('utf-8'), time=1) if self.library_setting == 'true' and not control.condVisibility( 'Library.IsScanningVideo') and files_added > 0: control.execute('UpdateLibrary(video)')
def get(function, timeout, *args): try: response = None f = repr(function) f = re.sub('.+\smethod\s|.+function\s|\sat\s.+|\sof\s.+', '', f) a = hashlib.md5() for i in args: a.update(str(i)) a = str(a.hexdigest()) except: pass try: control.makeFile(control.dataPath) dbcon = database.connect(control.cachemetaFile) dbcur = dbcon.cursor() dbcur.execute( "SELECT * FROM rel_list WHERE func = '%s' AND args = '%s'" % (f, a)) match = dbcur.fetchone() response = eval(match[2].encode('utf-8')) t1 = int(match[3]) t2 = int(time.time()) update = (abs(t2 - t1) / 3600) >= int(timeout) if update == False: return response except: pass try: r = function(*args) if (r == None or r == []) and not response == None: return response elif (r == None or r == []): return r except: return try: insert = True if r['cover_url'] == '' or r['backdrop_url'] == '': insert = False r = repr(r) t = int(time.time()) dbcur.execute("CREATE TABLE IF NOT EXISTS rel_list (" "func TEXT, " "args TEXT, " "response TEXT, " "added TEXT, " "UNIQUE(func, args)" ");") dbcur.execute( "DELETE FROM rel_list WHERE func = '%s' AND args = '%s'" % (f, a)) if insert == True: dbcur.execute("INSERT INTO rel_list Values (?, ?, ?, ?)", (f, a, r, t)) dbcon.commit() except: pass try: return eval(r.encode('utf-8')) except: pass
def run(self): def download(): return [] result = cache.bennu_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()
def download(name, image, url): if url == None: return from ptw.libraries import control try: headers = dict(urlparse.parse_qsl(url.rsplit('|', 1)[1])) except: headers = dict('') url = url.split('|')[0] content = re.compile('(.+?)\sS(\d*)E\d*$').findall(name) transname = name.translate(None, '\/:*?"<>|').strip('.') levels = ['../../../..', '../../..', '../..', '..'] if len(content) == 0: dest = control.setting('movie.download.path') dest = control.transPath(dest) for level in levels: try: control.makeFile(os.path.abspath(os.path.join(dest, level))) except: pass control.makeFile(dest) dest = os.path.join(dest, transname) control.makeFile(dest) else: dest = control.setting('tv.download.path') dest = control.transPath(dest) for level in levels: try: control.makeFile(os.path.abspath(os.path.join(dest, level))) except: pass control.makeFile(dest) transtvshowtitle = content[0][0].translate(None, '\/:*?"<>|').strip('.') dest = os.path.join(dest, transtvshowtitle) control.makeFile(dest) dest = os.path.join(dest, 'Season %01d' % int(content[0][1])) control.makeFile(dest) ext = os.path.splitext(urlparse.urlparse(url).path)[1][1:] if not ext in ['mp4', 'mkv', 'flv', 'avi', 'mpg']: ext = 'mp4' dest = os.path.join(dest, transname + '.' + ext) sysheaders = urllib.quote_plus(json.dumps(headers)) sysurl = urllib.quote_plus(url) systitle = urllib.quote_plus(name) sysimage = urllib.quote_plus(image) sysdest = urllib.quote_plus(dest) script = inspect.getfile(inspect.currentframe()) cmd = 'RunScript(%s, %s, %s, %s, %s, %s)' % ( script, sysurl, sysdest, systitle, sysimage, sysheaders) xbmc.executebuiltin(cmd)