def CleanExpired(self): #delete files more than an hour old self.Notification('Hulu Library','Removing Expired Content') #delete old tv show files dir = xbmc.makeLegalFilename(TV_SHOWS_PATH) dirs, trash = xbmcvfs.listdir(dir) for show in dirs: show = xbmc.makeLegalFilename(os.path.join(dir, show)) trash, files = xbmcvfs.listdir(show) for file in files: path = xbmc.makeLegalFilename(os.path.join(show,file)) if (sys.platform == 'win32'): path = path.replace('smb:','') if (time.mktime(time.strptime(time.ctime(os.path.getmtime(path)))) < (time.mktime(time.localtime()) - 3600)): xbmcvfs.delete(path) #delete old movie files dir = xbmc.makeLegalFilename(MOVIE_PATH) trash, movies = xbmcvfs.listdir(dir) for movie in movies: path = xbmc.makeLegalFilename(os.path.join(dir, movie)) if (sys.platform == 'win32'): path = path.replace('smb:','') if time.mktime(time.strptime(time.ctime(os.path.getmtime(path)))) < (time.mktime(time.localtime()) - 3600): xbmcvfs.delete(path) xbmc.log(path) self.Notification('Hulu Library','Expired Content Removed')
def getOfflineFileList(cachePath): localFiles = [] #workaround for this issue: https://github.com/xbmc/xbmc/pull/8531 if xbmcvfs.exists(cachePath) or os.path.exists(cachePath): dirs,files = xbmcvfs.listdir(cachePath) for dir in dirs: subdir,subfiles = xbmcvfs.listdir(str(cachePath) + '/' + str(dir)) for file in subfiles: if bool(re.search('\.stream\.mp4', file)): try: nameFile = xbmcvfs.File(str(cachePath) + '/' + str(dir) + '/' + str(dir) + '.name') filename = nameFile.read() nameFile.close() except: filename = file try: nameFile = xbmcvfs.File(str(cachePath) + '/' + str(dir) + '/' + str(os.path.splitext(file)[0]) + '.resolution') resolution = nameFile.read() nameFile.close() except: resolution = file offlineFile = offlinefile.offlinefile(filename, str(cachePath) + '/' + str(dir) +'.jpg', resolution.rstrip(), str(cachePath) + '/' + str(dir) + '/' + str(os.path.splitext(file)[0]) + '.mp4') localFiles.append(offlineFile) return localFiles
def Download(url,lang): try: rmtree(__temp__) except: pass try: os.makedirs(__temp__) except: pass subtitle_list = [] exts = [".srt", ".sub", ".smi", ".ssa", ".ass" ] log( sys._getframe().f_code.co_name ,"Download page: %s" % (url)) try: req = urllib2.Request(url) req.add_header('User-Agent', UserAgent) socket = urllib2.urlopen(req) data = socket.read() soup = BeautifulSoup(data, 'html.parser') url = soup.find("li", class_="dlsub").a.get('href').encode('utf-8') if url[:4] != 'http': url = ZIMUKU_BASE + url log( sys._getframe().f_code.co_name ,"Download links: %s" % (url)) req = urllib2.Request(url) req.add_header('User-Agent', UserAgent) socket = urllib2.urlopen(req) data = socket.read() socket.close() soup = BeautifulSoup(data, 'html.parser') links = soup.find("div", {"class":"clearfix"}).find_all('a') except: log( sys.exc_info()[2].tb_frame.f_code.co_name, "(%d) [%s]" % ( sys.exc_info()[2].tb_lineno, sys.exc_info()[1] )) return [] filename, data = DownloadLinks(links, url) if len(data) < 1024: return [] tempfile = os.path.join(__temp__, "subtitles%s" % os.path.splitext(filename)[1]) with open(tempfile, "wb") as subFile: subFile.write(data) subFile.close() xbmc.sleep(500) if data[:4] == 'Rar!' or data[:2] == 'PK': xbmc.executebuiltin(('XBMC.Extract("%s","%s")' % (tempfile,__temp__,)).encode('utf-8'), True) path = __temp__ dirs, files = xbmcvfs.listdir(path) if len(dirs) > 0: path = os.path.join(__temp__, dirs[0].decode('utf-8')) dirs, files = xbmcvfs.listdir(path) list = [] for subfile in files: if (os.path.splitext( subfile )[1] in exts): list.append(subfile.decode('utf-8')) if len(list) == 1: subtitle_list.append(os.path.join(path, list[0])) else: sel = xbmcgui.Dialog().select('请选择压缩包中的字幕', list) if sel == -1: sel = 0 subtitle_list.append(os.path.join(path, list[sel])) return subtitle_list
def listFilesInPath(path, allFilesList=None): #used for easy matching of studio logos if not allFilesList: allFilesList = {} dirs, files = xbmcvfs.listdir(path) for file in files: file = file.decode("utf-8") name = file.split(".png")[0].lower() if not allFilesList.has_key(name): allFilesList[name] = path + file for dir in dirs: dirs2, files2 = xbmcvfs.listdir(os.path.join(path,dir)+os.sep) for file in files2: file = file.decode("utf-8") dir = dir.decode("utf-8") name = dir + "/" + file.split(".png")[0].lower() if not allFilesList.has_key(name): if "/" in path: sep = "/" else: sep = "\\" allFilesList[name] = path + dir + sep + file #return the list return allFilesList
def parser_check(): dirs,files = xbmcvfs.listdir(base_dir) if not dirs: dirpackages,filespackages = xbmcvfs.listdir(parser_packages_folder) if filespackages: for fich in filespackages: shutil.copyfile(os.path.join(parser_packages_folder,fich), os.path.join(parser_core_folder,fich)) xbmc.sleep(100) import tarfile if tarfile.is_tarfile(os.path.join(parser_core_folder,fich)): download_tools().extract(os.path.join(parser_core_folder,fich),parser_core_folder) download_tools().remove(os.path.join(parser_core_folder,fich)) else: dirsuserdata,files = xbmcvfs.listdir(parser_folder) for fich in files: dictionary_module = eval(readfile(os.path.join(parser_folder,fich))) if "url" in dictionary_module.keys(): add_new_parser(dictionary_module["url"]) else: xbmcvfs.copy(os.path.join(parser_packages_folder,fich.replace('.txt','.tar.gz')),os.path.join(parser_core_folder,fich.replace('.txt','.tar.gz'))) import tarfile if tarfile.is_tarfile(os.path.join(parser_core_folder,fich.replace('.txt','.tar.gz'))): download_tools().extract(os.path.join(parser_core_folder,fich.replace('.txt','.tar.gz')),parser_core_folder) download_tools().remove(os.path.join(parser_core_folder,fich.replace('.txt','.tar.gz'))) else: pass return
def delete_cache(cls): # Remove all existing textures first path = xbmc.translatePath('special://thumbnails/').decode('utf-8') if xbmcvfs.exists(path): dirs, ignore_files = xbmcvfs.listdir(path) for directory in dirs: ignore_dirs, files = xbmcvfs.listdir(path + directory) for file_ in files: if os.path.supports_unicode_filenames: filename = os.path.join(path + directory.decode('utf-8'), file_.decode('utf-8')) else: filename = os.path.join(path.encode('utf-8') + directory, file_) xbmcvfs.delete(filename) log.debug("deleted: %s", filename) # remove all existing data from texture DB with DatabaseConn('texture') as cursor_texture: cursor_texture.execute('SELECT tbl_name FROM sqlite_master WHERE type="table"') rows = cursor_texture.fetchall() for row in rows: table_name = row[0] if table_name != "version": cursor_texture.execute("DELETE FROM " + table_name)
def lookup_custom_path(self, searchtitle, title): '''looks up a custom directory if it contains a subdir for our title''' details = {} details["art"] = {} title_path = self.get_custom_path(searchtitle, title) if title_path and xbmcvfs.exists(title_path): # we have found a folder for the title, look for artwork files = xbmcvfs.listdir(title_path)[1] for item in files: item = item.decode("utf-8") if item in ["banner.jpg", "clearart.png", "poster.png", "fanart.jpg", "landscape.jpg"]: key = item.split(".")[0] details["art"][key] = title_path + item elif item == "logo.png": details["art"]["clearlogo"] = title_path + item elif item == "thumb.jpg": details["art"]["thumb"] = title_path + item # extrafanarts efa_path = title_path + "extrafanart/" if xbmcvfs.exists(title_path + "extrafanart"): files = xbmcvfs.listdir(efa_path)[1] details["art"]["fanarts"] = [] if files: details["art"]["extrafanart"] = efa_path for item in files: item = efa_path + item.decode("utf-8") details["art"]["fanarts"].append(item) return details
def merge_epg(): # code from enen92. thank you print '[Rytec EPG Downloader]: merge epg' xml_path = get_xml_path() temp = os.path.join(xml_path,'temp') if not os.path.isdir(temp): os.mkdir(temp) out = os.path.join(xml_path,'merged_epg.xml') if xbmcvfs.exists(out): os.remove(out) print '[Rytec EPG Downloader]: start extracting files' dirs, files = xbmcvfs.listdir(os.path.join(xml_path)) for f in files: if f.endswith('.gz'): inF = gzip.GzipFile(os.path.join(xml_path,f), 'rb') s = inF.read() inF.close() outF = file(os.path.join(temp,f.replace('.gz','.xml')),'wb') outF.write(s) outF.close() print '[Rytec EPG Downloader]: extracting files done' print '[Rytec EPG Downloader]: start merging files' dirs, xmltv_list = xbmcvfs.listdir(os.path.join(temp)) i=1 total = len(xmltv_list) for xmltv in xmltv_list: if xmltv.endswith('.xml'): if i==1: f = open(os.path.join(temp,xmltv), "r") text = f.read() f.close() with open(out, "a") as myfile: myfile.write(text.replace('</tv>','')) elif i==total: o = open(out,"a") f = open(os.path.join(temp,xmltv),"r") lines = f.readlines() f.close() li = 0 for line in lines: if li == 0 or li == 1: pass else: o.write(line) li += 1 o.close() else: o = open(out,"a") f = open(os.path.join(temp,xmltv),"r") lines = f.readlines() total_lines = len(lines) f.close() li = 0 for line in lines: if li == 0 or li == 1: pass elif li == (total_lines -1): pass else: o.write(line) li += 1 o.close() os.remove(os.path.join(temp,xmltv)) i += 1 print '[Rytec EPG Downloader]: merging files done'
def Download(url,lang): try: shutil.rmtree(__temp__) except: pass try: os.makedirs(__temp__) except: pass subtitle_list = [] exts = [".srt", ".sub", ".txt", ".smi", ".ssa", ".ass" ] try: socket = urllib.request.urlopen( url ) data = socket.read() soup = BeautifulSoup(data) id = soup.find("button", class_="btn btn-danger btn-sm").get("sid").encode('utf-8') url = "http://www.subhd.com/ajax/down_ajax" values = {'sub_id':id} data = urllib.parse.urlencode(values) req = urllib.request.Request(url, data) response = urllib.request.urlopen(req) data = response.read() match = re.compile('"url":"([^"]+)"').search(data) url = SUBHD_BASE + match.group(1).replace(r'\/','/').decode("unicode-escape").encode('utf-8') socket = urllib.request.urlopen( url ) data = socket.read() socket.close() except: return [] if len(data) < 1024: return [] if data[:4] == 'Rar!': zip = os.path.join(__temp__,"subtitles.rar") elif data[:2] == 'PK': zip = os.path.join(__temp__,"subtitles.zip") else: zip = os.path.join(__temp__,"subtitles.srt") with open(zip, "wb") as subFile: subFile.write(data) subFile.close() xbmc.sleep(500) if not zip.endswith('.srt'): xbmc.executebuiltin(('XBMC.Extract("%s","%s")' % (zip,__temp__,)).encode('utf-8'), True) path = __temp__ dirs, files = xbmcvfs.listdir(path) if len(dirs) > 0: path = os.path.join(__temp__, dirs[0].decode('utf-8')) dirs, files = xbmcvfs.listdir(path) list = [] for subfile in files: if (os.path.splitext( subfile )[1] in exts): list.append(subfile.decode('utf-8')) if len(list) == 1: subtitle_list.append(os.path.join(path, list[0])) else: sel = xbmcgui.Dialog().select('请选择压缩包中的字幕', list) if sel == -1: sel = 0 subtitle_list.append(os.path.join(path, list[sel])) return subtitle_list
def delete_files(source, match, del_empty=False): # delete files from source if match dirs, files = xbmcvfs.listdir(source) for f in files: if match in f: f = os.path.join(source, f) xbmcvfs.delete(f) # delete source directory if empty if del_empty and len(xbmcvfs.listdir(source)) == 0: xbmcvfs.rmdir(source)
def __delete_files_alt(source, match, del_empty): # delete files from source if match dirs, files = xbmcvfs.listdir(source) for f in files: if match == os.path.splitext(f)[0]: f = os.path.join(source, f) xbmcvfs.delete(f) # delete source directory if empty if del_empty and len(xbmcvfs.listdir(source)) == 0: xbmcvfs.rmdir(source)
def __delete_files_alt(source, match, del_empty): # delete files from source if match dirs, files = xbmcvfs.listdir(source) for f in files: if os.path.splitext(f)[0].startswith(match): f = os.path.join(source, f) if not xbmcvfs.delete(f): raise ValueError('xbmcvfs.delete', f) # delete source directory if empty if del_empty and len(xbmcvfs.listdir(source)) == 0: if not xbmcvfs.rmdir(source): raise ValueError('xbmcvfs.rmdir', source)
def Download(id,lang): try: rmtree(__temp__) except: pass try: os.makedirs(__temp__) except: pass subtitle_list = [] exts = [".srt", ".sub", ".smi", ".ssa", ".ass" ] url = DOWNLOAD_API % (id) try: socket = urllib.urlopen( url ) data = socket.read() socket.close() soup = BeautifulSoup(data) url = soup.find("a", class_="down_ink download_link").get('href').encode('utf-8') socket = urllib.urlopen( url ) #filename = socket.headers['Content-Disposition'].split('filename=')[1] #if filename[0] == '"' or filename[0] == "'": # filename = filename[1:-1] filename = os.path.basename(url) data = socket.read() socket.close() except: return [] if len(data) < 1024: return [] tempfile = os.path.join(__temp__, "subtitles%s" % os.path.splitext(filename)[1]) with open(tempfile, "wb") as subFile: subFile.write(data) subFile.close() xbmc.sleep(500) if data[:4] == 'Rar!' or data[:2] == 'PK': xbmc.executebuiltin(('XBMC.Extract("%s","%s")' % (tempfile,__temp__,)).encode('utf-8'), True) path = __temp__ dirs, files = xbmcvfs.listdir(path) if ('__MACOSX') in dirs: dirs.remove('__MACOSX') if len(dirs) > 0: path = os.path.join(__temp__, dirs[0].decode('utf-8')) dirs, files = xbmcvfs.listdir(path) list = [] for subfile in files: if (os.path.splitext( subfile )[1] in exts): list.append(subfile.decode('utf-8')) if len(list) == 1: subtitle_list.append(os.path.join(path, list[0])) elif len(list) > 1: sel = xbmcgui.Dialog().select('请选择压缩包中的字幕', list) if sel == -1: sel = 0 subtitle_list.append(os.path.join(path, list[sel])) return subtitle_list
def Download(url,lang): try: rmtree(__temp__) except: pass try: os.makedirs(__temp__) except: pass subtitle_list = [] exts = [".srt", ".sub", ".smi", ".ssa", ".ass" ] try: req = urllib2.Request(url) req.add_header('User-Agent', UserAgent) socket = urllib2.urlopen(req) data = socket.read() socket.close() soup = BeautifulSoup(data) url = '%s%s' % (ZIMUKU_BASE, soup.find("li", class_="dlsub").a.get('href').encode('utf-8')) req = urllib2.Request(url) req.add_header('User-Agent', UserAgent) socket = urllib2.urlopen(req) filename = socket.headers['Content-Disposition'].split('filename=')[1] if filename[0] == '"' or filename[0] == "'": filename = filename[1:-1] data = socket.read() socket.close() except: return [] if len(data) < 1024: return [] tempfile = os.path.join(__temp__, "subtitles%s" % os.path.splitext(filename)[1]) with open(tempfile, "wb") as subFile: subFile.write(data) subFile.close() xbmc.sleep(500) if data[:4] == 'Rar!' or data[:2] == 'PK': xbmc.executebuiltin(('XBMC.Extract("%s","%s")' % (tempfile,__temp__,)).encode('utf-8'), True) path = __temp__ dirs, files = xbmcvfs.listdir(path) if len(dirs) > 0: path = os.path.join(__temp__, dirs[0].decode('utf-8')) dirs, files = xbmcvfs.listdir(path) list = [] for subfile in files: if (os.path.splitext( subfile )[1] in exts): list.append(subfile.decode('utf-8')) if len(list) == 1: subtitle_list.append(os.path.join(path, list[0])) else: sel = xbmcgui.Dialog().select('请选择压缩包中的字幕', list) if sel == -1: sel = 0 subtitle_list.append(os.path.join(path, list[sel])) return subtitle_list
def DownloadID(id): if xbmcvfs.exists(__temp__): rmtree(__temp__) xbmc.sleep(50) xbmcvfs.mkdirs(__temp__) subtitle_list = [] if id.startswith('999999'): url = 'http://sub.makedie.me/download/%06d/%s' %(int(id[6:]), 'XBMC.SUBTITLE') else: url = 'http://shooter.cn/files/file3.php?hash=duei7chy7gj59fjew73hdwh213f&fileid=%s' % (id) socket = urllib.urlopen( url ) data = socket.read() url = 'http://file0.shooter.cn%s' % (CalcFileHash(data)) #log(sys._getframe().f_code.co_name ,"url is %s" % (url)) socket = urllib.urlopen( url ) data = socket.read() socket.close() header = data[:4] if header == 'Rar!': zipext = ".rar" else: # header == 'PK': zipext = ".zip" zipname = 'SUBPACK%s' % (zipext) zip = os.path.join( __temp__, zipname) with open(zip, "wb") as subFile: subFile.write(data) subFile.close() xbmc.sleep(500) dirs, files = xbmcvfs.listdir(__temp__) # refresh xbmc folder cache xbmc.executebuiltin(('XBMC.Extract("%s","%s")' % (zip,__temp__,)).encode('utf-8'), True) path = __temp__ dirs, files = xbmcvfs.listdir(path) list = CheckSubList(files) if not list and len(dirs) > 0: path = os.path.join(__temp__, dirs[0].decode('utf-8')) dirs, files = xbmcvfs.listdir(path) list = CheckSubList(files) if list: filename = list[0].decode('utf-8') else: filename = '' if len(list) > 1: dialog = xbmcgui.Dialog() sel = dialog.select(__language__(32006), list) if sel != -1: filename = list[sel].decode('utf-8') if filename: filepath = os.path.join(path, filename) ChangeFileEndcoding(filepath) subtitle_list.append(filepath) return subtitle_list
def clear_parser_trace(): dirs,files = xbmcvfs.listdir(parser_core_folder) import shutil for directory in dirs: shutil.rmtree(os.path.join(parser_core_folder,directory)) dirs,files = xbmcvfs.listdir(parser_packages_folder) for fich in files: xbmcvfs.delete(os.path.join(parser_packages_folder,fich)) dirs,files = xbmcvfs.listdir(parser_folder) for fich in files: xbmcvfs.delete(os.path.join(parser_folder,fich)) xbmc.executebuiltin("Notification(%s,%s,%i,%s)" % (translate(40000),translate(70007),1,addonpath+"/icon.png"))
def Download(url,lang): try: rmtree(__temp__) except: pass try: os.makedirs(__temp__) except: pass subtitle_list = [] exts = [".srt", ".sub", ".txt", ".smi", ".ssa", ".ass" ] try: data = GetHttpData(url) soup = BeautifulSoup(data) id = soup.find("button", class_="btn btn-danger btn-sm").get("sid").encode('utf-8') url = "http://subhd.com/ajax/down_ajax" values = {'sub_id':id} para = urllib.urlencode(values) data = GetHttpData(url, para) match = re.compile('"url":"([^"]+)"').search(data) url = match.group(1).replace(r'\/','/').decode("unicode-escape").encode('utf-8') if url[:4] <> 'http': url = 'http://subhd.com%s' % (url) data = GetHttpData(url) except: return [] if len(data) < 1024: return [] zip = os.path.join(__temp__, "subtitles%s" % os.path.splitext(url)[1]) with open(zip, "wb") as subFile: subFile.write(data) subFile.close() xbmc.sleep(500) if data[:4] == 'Rar!' or data[:2] == 'PK': xbmc.executebuiltin(('XBMC.Extract("%s","%s")' % (zip,__temp__,)).encode('utf-8'), True) path = __temp__ dirs, files = xbmcvfs.listdir(path) if ('__MACOSX') in dirs: dirs.remove('__MACOSX') if len(dirs) > 0: path = os.path.join(__temp__, dirs[0].decode('utf-8')) dirs, files = xbmcvfs.listdir(path) list = [] for subfile in files: if (os.path.splitext( subfile )[1] in exts): list.append(subfile.decode('utf-8')) if len(list) == 1: subtitle_list.append(os.path.join(path, list[0])) elif len(list) > 1: sel = xbmcgui.Dialog().select('请选择压缩包中的字幕', list) if sel == -1: sel = 0 subtitle_list.append(os.path.join(path, list[sel])) return subtitle_list
def Download(url,lang): try: shutil.rmtree(__temp__) except: pass try: os.makedirs(__temp__) except: pass subtitle_list = [] exts = [".srt", ".sub", ".txt", ".smi", ".ssa", ".ass" ] try: socket = urllib.urlopen( url ) data = socket.read() soup = BeautifulSoup(data) results = soup.find("a", class_="down_ink download_link").get("onclick").encode('utf-8') id = results.split("'") url = "http://www.subom.net/index.php?m=down&a=sub&id=%s&s_id=%s" % (id[1], id[3]) socket = urllib.urlopen( url ) data = socket.read() socket.close() except: return [] if len(data) < 1024: return [] if data[:4] == 'Rar!': zip = os.path.join(__temp__,"subtitles.rar") elif data[:2] == 'PK': zip = os.path.join(__temp__,"subtitles.zip") else: zip = os.path.join(__temp__,"subtitles.srt") with open(zip, "wb") as subFile: subFile.write(data) subFile.close() xbmc.sleep(500) if not zip.endswith('.srt'): xbmc.executebuiltin(('XBMC.Extract("%s","%s")' % (zip,__temp__,)).encode('utf-8'), True) path = __temp__ dirs, files = xbmcvfs.listdir(path) if len(dirs) > 0: path = os.path.join(__temp__, dirs[0].decode('utf-8')) dirs, files = xbmcvfs.listdir(path) list = [] for subfile in files: if (os.path.splitext( subfile )[1] in exts): list.append(subfile.decode('utf-8')) if len(list) == 1: subtitle_list.append(os.path.join(path, list[0])) else: sel = xbmcgui.Dialog().select('请选择压缩包中的字幕', list) if sel == -1: sel = 0 subtitle_list.append(os.path.join(path, list[sel])) return subtitle_list
def DownloadID(url): try: shutil.rmtree(__temp__) except: pass try: os.makedirs(__temp__) except: pass subtitle_list = [] url = urllib.unquote(url) socket = urllib2.urlopen( url ) data = socket.read() socket.close() soup = BeautifulSoup(data) href = soup.find(id="btn_download")['href'] url= ('http://sub.makedie.me%s' % href) socket = urllib.urlopen( url ) data = socket.read() socket.close() zipname = urllib.unquote(os.path.basename(url)) zip = os.path.join( __temp__, zipname) with open(zip, "wb") as subFile: subFile.write(data) subFile.close() xbmc.sleep(500) if data[:4] == 'Rar!' or data[:2] == 'PK': xbmc.executebuiltin(('XBMC.Extract("%s","%s")' % (zip,__temp__,)).encode('utf-8'), True) path = __temp__ dirs, files = xbmcvfs.listdir(path) list = CheckSubList(files) if not list and len(dirs) > 0: path = os.path.join(__temp__, dirs[0].decode('utf-8')) dirs, files = xbmcvfs.listdir(path) list = CheckSubList(files) if list: filename = list[0].decode('utf-8') else: filename = '' if len(list) > 1: dialog = xbmcgui.Dialog() sel = dialog.select(__language__(32006), list) if sel != -1: filename = list[sel].decode('utf-8') if filename: filepath = os.path.join(path, filename) ChangeFileEndcoding(filepath) subtitle_list.append(filepath) return subtitle_list
def updatedb_from_exported(self): """Adds movies and shows from exported media to the local db Returns ------- bool Process finished """ tv_show_path = self.tvshow_path db_filepath = self.db_filepath if xbmcvfs.exists(self.nx_common.check_folder_path(self.movie_path)): movies = xbmcvfs.listdir(self.movie_path) for video in movies[0]: folder = os.path.join(self.movie_path, video) file = xbmcvfs.listdir(folder) year = int(str(file[1]).split("(", 1)[1].split(")", 1)[0]) alt_title = unicode(video.decode('utf-8')) title = unicode(video.decode('utf-8')) movie_meta = '%s (%d)' % (title, year) if self.movie_exists(title=title, year=year) is False: self.db[self.movies_label][movie_meta] = { 'alt_title': alt_title} self._update_local_db(filename=db_filepath, db=self.db) if xbmcvfs.exists(self.nx_common.check_folder_path(tv_show_path)): shows = xbmcvfs.listdir(tv_show_path) for video in shows[0]: show_dir = os.path.join(tv_show_path, video) title = unicode(video.decode('utf-8')) alt_title = unicode(video.decode('utf-8')) show_meta = '%s' % (title) if self.show_exists(title) is False: self.db[self.series_label][show_meta] = { 'seasons': [], 'episodes': [], 'alt_title': alt_title} episodes = xbmcvfs.listdir(show_dir) for episode in episodes[1]: file = str(episode).split(".")[0] season = int(str(file).split("S")[1].split("E")[0]) episode = int(str(file).split("E")[1]) episode_meta = 'S%02dE%02d' % (season, episode) episode_exists = self.episode_exists( title=title, season=season, episode=episode) if episode_exists is False: self.db[self.series_label][title]['episodes'].append(episode_meta) self._update_local_db( filename=self.db_filepath, db=self.db) return True
def addon_parsers_menu(): if settings.getSetting('parser_disclaimer') == "true": opcao= xbmcgui.Dialog().yesno(translate(40000),translate(70004),translate(70005),translate(70006)) if opcao: settings.setSetting('parser_disclaimer',"false") dirs,files = xbmcvfs.listdir(base_dir) if not dirs: dirsuserdata,files = xbmcvfs.listdir(parser_folder) for fich in files: dictionary_module = eval(readfile(os.path.join(parser_folder,fich))) if "url" in dictionary_module.keys(): add_new_parser(dictionary_module["url"]) else: xbmcvfs.copy(os.path.join(parser_packages_folder,fich.replace('.txt','.tar.gz')),os.path.join(parser_core_folder,fich.replace('.txt','.tar.gz'))) import tarfile if tarfile.is_tarfile(os.path.join(parser_core_folder,fich.replace('.txt','.tar.gz'))): download_tools().extract(os.path.join(parser_core_folder,fich.replace('.txt','.tar.gz')),parser_core_folder) download_tools().remove(os.path.join(parser_core_folder,fich.replace('.txt','.tar.gz'))) dirs,files = xbmcvfs.listdir(base_dir) parser_dict = {} for module in dirs: module_dir = os.path.join(base_dir,module) module_cfg = os.path.join(module_dir,"module.cfg") module_icon = os.path.join(module_dir,"icon.png") module_fanart = os.path.join(module_dir,"fanart.jpg") if xbmcvfs.exists(module_icon): thumbnail = module_icon else: thumbnail = 'os.path.join(module_dir,"")' if xbmcvfs.exists(module_fanart): fanart = module_fanart else: fanart = '' if xbmcvfs.exists(module_cfg): cfg = readfile(module_cfg) try: cfg = eval(cfg) module_name = cfg['name'] except: module_name = None if module_name: parser_dict[module_name] = [module,thumbnail,fanart] total_parsers = len(parser_dict.keys()) if settings.getSetting('parser_sync') == "true": try:t1 = datetime.datetime.strptime(settings.getSetting("parsers_last_sync"), "%Y-%m-%d %H:%M:%S.%f") except:t1 = datetime.datetime.fromtimestamp(time.mktime(time.strptime(settings.getSetting("parsers_last_sync"), "%Y-%m-%d %H:%M:%S.%f"))) t2 = datetime.datetime.now() hoursList = [10, 15, 20, 24] interval = int(settings.getSetting("parser_sync_cron")) update = abs(t2 - t1) > datetime.timedelta(hours=hoursList[interval]) if update: sync_parser() settings.setSetting('parsers_last_sync',value=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")) for key in sorted(parser_dict.keys()): addDir(key,MainURL,401,parser_dict[key][1],total_parsers,True,parser=parser_dict[key][0]) addDir(translate(400011),MainURL,402,addonpath + art + 'plus-menu.png',2,False)
def walk_dir(dir): exts = [".srt", ".sub", ".smi", ".ssa", ".ass" ] files_list = [] print ('dir: %s' % dir) for subdir in xbmcvfs.listdir(dir)[0]: print ('scanning: %s' % subdir) files_list.extend(walk_dir(os.path.join(dir,subdir))) for file in xbmcvfs.listdir(dir)[1]: if (os.path.splitext(file)[1] in exts): print ('appending %s' % file) files_list.append(os.path.join(dir,file)) return files_list
def addVideos(): entries = [] fileTypes = ( ".mkv", ".avi", ".mp4", ".wmv", ".flv", ".mpg", ".mpeg", ".mov", ".ts", ".m2ts", ".m4v", ".m2v", ".rm", ".3gp", ".asf", ".asx", ".amv", ".divx", ".pls", ".strm", ".m3u", ".mp3", ".aac", ".flac", ".ogg", ".wma", ".wav", ) if videoDir.startswith(("smb://", "nfs://", "upnp://", "ftp://")): dirs, files = xbmcvfs.listdir(videoDir) for file in files: if file.lower().endswith(fileTypes): entries.append(os.path.join(videoDir, file)) for dir in dirs: dirs2, files = xbmcvfs.listdir(os.path.join(videoDir, dir)) for file in files: if file.lower().endswith(fileTypes): entries.append(os.path.join(videoDir, os.path.join(dir, file))) else: for root, dirs, files in os.walk(videoDir): for filename in files: if filename.lower().endswith(fileTypes): entries.append(os.path.join(root, filename)) random.shuffle(entries) for file in entries: playlist.add(file)
def getDirList(path, newl=None): l=[] try: if not newl: dirs, newl=xbmcvfs.listdir(path) except: try: if not newl: dirs, newl=xbmcvfs.listdir(path.decode('utf-8').encode('cp1251')) except: showMessage(__language__(30206), __language__(30280), forced=True) return l for fl in newl: match=re.match('.avi|.mp4|.mkV|.flv|.mov|.vob|.wmv|.ogm|.asx|.mpg|mpeg|.avc|.vp3|.fli|.flc|.m4v', fl[int(len(fl))-4:len(fl)], re.I) if match: l.append(fl) return l
def get_play_count(filename): # Obtaining playback counter play_count = False if not filename or sqlite is None: return play_count # get path to database and determine videobase filename basepath = xbmc.translatePath("special://database") for basefile in xbmcvfs.listdir(basepath)[1]: if 'MyVideos' in basefile: videobase = basefile # connect to database db = sqlite.connect(os.path.join(basepath, videobase)) try: sqlcur = db.execute('SELECT playCount FROM files WHERE strFilename like ?', ('%'+filename+'%',)) res_playCount = sqlcur.fetchall() if res_playCount: # check in the result data for at the least one played current file if any(plcount > 0 for plcount in res_playCount): play_count = True except: print 'Error connection to table file. Database is may be busy' db.close() return play_count
def listdir(fle): FileAccess.log('listdir ' + fle) try: results = xbmcvfs.listdir(os.path.join(fle,'')) return results except: return [],[]
def delete_empty_folders(self, location): """ Delete the folder if it is empty. Presence of custom file extensions can be ignored while scanning. To achieve this, edit the ignored file types setting in the addon settings. Example: success = delete_empty_folders(path) :type location: str :param location: The path to the folder to be deleted. :rtype: bool :return: True if the folder was deleted successfully, False otherwise. """ if not get_setting(delete_folders): debug("Deleting of empty folders is disabled.") return False folder = self.unstack(location)[0] # Stacked paths should have the same parent, use any debug("Checking if %r is empty" % folder) ignored_file_types = [file_ext.strip() for file_ext in get_setting(ignore_extensions).split(",")] debug("Ignoring file types %r" % ignored_file_types) subfolders, files = xbmcvfs.listdir(folder) debug("Contents of %r:\nSubfolders: %r\nFiles: %r" % (folder, subfolders, files)) empty = True try: for f in files: _, ext = os.path.splitext(f) if ext and not ext in ignored_file_types: # ensure f is not a folder and its extension is not ignored debug("Found non-ignored file type %r" % ext) empty = False break except OSError as oe: debug("Error deriving file extension. Errno " + str(oe.errno), xbmc.LOGERROR) empty = False # Only delete directories if we found them to be empty (containing no files or filetypes we ignored) if empty: debug("Directory is empty and will be removed") try: # Recursively delete any subfolders for f in subfolders: debug("Deleting file at " + str(os.path.join(folder, f))) self.delete_empty_folders(os.path.join(folder, f)) # Delete any files in the current folder for f in files: debug("Deleting file at " + str(os.path.join(folder, f))) xbmcvfs.delete(os.path.join(folder, f)) # Finally delete the current folder return xbmcvfs.rmdir(folder) except OSError as oe: debug("An exception occurred while deleting folders. Errno " + str(oe.errno), xbmc.LOGERROR) return False else: debug("Directory is not empty and will not be removed") return False
def get_customfolder_path(self, customfolder, foldername, sublevel=False): '''search recursively (max 2 levels) for a specific folder''' cachestr = "customfolder_path.%s.%s" % (customfolder, foldername) folder_path = self.cache.get(cachestr) if not folder_path: if "\\" in customfolder: delim = "\\" else: delim = "/" dirs = xbmcvfs.listdir(customfolder)[0] for strictness in [1, 0.95, 0.9, 0.8]: for directory in dirs: directory = directory.decode("utf-8") curpath = os.path.join(customfolder, directory) + delim match = SM(None, foldername.lower(), directory.lower()).ratio() if match >= strictness: folder_path = curpath elif not sublevel: # check if our requested path is in a sublevel of the current path # restrict the number of sublevels to just one for now for performance reasons folder_path = self.get_customfolder_path(curpath, foldername, True) if folder_path: break if folder_path: break if not sublevel: self.cache.set(cachestr, folder_path) return folder_path
def Download(id,url,format,stack=False): subtitle_list = [] exts = [".srt", ".sub", ".txt", ".smi", ".ssa", ".ass" ] if stack: ## we only want XMLRPC download if movie is not in stack, ## you can only retreive multiple subs in zip result = False else: subtitle = os.path.join(__temp__, "%s.%s" %(str(uuid.uuid4()), format)) try: result = OSDBServer().download(id, subtitle) except: log( __name__, "failed to connect to service for subtitle download") return subtitle_list if not result: log( __name__,"Download Using HTTP") zip = os.path.join( __temp__, "OpenSubtitles.zip") f = urllib.urlopen(url) with open(zip, "wb") as subFile: subFile.write(f.read()) subFile.close() xbmc.sleep(500) xbmc.executebuiltin(('XBMC.Extract("%s","%s")' % (zip,__temp__,)).encode('utf-8'), True) for file in xbmcvfs.listdir(zip)[1]: file = os.path.join(__temp__, file) if (os.path.splitext( file )[1] in exts): subtitle_list.append(file) else: subtitle_list.append(subtitle) if xbmcvfs.exists(subtitle_list[0]): return subtitle_list
def getFilesByWildcardExt(self, pathName): Logutil.log('Begin getFilesByWildcard. pathName = %s' %pathName, util.LOG_LEVEL_INFO) files = [] dirname = os.path.dirname(pathName) Logutil.log("dirname: " +dirname, util.LOG_LEVEL_INFO) filemask = os.path.basename(pathName) #HACK: escape [] for use with fnmatch filemask = filemask.replace('[', '[[]') filemask = filemask.replace(']', '[]]') #This might be stupid but it was late... filemask = filemask.replace('[[[]]', '[[]') Logutil.log("filemask: " +filemask, util.LOG_LEVEL_INFO) dirs, filesLocal = xbmcvfs.listdir(dirname) Logutil.log("xbmcvfs dirs: %s" %dirs, util.LOG_LEVEL_INFO) Logutil.log("xbmcvfs files: %s" %filesLocal, util.LOG_LEVEL_INFO) for file in filesLocal: if(fnmatch.fnmatch(file, filemask)): #allFiles = [f.decode(sys.getfilesystemencoding()).encode('utf-8') for f in glob.glob(newRomPath)] file = util.joinPath(dirname, file) files.append(file) return dirs, files, dirname, filemask """
def remove_item(item_task, library_home=None): """Remove an item from the library and delete if from disk""" # pylint: disable=unused-argument, broad-except common.info('Removing {} from library', item_task['title']) exported_filename = xbmc.translatePath(item_task['filepath']) videoid = item_task['videoid'] common.debug('VideoId: {}', videoid) try: parent_folder = xbmc.translatePath(os.path.dirname(exported_filename)) if xbmcvfs.exists(exported_filename): xbmcvfs.delete(exported_filename) else: common.warn('Cannot delete {}, file does not exist', g.py2_decode(exported_filename)) # Remove the NFO files if exists nfo_file = os.path.splitext(g.py2_decode(exported_filename))[0] + '.nfo' if xbmcvfs.exists(nfo_file): xbmcvfs.delete(nfo_file) dirs, files = xbmcvfs.listdir(parent_folder) tvshow_nfo_file = xbmc.makeLegalFilename( '/'.join([g.py2_decode(parent_folder), 'tvshow.nfo'])) # Remove tvshow_nfo_file only when is the last file # (users have the option of removing even single seasons) if xbmcvfs.exists(tvshow_nfo_file) and not dirs and len(files) == 1: xbmcvfs.delete(tvshow_nfo_file) # Delete parent folder xbmcvfs.rmdir(parent_folder) # Delete parent folder when empty if not dirs and not files: xbmcvfs.rmdir(parent_folder) _remove_videoid_from_db(videoid) except ItemNotFound: common.warn('The video with id {} not exists in the database', videoid) except Exception as exc: import traceback common.error(traceback.format_exc()) ui.show_addon_error_info(exc)
def sync_parser(): dirs, files = xbmcvfs.listdir(parser_folder) if files: mensagemprogresso.create(translate(40000),translate(400020),"") mensagemprogresso.update(0,translate(400020),"") xbmc.sleep(1000) number_of_files = len(files) i = 0 for file in files: i += 1 error = False mensagemprogresso.update(int(float(i)/number_of_files*100),translate(400020),file.replace('.txt',''),translate(400021)) module_file = os.path.join(parser_folder,file) text = eval(readfile(module_file)) if not text: pass else: if 'url' and 'md5' in text.keys(): installed_md5 = text['md5'] module_url = text['url'] module_md5 = text['url'].replace('.tar.gz','.md5') try: current_md5 = get_page_source(module_md5) except: current_md5 = installed_md5; error = True if current_md5 != installed_md5: print('Module requires update ' + str(file.replace('.txt','')) + ' ' + str(installed_md5) + ' != ' + str(current_md5)) mensagemprogresso.update(int(float(i)/number_of_files*100),translate(400020),file.replace('.txt',''),translate(400025)) add_new_parser(module_url) mensagemprogresso.create(translate(40000),translate(400020),file.replace('.txt',''),translate(400022)) else: print('Module is up to date: ' + str(file.replace('.txt',''))) if error == False: message = translate(400023) else: message = translate(400024) mensagemprogresso.update(int(float(i)/number_of_files*100),translate(400020),file.replace('.txt',''),message) xbmc.sleep(1000) try: mensagemprogresso.update(100,"","") mensagemprogresso.close() except: pass settings.setSetting('parsers_last_sync',value=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")) return
def build_players(self, tmdbtype=None): basedirs = [ 'special://profile/addon_data/plugin.video.themoviedb.helper/players/' ] if self.addon.getSettingBool('bundled_players'): basedirs.append( 'special://home/addons/plugin.video.themoviedb.helper/resources/players/' ) for basedir in basedirs: files = [ x for x in xbmcvfs.listdir(basedir)[1] if x.endswith('.json') ] for file in files: meta = loads(utils.read_file(basedir + file)) or {} self.players[file] = meta plugins = meta.get( 'plugin' ) or 'plugin.undefined' # Give dummy name to undefined plugins so that they fail the check plugins = plugins if isinstance(plugins, list) else [ plugins ] # Listify for simplicity of code for plugin in plugins: if not xbmc.getCondVisibility( u'System.HasAddon({0})'.format(plugin)): break # System doesn't have a required plugin so skip this player else: # If the system has all the listed addons then build the player tmdbtype = tmdbtype or self.tmdbtype priority = utils.try_parse_int( meta.get('priority')) or 1000 if tmdbtype == 'movie' and meta.get('search_movie'): self.search_movie.append((file, priority)) if tmdbtype == 'movie' and meta.get('play_movie'): self.play_movie.append((file, priority)) if tmdbtype == 'tv' and meta.get('search_episode'): self.search_episode.append((file, priority)) if tmdbtype == 'tv' and meta.get('play_episode'): self.play_episode.append((file, priority))
def listdir(path, silent=False, vfs=True, file_inf=False): """ Lista un directorio @param path: Directorio a listar, debe ser un str "UTF-8" @type path: str @rtype: str @return: contenido de un directorio """ path = encode(path) try: if xbmc_vfs and vfs: dirs, files = xbmcvfs.listdir(path) res = sorted(dirs) + sorted(files) if file_inf: path = join(path, ' ').rstrip() ls_la = [] for file in res: file_ext = file_info(join(path, file)).replace(path, '') if file_ext: ls_la += [file_ext] else: ls_la += [ '%s%s %s %s %s %s %s %s' % ('#', '#', '#', '#', '#', '#', '#', file) ] res = ls_la return decode(res) elif path.lower().startswith("smb://"): return decode(samba.listdir(path)) else: return decode(os.listdir(path)) except: logger.error("ERROR al leer el directorio: %s" % path) if not silent: logger.error(traceback.format_exc()) return False
def get_previously_exported_items(): """Return a list of movie or tvshow VideoIds for items that were exported in the old storage format""" result = [] videoid_pattern = re.compile('video_id=(\\d+)') for folder in _lib_folders(FOLDER_MOVIES) + _lib_folders(FOLDER_TV): for filename in xbmcvfs.listdir(folder)[1]: filepath = g.py2_decode( makeLegalFilename('/'.join([folder, filename]))) if filepath.endswith('.strm'): common.debug('Trying to migrate {}', filepath) try: # Only get a VideoId from the first file in each folder. # For shows, all episodes will result in the same VideoId # and movies only contain one file result.append(_get_root_videoid(filepath, videoid_pattern)) except MetadataNotAvailable: common.warn('Metadata not available, item skipped') except (AttributeError, IndexError): common.warn('Item does not conform to old format') break return result
def list_favourites(): if not os.path.exists(datapath): xbmcvfs.mkdir(datapath) if not os.path.exists(programafav): xbmcvfs.mkdir(programafav) dirs, files = xbmcvfs.listdir(programafav) if files: totalit = len(files) for fich in files: text = readfile(os.path.join(programafav, fich)) data = text.split('|') try: information = {"Title": data[0], "plot": data[3]} if 'arquivo/' not in data[1]: mode = 16 else: mode = 11 addprograma(data[0], data[1], mode, data[2], totalit, information) except: pass xbmcplugin.setContent(int(sys.argv[1]), 'tvshows') setview('show-view') else: msgok(translate(30001), translate(30024)) sys.exit(0)
def index_of(path=None): items = [] folders, files = xbmcvfs.listdir(path) for folder in sorted(folders, key=lambda x: x.lower()): folder_path = "%s%s/" % (path, folder) thumbnail_file = "%sicon.txt" % folder_path thumbnail = xbmcvfs.File(thumbnail_file, "rb").read() context_items = [] context_items.append( ("[COLOR yellow][B]%s[/B][/COLOR] " % 'Remove', 'XBMC.RunPlugin(%s)' % (plugin.url_for(remove_folder, path=folder_path)))) context_items.append( ("[COLOR yellow][B]%s[/B][/COLOR] " % 'Rename', 'XBMC.RunPlugin(%s)' % (plugin.url_for(rename_folder, path=path, name=folder)))) context_items.append( ("[COLOR yellow][B]%s[/B][/COLOR] " % 'Change Image', 'XBMC.RunPlugin(%s)' % (plugin.url_for(change_folder_thumbnail, path=folder_path)))) items.append({ 'label': folder, 'path': plugin.url_for('index_of', path=folder_path), 'thumbnail': thumbnail, 'context_menu': context_items, }) items = items + sorted(favourites(path), key=lambda x: x["label"].lower()) items.append({ 'label': "Add", 'path': plugin.url_for('add', path=path), 'thumbnail': get_icon_path('settings'), }) view = plugin.get_setting('view.type') if view != "default": plugin.set_content(view) return items
def getFolderTrailers(path): trailers = [] folders = [] # multipath support if path.startswith('multipath://'): # get all paths from the multipath paths = path[12:-1].split('/') for item in paths: folders.append(urllib.unquote_plus(item)) else: folders.append(path) for folder in folders: if xbmcvfs.exists(xbmc.translatePath(folder)): # get all files and subfolders dirs,files = xbmcvfs.listdir(folder) for item in files: if not os.path.join(folder,item) in played: trailers.append(os.path.join(folder,item)) for item in dirs: # recursively scan all subfolders trailers += getFolderTrailers(os.path.join(folder,item)) return trailers
def addon_favourites(): if xbmcvfs.exists(os.path.join(pastaperfil, "Favourites")): dirs, files = xbmcvfs.listdir(os.path.join(pastaperfil, "Favourites")) if files: for file in files: string = readfile(os.path.join(pastaperfil, "Favourites", file)) match = string.split("|") try: iconimage = match[3] except: if 'acestream' in file: iconimage = addonpath + art + 'acelogofull.png' elif 'sop' in file: iconimage = addonpath + art + 'sopcast_logo.jpg' else: iconimage = '' addDir("[B][COLOR orange]" + match[0] + "[/B][/COLOR]", match[2], int(match[1]), iconimage, 1, False) addDir(translate(70022), MainURL, 203, addonpath + art + 'plus-menu.png', 2, False) xbmc.executebuiltin("Container.SetViewMode(51)")
def update_tvshows(self, force=False, **kwargs): nfos = [] # Get TMDb IDs from nfo files in folder nfos_append = nfos.append # For speed since we can't do a list comp easily here for f in xbmcvfs.listdir(BASEDIR_TV)[0]: tmdb_id = get_tmdb_id_nfo(BASEDIR_TV, f) nfos_append({'tmdb_id': tmdb_id, 'folder': f}) if tmdb_id else None # Update each show in folder nfos_total = len(nfos) for x, i in enumerate(nfos): self._update(x, nfos_total, message=u'{} {}...'.format( ADDON.getLocalizedString(32167), i['folder'])) self.add_tvshow(tmdb_id=i['tmdb_id'], force=force) # Update last updated stamp ADDON.setSettingString( 'last_autoupdate', 'Last updated {}'.format(get_current_date_time()))
def AddArtToLibrary(type, media, folder, limit, silent=False): json_query = xbmc.executeJSONRPC( '{"jsonrpc": "2.0", "method": "VideoLibrary.Get%ss", "params": {"properties": ["art", "file"], "sort": { "method": "label" } }, "id": 1}' % media.lower()) json_query = unicode(json_query, 'utf-8', errors='ignore') json_response = simplejson.loads(json_query) if (json_response['result'] is not None) and ('%ss' % (media.lower()) in json_response['result']): # iterate through the results if not silent: progressDialog = xbmcgui.DialogProgress(ADDON_LANGUAGE(32016)) progressDialog.create(ADDON_LANGUAGE(32016)) for count, item in enumerate(json_response['result']['%ss' % media.lower()]): if not silent: if progressDialog.iscanceled(): return path = os.path.join( media_path(item['file']).encode("utf-8"), folder) file_list = xbmcvfs.listdir(path)[1] for i, file in enumerate(file_list): if i + 1 > limit: break if not silent: progressDialog.update( (count * 100) / json_response['result']['limits']['total'], ADDON_LANGUAGE(32011) + ' %s: %s %i' % (item["label"], type, i + 1)) if progressDialog.iscanceled(): return file_path = os.path.join(path, file).encode('string-escape') if xbmcvfs.exists(file_path) and item['art'].get( '%s%i' % (type, i), '') == "": xbmc.executeJSONRPC( '{"jsonrpc": "2.0", "method": "VideoLibrary.Set%sDetails", "params": { "%sid": %i, "art": { "%s%i": "%s" }}, "id": 1 }' % (media, media.lower(), item.get( '%sid' % media.lower()), type, i + 1, file_path))
def addDir_livestreams_common(name, url, mode, iconimage, folder, fannart=None): u = sys.argv[0] + "?url=" + urllib.quote_plus(url) + "&mode=" + str( mode) + "&name=" + urllib.quote_plus(name) ok = True contextmen = [] liz = xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage) if fannart: liz.setProperty('fanart_image', fannart) else: liz.setProperty('fanart_image', "%s/fanart.jpg" % settings.getAddonInfo("path")) if mode == 1 or mode == 2: try: dirs, files = xbmcvfs.listdir( os.path.join(pastaperfil, "Favourites")) if url.replace(":", "").replace("/", "") + ".txt" in files: contextmen.append(( translate(40146), 'XBMC.RunPlugin(%s?mode=202&url=%s&name=%s&iconimage=%s)' % (sys.argv[0], urllib.quote_plus(url), name, iconimage))) else: contextmen.append(( translate(40143), 'XBMC.RunPlugin(%s?mode=201&url=%s&name=%s&iconimage=%s)' % (sys.argv[0], urllib.quote_plus(url), name, iconimage))) except: pass liz.addContextMenuItems(contextmen, replaceItems=False) ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=u, listitem=liz, isFolder=folder)
def remove_show(self, title): """Removes the DB entry & the strm files for the show given Parameters ---------- title : :obj:`str` Title of the show Returns ------- bool Delete successfull """ title = re.sub(r'[?|$|!|:|#]', r'', title) folder = re.sub( r'[?|$|!|:|#]', r'', self.db[self.series_label][title]['alt_title'].encode('utf-8')) progress = xbmcgui.DialogProgress() progress.create(kodi_helper.get_local_string(1210), title) time.sleep(0.5) del self.db[self.series_label][title] self._update_local_db(filename=self.db_filepath, db=self.db) show_dir = kodi_helper.check_folder_path( os.path.join(self.tvshow_path, folder)) if xbmcvfs.exists(show_dir): show_files = xbmcvfs.listdir(show_dir)[1] episode_count_total = len(show_files) step = round(100.0 / episode_count_total, 1) percent = 100 - step for filename in show_files: progress.update(int(percent)) xbmcvfs.delete(os.path.join(show_dir, filename)) percent = percent - step time.sleep(0.05) xbmcvfs.rmdir(show_dir) return True return False time.sleep(1) progress.close()
def _del_path(self, path): if xbmcvfs.exists(path): try: common.addon.log('Removing folder: %s' % path, 2) try: dirs, files = xbmcvfs.listdir(path) for file in files: xbmcvfs.delete(os.path.join(path, file)) success = xbmcvfs.rmdir(path) if success == 0: raise except Exception, e: try: common.addon.log('Failed to delete path using xbmcvfs: %s' % e, 4) common.addon.log('Attempting to remove with shutil: %s' % path, 2) shutil.rmtree(path) except: raise except Exception, e: common.addon.log('Failed to delete path: %s' % e, 4) return False
def download(id): try: rmtree(mySubFolder) except Exception as err: wlog('Caught Exception: error deleting folders: %s' % format(err)) pass mkdirs(mySubFolder) subtitle_list = [] exts = [".srt", ".sub", ".str"] archive_file = path.join(myTmp, 'wizdom.sub.' + id + '.zip') if not path.exists(archive_file): data = get("http://zip.%s/" % format(myDomain) + id + ".zip") open(archive_file, 'wb').write(data.content) executebuiltin('XBMC.Extract("%s","%s")' % (archive_file, mySubFolder), True) for file_ in listdir(mySubFolder)[1]: ufile = file_.decode('utf-8') file_ = path.join(mySubFolder, ufile) if path.splitext(ufile)[1] in exts: convert_to_utf(file_) subtitle_list.append(file_) return subtitle_list
def clean_oldbackups(self): '''auto clean old backups''' backuppath = self.addon.getSetting("backup_path").decode("utf-8") max_backups = self.addon.getSetting("max_old_backups") if max_backups: max_backups = int(max_backups) all_files = [] for filename in xbmcvfs.listdir(backuppath)[1]: if ".zip" in filename and "Skinbackup" in filename: filename = filename.decode("utf-8") filepath = backuppath + filename filestat = xbmcvfs.Stat(filepath) modified = filestat.st_mtime() del filestat log_msg(modified) all_files.append((filepath, modified)) if len(all_files) > max_backups: from operator import itemgetter old_files = sorted(all_files, key=itemgetter(1), reverse=True)[max_backups - 1:] for backupfile in old_files: xbmcvfs.delete(backupfile[0])
def unzip(path, dest, folder=None): ''' Unzip file. zipfile module seems to fail on android with badziperror. ''' path = urllib.quote_plus(path) root = "zip://" + path + '/' if folder: xbmcvfs.mkdir(os.path.join(dest, folder)) dest = os.path.join(dest, folder) root = get_zip_directory(root, folder) dirs, files = xbmcvfs.listdir(root) if dirs: unzip_recursive(root, dirs, dest) for file in files: unzip_file(os.path.join(root, file.decode('utf-8')), os.path.join(dest, file.decode('utf-8'))) LOG.info("Unzipped %s", path)
def remove_parser(iconimage): parser_plugin = iconimage.split('/') if len(parser_plugin) == 1: parser_plugin = iconimage.split("\\") parser_plugin = parser_plugin[-2] xbmcvfs.delete(os.path.join(parser_folder, parser_plugin + '.txt')) module_folder = os.path.join(parser_core_folder, parser_plugin) module_package_backup = os.path.join(parser_packages_folder, parser_plugin + '.tar.gz') dirs, files = xbmcvfs.listdir(module_folder) for file in files: xbmcvfs.delete(os.path.join(module_folder, file)) import shutil shutil.rmtree(module_folder) try: xbmcvfs.delete(module_package_backup) except: pass xbmc.executebuiltin( "Notification(%s,%s,%i,%s)" % (translate(40000), translate(400019), 1, addonpath + "/icon.png")) xbmc.executebuiltin("Container.Refresh")
def get_customfolder_path(self, customfolder, foldername, sublevel=False): """search recursively (max 2 levels) for a specific folder""" if sys.version_info.major == 3: artistcustom_path = self._mutils.addon.getSetting("music_art_custom_path") else: artistcustom_path = self._mutils.addon.getSetting("music_art_custom_path").decode("utf-8") cachestr = "customfolder_path.%s%s" % (customfolder, foldername) folder_path = self.cache.get(cachestr) if not folder_path: if "\\" in customfolder: delim = "\\" else: delim = "/" dirs = xbmcvfs.listdir(customfolder)[0] for strictness in [1, 0.95, 0.9, 0.85]: for directory in dirs: if sys.version_info.major < 3: directory = directory.decode("utf-8") curpath = os.path.join(customfolder, directory) + delim match = SM(None, foldername.lower(), directory.lower()).ratio() if match >= strictness: folder_path = curpath elif not sublevel: # check if our requested path is in a sublevel of the current path # restrict the number of sublevels to just one for now for performance reasons folder_path = self.get_customfolder_path(curpath, foldername, True) if folder_path: break if folder_path: break if not sublevel: if not folder_path and self._mutils.addon.getSetting("music_art_download_custom") == "true": # allow creation of folder if downloading is enabled folder_path = os.path.join(customfolder, foldername) + delim self.cache.set(cachestr, folder_path) if not folder_path and self._mutils.addon.getSetting("music_art_download_custom") == "true": folder_path = os.path.join(artistcustom_path, foldername) + delim return folder_path
def GetImages(path=""): PinString = "&markers=color:blue" letter = ord('A') count = 0 images_list = list() for filename in xbmcvfs.listdir(path)[-1]: try: img = Image.open(path + filename) exif_data = get_exif_data(img) lat, lon = get_lat_lon(exif_data) if "DateTimeOriginal" in exif_data: date = exif_data["DateTimeOriginal"] elif "DateTime" in exif_data: date = exif_data["DateTime"] else: date = "" if lat: prop_list = { "name": filename, "label": filename, "lat": str(lat), "lon": str(lon), "date": date, "description": date, "thumb": path + filename, "filepath": path + filename, "index": str(count), "sortletter": chr(letter), } if len(PinString) < 1850: PinString = PinString + "%7C" + str(lat) + "," + str(lon) letter += 1 images_list.append(prop_list) count += 1 except Exception as e: log("Error when handling GetImages results") log(e) return images_list, PinString
def remove_season(self, title, season): """Removes the DB entry & the strm files for a season of a show given Parameters ---------- title : :obj:`str` Title of the show season : :obj:`int` Season sequence number Returns ------- bool Delete successfull """ title = re.sub(r'[?|$|!|:|#]', r'', title.encode('utf-8')) season = int(season) season_list = [] episodes_list = [] show_meta = '%s' % (title) for season_entry in self.db[self.series_label][show_meta]['seasons']: if season_entry != season: season_list.append(season_entry) self.db[self.series_label][show_meta]['seasons'] = season_list alt_title = self.db[self.series_label][show_meta]['alt_title'] show_dir = self.nx_common.check_folder_path( path=os.path.join(self.tvshow_path, alt_title)) if xbmcvfs.exists(show_dir): show_files = [f for f in xbmcvfs.listdir(show_dir) if xbmcvfs.exists(os.path.join(show_dir, f))] for filename in show_files: if 'S%02dE' % (season) in filename: xbmcvfs.delete(os.path.join(show_dir, filename)) else: episodes_list.append(filename.replace('.strm', '')) self.db[self.series_label][show_meta]['episodes'] = episodes_list self._update_local_db(filename=self.db_filepath, db=self.db) return True
def download(sub_id, option_id, filename, stack=False): result = None subtitle_list = [] exts = [".srt", ".sub"] downloader = TorecSubtitlesDownloader() start_time = time.time() delete_old_subs() try: result = downloader.get_download_link(sub_id, option_id) except Exception as e: log(__name__,"failed to connect to service for subtitle download %s" % e) return subtitle_list if result is not None: log(__name__, "Downloading subtitles from '%s'" % result) (subtitle_data, subtitle_name) = downloader.download(result) (file_name, file_ext) = os.path.splitext(subtitle_name) archive_file = os.path.join(__temp__, "Torec%s" % file_ext) with open(archive_file, "wb") as subFile: subFile.write(subtitle_data) xbmc.executebuiltin( ('XBMC.Extract("%s","%s")' % (archive_file, __temp__,) ).encode('utf-8'), True) for file_ in xbmcvfs.listdir(__temp__)[1]: ufile = file_.decode('utf-8') log(__name__, "file=%s" % ufile) file_ = os.path.join(__temp__, ufile) if os.path.splitext(ufile)[1] in exts: convert_to_utf(file_) subtitle_list.append(file_) log(__name__, "Overall download took %f" % (time.time() - start_time)) return subtitle_list
def restoreColorTheme(): import shutil import zipfile zip_path = None userThemesPath = os.path.join(userThemesDir, "themes") + os.sep zip_path = get_browse_dialog(dlg_type=1, heading=ADDON.getLocalizedString(32020), mask=".zip") if zip_path and zip_path != "protocol://": #create temp path temp_path = xbmc.translatePath('special://temp/skinbackup/').decode( "utf-8") if xbmcvfs.exists(temp_path): shutil.rmtree(temp_path) xbmcvfs.mkdir(temp_path) #unzip to temp if "\\" in zip_path: delim = "\\" else: delim = "/" zip_temp = xbmc.translatePath( 'special://temp/' + zip_path.split(delim)[-1]).decode("utf-8") xbmcvfs.copy(zip_path, zip_temp) zfile = zipfile.ZipFile(zip_temp) zfile.extractall(temp_path) zfile.close() xbmcvfs.delete(zip_temp) dirs, files = xbmcvfs.listdir(temp_path) for file in files: if file.endswith(".theme") or file.endswith(".jpg"): sourcefile = os.path.join(temp_path, file) destfile = os.path.join(userThemesPath, file) xbmcvfs.copy(sourcefile, destfile) xbmcgui.Dialog().ok(ADDON.getLocalizedString(32022), ADDON.getLocalizedString(32021))
def openLibrary(self): oGui = cGui() oInputParameterHandler = cInputParameterHandler() sFile = oInputParameterHandler.getValue('filePath') listDir = xbmcvfs.listdir(sFile) if listDir[0]: data = listDir[0] else: data = listDir[1] addon_handle = None for i in data: path = VSPath(sFile + '/' + i) #Suppression du special: pour plus tard sTitle = os.path.basename(path) #Titre du fichier .strm if '.strm' in i: sHosterUrl = sFile + '/' + i addon_handle = int(sys.argv[1]) xbmcplugin.setContent(addon_handle, 'video') li = xbmcgui.ListItem(sTitle) xbmcplugin.addDirectoryItem(handle=addon_handle, url=sHosterUrl, listitem=li) else: oOutputParameterHandler = cOutputParameterHandler() oOutputParameterHandler.addParameter('filePath', sFile + '/' + i) oGui.addDir(SITE_IDENTIFIER, 'openLibrary', sTitle, 'annees.png', oOutputParameterHandler) if addon_handle: xbmcplugin.endOfDirectory(addon_handle) else: oGui.setEndOfDirectory()
def listdir(path, silent=False, vfs=True): """ Lista un directorio @param path: Directorio a listar, debe ser un str "UTF-8" @type path: str @rtype: str @return: contenido de un directorio """ path = encode(path) try: if xbmc_vfs and vfs: dirs, files = xbmcvfs.listdir(path) return dirs + files elif path.lower().startswith("smb://"): return decode(samba.listdir(path)) else: return decode(os.listdir(path)) except: logger.error("ERROR al leer el directorio: %s" % path) if not silent: logger.error(traceback.format_exc()) return False
def listdir(path, silent=False, vfs=True): """ List a directory @param path: Directory to list, must be a str "UTF-8" @type path: str @rtype: str @return: content of a directory """ path = encode(path) try: if xbmc_vfs and vfs: dirs, files = xbmcvfs.listdir(path) return dirs + files elif path.lower().startswith("smb://"): return decode(samba.listdir(path)) else: return decode(os.listdir(path)) except: logger.error("ERROR when reading the directory: %s" % path) if not silent: logger.error(traceback.format_exc()) return False
def remove_item(item_task, library_home=None): """Remove an item from the library and delete if from disk""" # pylint: disable=unused-argument, broad-except common.debug('Removing {} from library'.format(item_task['title'])) if not is_in_library(item_task['videoid']): common.warn('cannot remove {}, item not in library' .format(item_task['title'])) return id_path = item_task['videoid'].to_list() exported_filename = xbmc.translatePath( common.get_path(id_path, g.library())['file']).decode("utf-8") parent_folder = os.path.dirname(exported_filename) try: xbmcvfs.delete(xbmc.translatePath(exported_filename).decode("utf-8")) # Fix parent folder not removed dirs, files = xbmcvfs.listdir(xbmc.translatePath(parent_folder).decode("utf-8")) if not dirs and not files: # the destination folder is empty xbmcvfs.rmdir(xbmc.translatePath(parent_folder).decode("utf-8")) except Exception: common.debug('Cannot delete {}, file does not exist' .format(exported_filename)) common.remove_path(id_path, g.library(), lambda e: e.keys() == ['videoid']) g.save_library()
def _listdir(path): try: return xbmcvfs.listdir(path) except NameError: pass # Emulate xbmcvfs.listdir assert isinstance(path, str) assert path.endswith(b'/') assert os.path.isdir(path) dirs = [] files = [] path = path.rstrip(b'/') try: for name in os.listdir(path): if os.path.isdir(os.path.join(path, name)): dirs.append(name) else: files.append(name) except OSError: pass return dirs, files
def removeCacheFile(target, isDir=False): try: fullFilename = os_path_join(PROFILE_DIR, target) log("VideoExtrasCleanup: Checking cache file %s" % fullFilename) # If the file already exists, delete it if xbmcvfs.exists(fullFilename): if isDir: # Remove the png files in the directory first dirs, files = xbmcvfs.listdir(fullFilename) for aFile in files: m = re.search("[0-9]+[a-zA-Z_]*.png", aFile, re.IGNORECASE) if m: pngFile = os_path_join(fullFilename, aFile) xbmcvfs.delete(pngFile) # Now remove the actual directory xbmcvfs.rmdir(fullFilename) else: xbmcvfs.delete(fullFilename) except: log("CacheCleanup: %s" % traceback.format_exc(), xbmc.LOGERROR)
def getFanArt(self): baseDirectory = self.filePath if self.filePath.lower().endswith('.m4b'): # Check if there is a file just for this audiobook fullpathLocalImage, bookExt = os.path.splitext(self.filePath) fullpathLocalImage = "%s-fanart.jpg" % fullpathLocalImage if xbmcvfs.exists(fullpathLocalImage): log("AudioBookHandler: Found book fanart image %s" % fullpathLocalImage) return fullpathLocalImage # Get the name of the directory this file is in baseDirectory = (os_path_split(self.filePath))[0] # Now check if there is a default fanart file fanartImage = FANART subdirs, filesInDir = xbmcvfs.listdir(baseDirectory) for fileInDir in filesInDir: if fileInDir.lower() in ['fanart.jpg', 'fanart.png']: fanartImage = os_path_join(baseDirectory, fileInDir) break return fanartImage