我们从Python开源项目中,提取了以下34个代码示例,用于说明如何使用xbmcvfs.listdir()。
def get_own_pictures(path): _, files = xbmcvfs.listdir(xbmc.translatePath(path)) images_dict = {} image_file = os.path.join(xbmc.translatePath(path), "images.json") if xbmcvfs.exists(image_file): with open(image_file, "r") as f: try: images_dict = json.loads(f.read()) except ValueError: kodiutils.log(kodiutils.get_string(32010), xbmc.LOGERROR) for _file in files: if _file.endswith(('.png', '.jpg', '.jpeg')): returned_dict = { "url": os.path.join(xbmc.translatePath(path), _file), "private": True } if images_dict: for image in images_dict: if "image" in image.keys() and image["image"] == _file: if "line1" in image.keys(): returned_dict["line1"] = image["line1"] if "line2" in image.keys(): returned_dict["line2"] = image["line2"] yield returned_dict
def backup_theme(self, themename): '''backup a colortheme to a zipfile''' import zipfile backup_path = xbmcgui.Dialog().browse(3, self.addon.getLocalizedString(32029), "files").decode("utf-8") if backup_path: xbmc.executebuiltin("ActivateWindow(busydialog)") backup_name = u"%s ColorTheme - %s" % (get_skin_name().capitalize(), themename) backupfile = os.path.join(backup_path, backup_name + u".zip") zip_temp = u'special://temp/%s.zip' % backup_name xbmcvfs.delete(zip_temp) xbmcvfs.delete(backupfile) zip_temp = xbmc.translatePath(zip_temp).decode("utf-8") zip_file = zipfile.ZipFile(zip_temp, "w", zipfile.ZIP_DEFLATED) abs_src = os.path.abspath(xbmc.translatePath(self.userthemes_path).decode("utf-8")) for filename in xbmcvfs.listdir(self.userthemes_path)[1]: if (filename.startswith("%s_" % themename) or filename.replace(".theme", "").replace(".jpg", "") == themename): filename = filename.decode("utf-8") filepath = xbmc.translatePath(self.userthemes_path + filename).decode("utf-8") absname = os.path.abspath(filepath) arcname = absname[len(abs_src) + 1:] zip_file.write(absname, arcname) zip_file.close() xbmcvfs.copy(zip_temp, backupfile) xbmc.executebuiltin("Dialog.Close(busydialog)")
def get_user_colorthemes(self): '''get all user stored color themes as listitems''' listitems = [] for file in xbmcvfs.listdir(self.userthemes_path)[1]: if file.endswith(".theme"): file = file.decode("utf-8") themefile = self.userthemes_path + file label = file.replace(".theme", "") icon = themefile.replace(".theme", ".jpg") if not xbmcvfs.exists(icon): icon = "" desc = "user defined theme" if label == self.get_activetheme(): desc = xbmc.getLocalizedString(461) listitem = xbmcgui.ListItem(label, iconImage=icon) listitem.setLabel2(desc) listitem.setPath(themefile) listitems.append(listitem) return listitems
def restore_colortheme(self): '''restore zipbackup of colortheme to colorthemes folder''' zip_path = xbmcgui.Dialog().browse(1, self.addon.getLocalizedString(32030), "files", ".zip") if zip_path and zip_path.endswith(".zip"): # create temp path temp_path = u'special://temp/skinbackup/' temp_zip = u"special://temp/colortheme.zip" if xbmcvfs.exists(temp_path): recursive_delete_dir(temp_path) xbmcvfs.mkdir(temp_path) # unzip to temp xbmcvfs.copy(zip_path, temp_zip) unzip_fromfile(temp_zip, temp_path) for filename in xbmcvfs.listdir(temp_path)[1]: filename = filename.decode("utf-8") sourcefile = os.path.join(temp_path, filename) destfile = os.path.join(self.userthemes_path, filename) xbmcvfs.copy(sourcefile, destfile) # cleanup temp xbmcvfs.delete(temp_zip) recursive_delete_dir(temp_path) xbmcgui.Dialog().ok(self.addon.getLocalizedString(32026), self.addon.getLocalizedString(32027))
def backup_skinsettings(self, dest_file, filters, temp_path): '''backup the skinsettings (guisettings)''' # save guisettings skinfile = xbmcvfs.File(dest_file, "w") skinsettings = self.get_skinsettings(filters) skinfile.write(repr(skinsettings)) skinfile.close() # copy any custom skin images or themes for item in ["custom_images/", "themes/"]: custom_images_folder = u"special://profile/addon_data/%s/%s" % (xbmc.getSkinDir(), item) if xbmcvfs.exists(custom_images_folder): custom_images_folder_temp = os.path.join(temp_path, item) for file in xbmcvfs.listdir(custom_images_folder)[1]: source = os.path.join(custom_images_folder, file) dest = os.path.join(custom_images_folder_temp, file) copy_file(source, dest)
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: delete_file(backupfile[0])
def getSRT(self, service): #load cachePath if not already loaded # if self.cachePath == '': # self.cachePath = service.settings.cachePath # # if self.cachePath != '': # # dirs, files = xbmcvfs.listdir(str(self.cachePath) + '/'+ str(self.package.file.id) + '/') # for file in files: # if str(os.path.splitext(file)[1]).lower() in ('.srt', '.sub', '.ass', '.ssa') or str(os.path.splitext(file)[1]).lower() in ('srt', 'sub', 'ass', 'ssa'): # self.srt.append(str(self.cachePath) + '/'+ str(self.package.file.id) + '/' + file) return self.srt ## # set the thumbnail ##
def list_exported_media(self): """Return List of exported movies Returns ------- obj:`dict` Contents of export folder """ movies = (['', '']) shows = (['', '']) movie_path = self.movie_path tvshow_path = self.tvshow_path if xbmcvfs.exists(self.kodi_helper.check_folder_path(movie_path)): movies = xbmcvfs.listdir(movie_path) if xbmcvfs.exists(self.kodi_helper.check_folder_path(tvshow_path)): shows = xbmcvfs.listdir(tvshow_path) return movies + shows
def _del_path(self, path): common.addon.log('Attempting to remove folder: %s' % path, 0) if xbmcvfs.exists(path): try: common.addon.log('Removing folder: %s' % path, 0) 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, 0) shutil.rmtree(path) except: raise except Exception, e: common.addon.log('Failed to delete path: %s' % e, 4) return False else: common.addon.log('Folder does not exist: %s' % path)
def lookup_albumart_in_folder(folderpath): '''lookup artwork in given folder''' artwork = {} if not folderpath or not xbmcvfs.exists(folderpath): return artwork files = xbmcvfs.listdir(folderpath)[1] for item in files: item = item.decode("utf-8") if item in ["cdart.png", "disc.png"]: artwork["discart"] = folderpath + item if item == "thumbback.jpg": artwork["thumbback"] = folderpath + item if item == "spine.jpg": artwork["spine"] = folderpath + item elif item == "folder.jpg": artwork["thumb"] = folderpath + item return artwork
def get_custom_album_path(self, custom_path, artist, album, disc): '''try to locate the custom path for the album''' artist_path = self.get_customfolder_path(custom_path, artist) album_path = "" if artist_path: album_path = self.get_customfolder_path(artist_path, album) if album_path and disc: if "\\" in album_path: delim = "\\" else: delim = "/" dirs = xbmcvfs.listdir(album_path)[0] for directory in dirs: directory = directory.decode("utf-8") if disc in directory: return os.path.join(album_path, directory) + delim return album_path
def list_files_in_path(filespath): '''used for easy matching of studio logos''' all_files = {} dirs, files = xbmcvfs.listdir(filespath) if "/" in filespath: sep = "/" else: sep = "\\" for file in files: file = try_decode(file) name = file.split(".png")[0].lower() all_files[name] = filespath + file for directory in dirs: directory = try_decode(directory) files = xbmcvfs.listdir(os.path.join(filespath, directory) + sep)[1] for file in files: file = try_decode(file) name = directory + "/" + file.split(".png")[0].lower() all_files[name] = filespath + directory + sep + file # return the list return all_files
def _get_folder_images(self, path): self.log('_get_folder_images started with path: %s' % repr(path)) _, files = xbmcvfs.listdir(path) images = [ xbmc.validatePath(path + f) for f in files if f.lower()[-3:] in ('jpg', 'png') ] #if addon.getSetting('recursive') == 'true': # for directory in dirs: # if directory.startswith('.'): # continue # images.extend( # self._get_folder_images( # xbmc.validatePath('/'.join((path, directory, ''))) # ) # ) self.log('_get_folder_images ends') return images
def scanFolder(self, path): #Scan set folder for images with png and jpg extension self.log('scanFolder started with path: %s' % repr(path)) dirs, files = xbmcvfs.listdir(path) images = [ xbmc.validatePath(path + f) for f in files if f.lower()[-3:] in ('jpg', 'png') ] if addon.getSetting('recursive') == 'true': for directory in dirs: if directory.startswith('.'): continue images.extend( self.scanFolder( xbmc.validatePath('/'.join((path, directory, ''))) ) ) self.log('scanFolder ends') return images
def get_skin_colorthemes(self): '''returns all available skinprovided colorthemes as listitems''' listitems = [] for file in xbmcvfs.listdir(self.skinthemes_path)[1]: if file.endswith(".theme"): file = file.decode("utf-8") themefile = self.skinthemes_path + file icon = themefile.replace(".theme", ".jpg") if not xbmcvfs.exists(icon): icon = "" xbmcfile = xbmcvfs.File(themefile) data = xbmcfile.read() xbmcfile.close() for skinsetting in eval(data): if skinsetting[0] == "DESCRIPTION": desc = skinsetting[1] if skinsetting[0] == "THEMENAME": label = skinsetting[1] if label == self.get_activetheme(): desc = xbmc.getLocalizedString(461) listitem = xbmcgui.ListItem(label, iconImage=icon) listitem.setLabel2(desc) listitem.setPath(themefile) listitems.append(listitem) return listitems
def backup_skinshortcuts(self, dest_path): '''backup skinshortcuts including images''' source_path = u'special://profile/addon_data/script.skinshortcuts/' if not xbmcvfs.exists(dest_path): xbmcvfs.mkdir(dest_path) for file in xbmcvfs.listdir(source_path)[1]: file = file.decode("utf-8") sourcefile = source_path + file destfile = dest_path + file if xbmc.getCondVisibility("SubString(Skin.String(skinshortcuts-sharedmenu),false)"): # User is not sharing menu, so strip the skin name out of the destination file destfile = destfile.replace("%s." % (xbmc.getSkinDir()), "") if (file.endswith(".DATA.xml") and (not xbmc.getCondVisibility( "SubString(Skin.String(skinshortcuts-sharedmenu),false)") or file.startswith(xbmc.getSkinDir()))): xbmcvfs.copy(sourcefile, destfile) # parse shortcuts file and look for any images - if found copy them to addon folder self.backup_skinshortcuts_images(destfile, dest_path) elif file.endswith(".properties") and xbmc.getSkinDir() in file: if xbmc.getSkinDir() in file: destfile = dest_path + file.replace(xbmc.getSkinDir(), "SKINPROPERTIES") copy_file(sourcefile, destfile) self.backup_skinshortcuts_properties(destfile, dest_path) else: # just copy the remaining files copy_file(sourcefile, destfile)
def restore_skinshortcuts(temp_path): '''restore skinshortcuts files''' source_path = temp_path + u"skinshortcuts/" if xbmcvfs.exists(source_path): dest_path = u'special://profile/addon_data/script.skinshortcuts/' for filename in xbmcvfs.listdir(source_path)[1]: filename = filename.decode("utf-8") sourcefile = source_path + filename destfile = dest_path + filename if filename == "SKINPROPERTIES.properties": destfile = dest_path + filename.replace("SKINPROPERTIES", xbmc.getSkinDir()) elif xbmc.getCondVisibility("SubString(Skin.String(skinshortcuts-sharedmenu),false)"): destfile = "%s-" % (xbmc.getSkinDir()) copy_file(sourcefile, destfile)
def recursive_delete_dir(fullpath): '''helper to recursively delete a directory''' success = True if not isinstance(fullpath, unicode): fullpath = fullpath.decode("utf-8") dirs, files = xbmcvfs.listdir(fullpath) for file in files: file = file.decode("utf-8") success = xbmcvfs.delete(os.path.join(fullpath, file)) for directory in dirs: directory = directory.decode("utf-8") success = recursive_delete_dir(os.path.join(fullpath, directory)) success = xbmcvfs.rmdir(fullpath) return success
def getOfflineFileList(self,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 ## # Add a media file to a directory listing screen # parameters: package, context type, whether file is encfs, encfs:decryption path, encfs:encryption path ##
def getFiles(self,service): if not constants.CONST.CACHE: return None #load cachePath if not already loaded if self.cachePath == '': self.cachePath = service.settings.cachePath localResolutions = [] localFiles = [] # no local cache, no local files to look for if self.cachePath == '': return (localResolutions,localFiles) cachePath = str(self.cachePath) + '/' + str(self.package.file.id) + '/' #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 file in files: if '.stream.mp4' in file: try: resolutionFile = xbmcvfs.File(cachePath + str(os.path.splitext(file)[0]) + '.resolution') resolution = resolutionFile.read() resolutionFile.close() except: resolution = file localResolutions.append('offline - ' + str(resolution)) localFiles.append(str(cachePath) + str(file)) return (localResolutions,localFiles)
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.kodi_helper.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 get_exported_movie_year(self, title): """Return year of given exported movie Returns ------- obj:`int` year of given movie """ year = '0000' folder = self.kodi_helper.check_folder_path( path=os.path.join(self.movie_path, title)) if xbmcvfs.exists(folder): file = xbmcvfs.listdir(folder) year = str(file[1]).split('(', 1)[1].split(')', 1)[0] return int(year)
def lookup_artistart_in_folder(folderpath): '''lookup artwork in given folder''' artwork = {} if not folderpath or not xbmcvfs.exists(folderpath): return artwork files = xbmcvfs.listdir(folderpath)[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] artwork[key] = folderpath + item elif item == "logo.png": artwork["clearlogo"] = folderpath + item elif item == "folder.jpg": artwork["thumb"] = folderpath + item # extrafanarts efa_path = folderpath + "extrafanart/" if xbmcvfs.exists(efa_path): files = xbmcvfs.listdir(efa_path)[1] artwork["fanarts"] = [] if files: artwork["extrafanart"] = efa_path for item in files: item = efa_path + item.decode("utf-8") artwork["fanarts"].append(item) return artwork
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.85]: 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: 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) return folder_path
def get_extraposter(file_path): '''get extraposter path on disk based on media path''' result = {} efa_path = "" if "plugin.video.emby" in file_path: # workaround for emby addon efa_path = u"plugin://plugin.video.emby/extraposter?path=" + file_path elif "plugin://" in file_path: efa_path = "" elif "videodb://" in file_path: efa_path = "" else: count = 0 while not count == 3: # lookup extraposter folder by navigating up the tree file_path = os.path.dirname(file_path) try_path = file_path + u"/extraposter/" if xbmcvfs.exists(try_path): efa_path = try_path break count += 1 if efa_path: result["art"] = {"extraposter": efa_path} for count, file in enumerate(xbmcvfs.listdir(efa_path)[1]): if file.lower().endswith(".jpg"): result["art"]["ExtraPoster.%s" % count] = efa_path + file.decode("utf-8") return result
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.jpg", "disc.png", "characterart.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 get_extrafanart(file_path): '''get extrafanart path on disk based on media path''' result = {} efa_path = "" if "plugin.video.emby" in file_path: # workaround for emby addon efa_path = u"plugin://plugin.video.emby/extrafanart?path=" + file_path elif "plugin://" in file_path: efa_path = "" elif "videodb://" in file_path: efa_path = "" else: count = 0 while not count == 3: # lookup extrafanart folder by navigating up the tree file_path = os.path.dirname(file_path) try_path = file_path + u"/extrafanart/" if xbmcvfs.exists(try_path): efa_path = try_path break count += 1 if efa_path: result["art"] = {"extrafanart": efa_path} for count, file in enumerate(xbmcvfs.listdir(efa_path)[1]): if file.lower().endswith(".jpg"): result["art"]["ExtraFanArt.%s" % count] = efa_path + file.decode("utf-8") return result
def deleteDir(dir): if xbmcvfs.exists(dir): files=xbmcvfs.listdir(dir) if len(files)==2: xbmcvfs.rmdir(dir)
def dltMovie(id, path, video): kodiJsonRequest({'jsonrpc': '2.0', 'method': 'VideoLibrary.RemoveMovie', 'params': {'movieid': int(id)}, 'id': 1}) if separate_movies == "true": xdir, xfil = xbmcvfs.listdir(path) for fl in xfil: xbmcvfs.delete(path + fl) deleteDir(path) else: deleteVideo(path, video) xbmc.executebuiltin('Notification(' + xbmc.getInfoLabel('ListItem.Label').replace(",",";") + ',' + lang(30002) + ')')
def getFiles(self): logfiles = [] logfiles.append(['log', LOGFILE]) if self.oldlog: if xbmcvfs.exists(OLDLOG): logfiles.append(['oldlog', OLDLOG]) else: self.showResult(LANGUAGE(32021)) if self.crashlog: crashlog_path = '' items = [] if xbmc.getCondVisibility('system.platform.osx'): crashlog_path = os.path.join(os.path.expanduser('~'), 'Library/Logs/DiagnosticReports/') filematch = 'Kodi' elif xbmc.getCondVisibility('system.platform.ios'): crashlog_path = '/var/mobile/Library/Logs/CrashReporter/' filematch = 'Kodi' elif xbmc.getCondVisibility('system.platform.linux'): crashlog_path = os.path.expanduser('~') # not 100% accurate (crashlogs can be created in the dir kodi was started from as well) filematch = 'kodi_crashlog' elif xbmc.getCondVisibility('system.platform.windows'): self.showResult(LANGUAGE(32023)) elif xbmc.getCondVisibility('system.platform.android'): self.showResult(LANGUAGE(32024)) if crashlog_path and os.path.isdir(crashlog_path): lastcrash = None dirs, files = xbmcvfs.listdir(crashlog_path) for item in files: if filematch in item and os.path.isfile(os.path.join(crashlog_path, item)): items.append(os.path.join(crashlog_path, item)) items.sort(key=lambda f: os.path.getmtime(f)) lastcrash = items[-1] if lastcrash: logfiles.append(['crashlog', lastcrash]) if len(items) == 0: self.showResult(LANGUAGE(32022)) return logfiles
def getLocalChannelLogo(channel_name): logo_path = xbmcaddon.Addon().getSetting('logoPath') if not logo_path == '' and xbmcvfs.exists(logo_path): dirs, files = xbmcvfs.listdir(logo_path) for f in files: if f.lower().endswith('.png'): if channel_name.lower().replace(' ', '') == os.path.basename(f).lower().replace('.png', '').replace(' ', ''): return os.path.join(logo_path, f) return None
def restore(self, filename="", silent=False): '''restore skin settings from file''' if not filename: filename = self.get_restorefilename() progressdialog = None if not silent: progressdialog = xbmcgui.DialogProgress(self.addon.getLocalizedString(32006)) progressdialog.create(self.addon.getLocalizedString(32007)) if filename and xbmcvfs.exists(filename): # create temp path temp_path = self.create_temp() if not filename.endswith("zip"): # assume that passed filename is actually a skinsettings file skinsettingsfile = filename else: # copy zip to temp directory and unzip skinsettingsfile = temp_path + "guisettings.txt" if progressdialog: progressdialog.update(0, "unpacking backup...") zip_temp = u'%sskinbackup-%s.zip' % (ADDON_DATA, datetime.now().strftime('%Y-%m-%d-%H-%M')) copy_file(filename, zip_temp, True) unzip_fromfile(zip_temp, temp_path) delete_file(zip_temp) # copy skinshortcuts preferences self.restore_skinshortcuts(temp_path) # restore any custom skin images or themes for directory in ["custom_images/", "themes/"]: custom_images_folder = u"special://profile/addon_data/%s/%s" % (xbmc.getSkinDir(), directory) custom_images_folder_temp = temp_path + directory if xbmcvfs.exists(custom_images_folder_temp): for file in xbmcvfs.listdir(custom_images_folder_temp)[1]: xbmcvfs.copy(custom_images_folder_temp + file, custom_images_folder + file) # restore guisettings if xbmcvfs.exists(skinsettingsfile): self.restore_guisettings(skinsettingsfile, progressdialog) # cleanup temp recursive_delete_dir(temp_path) progressdialog.close() if not silent: xbmcgui.Dialog().ok(self.addon.getLocalizedString(32006), self.addon.getLocalizedString(32009))
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) label = self.series_label rep_str = self.db[label][title]['alt_title'].encode('utf-8') folder = re.sub( pattern=r'[?|$|!|:|#]', repl=r'', string=rep_str) progress = xbmcgui.DialogProgress() progress.create(self.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 = self.kodi_helper.check_folder_path( 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 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.kodi_helper.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.kodi_helper.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