我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用xbmcvfs.exists()。
def get_images(self, override=False): # Read google images from json file self.images = [] if kodiutils.get_setting_as_int("screensaver-mode") == 0 or kodiutils.get_setting_as_int("screensaver-mode") == 2 or override: with open(IMAGE_FILE, "r") as f: images = f.read() self.images = json.loads(images) # Check if we have images to append if kodiutils.get_setting_as_int("screensaver-mode") == 1 or kodiutils.get_setting_as_int("screensaver-mode") == 2 and not override: if kodiutils.get_setting("my-pictures-folder") and xbmcvfs.exists(xbmc.translatePath(kodiutils.get_setting("my-pictures-folder"))): for image in screensaverutils.get_own_pictures(kodiutils.get_setting("my-pictures-folder")): self.images.append(image) else: return self.get_images(override=True) shuffle(self.images) return
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 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 backup_skinshortcuts_properties(propertiesfile, dest_path): '''parse skinshortcuts properties file and translate images''' # look for any backgrounds and translate them propfile = xbmcvfs.File(propertiesfile) data = propfile.read() propfile.close() allprops = eval(data) if data else [] for count, prop in enumerate(allprops): if prop[2] == "background": background = prop[3] if prop[3] else "" defaultid = prop[1] if background.endswith(".jpg") or background.endswith(".png") or background.endswith(".gif"): background = get_clean_image(background) extension = background.split(".")[-1] newthumb = os.path.join(dest_path, "%s-background-%s.%s" % (xbmc.getSkinDir(), normalize_string(defaultid), extension)) newthumb_vfs = "special://profile/addon_data/script.skinshortcuts/%s-background-%s.%s" % ( xbmc.getSkinDir(), normalize_string(defaultid), extension) if xbmcvfs.exists(background): copy_file(background, newthumb) allprops[count] = [prop[0], prop[1], prop[2], newthumb_vfs] # write updated properties file propfile = xbmcvfs.File(propertiesfile, "w") propfile.write(repr(allprops)) propfile.close()
def getThumbnail(self,service, url='', fileID=''): # user isn't caching thumbnails if not constants.CONST.CACHE or not service.settings.cacheThumbnails or self.cachePath == '': if url != '': return url + '|' + service.getHeadersEncoded() elif self.package != None and self.package.file != None: return self.package.file.thumbnail + '|' + service.getHeadersEncoded() else: return '' if fileID == '': if xbmcvfs.exists(str(self.cachePath) + str(self.package.file.id) + '/' + str(self.package.file.id) + '.jpg'): return str(self.cachePath) + str(self.package.file.id) + '/' + str(self.package.file.id) + '.jpg' else: return self.package.file.thumbnail + '|' + service.getHeadersEncoded() else: if xbmcvfs.exists(str(self.cachePath) + str(fileID) + '/' + str(fileID) + '.jpg'): return str(self.cachePath) + str(fileID) + '/' + str(fileID) + '.jpg' else: return url + '|' + service.getHeadersEncoded() ## # get a list of offline files for this file ##
def write_metadata_file(self, video_id, content): """Writes the metadata file that caches grabbed content from netflix Parameters ---------- video_id : :obj:`str` ID of video content : Unchanged metadata from netflix """ meta_file = os.path.join(self.metadata_path, video_id+'.meta') if not xbmcvfs.exists(meta_file): f = xbmcvfs.File(meta_file, 'wb') pickle.dump(content, f) f.close()
def read_metadata_file(self, video_id): """Reads the metadata file that caches grabbed content from netflix Parameters ---------- video_id : :obj:`str` ID of video content : Unchanged metadata from cache file """ meta_file = os.path.join(self.metadata_path, str(video_id)+'.meta') if xbmcvfs.exists(meta_file): f = xbmcvfs.File(meta_file, 'rb') content = f.read() f.close() meta_data = pickle.loads(content) return meta_data return
def write_artdata_file(self, video_id, content): """Writes the art data file that caches grabbed content from netflix Parameters ---------- video_id : :obj:`str` ID of video content : Unchanged artdata from netflix """ meta_file = os.path.join(self.metadata_path, video_id+'.art') if not xbmcvfs.exists(meta_file): f = xbmcvfs.File(meta_file, 'wb') pickle.dump(content, f) f.close()
def movie_exists(self, title, year): """Checks if a movie is already present in the local DB Parameters ---------- title : :obj:`str` Title of the movie year : :obj:`int` Release year of the movie Returns ------- bool Movie exists in DB """ title = re.sub(r'[?|$|!|:|#]', r'', title) movie_meta = '%s (%d)' % (title, year) return movie_meta in self.db[self.movies_label]
def show_exists(self, title): """Checks if a show is present in the local DB Parameters ---------- title : :obj:`str` Title of the show Returns ------- bool Show exists in DB """ title = re.sub(r'[?|$|!|:|#]', r'', title) show_meta = '%s' % (title) return show_meta in self.db[self.series_label]
def season_exists(self, title, season): """Checks if a season is present in the local DB Parameters ---------- title : :obj:`str` Title of the show season : :obj:`int` Season sequence number Returns ------- bool Season of show exists in DB """ title = re.sub(r'[?|$|!|:|#]', r'', title) if self.show_exists(title) is False: return False show_entry = self.db[self.series_label][title] return season in show_entry['seasons']
def episode_exists(self, title, season, episode): """Checks if an episode if a show is present in the local DB Parameters ---------- title : :obj:`str` Title of the show season : :obj:`int` Season sequence number episode : :obj:`int` Episode sequence number Returns ------- bool Episode of show exists in DB """ title = re.sub(r'[?|$|!|:|#]', r'', title) if self.show_exists(title) is False: return False show_entry = self.db[self.series_label][title] episode_entry = 'S%02dE%02d' % (season, episode) return episode_entry in show_entry['episodes']
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 get_previewimage(self, title): """Load thumb image which is shown in exported Parameters ---------- title : :obj:`str` Filename based on title url : :obj:`str` Image url Returns ------- obj:`int` image of given title if exists """ title = re.sub(r'[?|$|!|:|#]', r'', title) imgfile = title + '.jpg' file = os.path.join(self.imagecache_path, imgfile) if xbmcvfs.exists(file): return file return self.kodi_helper.default_fanart
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 __init__(self,force=False): self.conn = None self.eventQueue = list() self.event = threading.Event() self.eventResults = dict() self.loadOptional(force) self.source = instantiateSource(force) self.updateInProgress = False self.updateFailed = False self.settingsChanged = None self.alreadyTriedUnlinking = False self.channelList = list() self.category = "Any" profilePath = xbmc.translatePath(ADDON.getAddonInfo('profile')) if not os.path.exists(profilePath): os.makedirs(profilePath) self.databasePath = os.path.join(profilePath, Database.SOURCE_DB) threading.Thread(name='Database Event Loop', target=self.eventLoop).start()
def getDataFromExternal(self, date, ch_list, progress_callback=None): if not xbmcvfs.exists(self.xmltvFile): raise SourceNotConfiguredException() if (ADDON.getSetting('xmltv2.enabled') == 'true') and xbmcvfs.exists(self.xmltv2File): if ADDON.getSetting('fixtures') == 'true': fixtures = FixturesSource(ADDON) for v in chain(self.getDataFromExternal2(self.xmltvFile, date, ch_list, progress_callback), self.getDataFromExternal2(self.xmltv2File, date, ch_list, progress_callback), fixtures.getDataFromExternal(date, ch_list, progress_callback)): yield v else: for v in chain(self.getDataFromExternal2(self.xmltvFile, date, ch_list, progress_callback), self.getDataFromExternal2(self.xmltv2File, date, ch_list, progress_callback)): yield v else: if ADDON.getSetting('fixtures') == 'true': fixtures = FixturesSource(ADDON) for v in chain(self.getDataFromExternal2(self.xmltvFile, date, ch_list, progress_callback), fixtures.getDataFromExternal(date, ch_list, progress_callback)): yield v else: for v in chain(self.getDataFromExternal2(self.xmltvFile, date, ch_list, progress_callback)): yield v
def __init__(self, addon, force): self.needReset = False self.fetchError = False self.start = True self.force = force ''' self.xmltvInterval = int(addon.getSetting('sd.interval')) self.logoSource = int(addon.getSetting('logos.source')) self.addonsType = int(addon.getSetting('addons.ini.type')) # make sure the folder in the user's profile exists or create it! if not os.path.exists(self.PLUGIN_DATA): os.makedirs(self.PLUGIN_DATA) # make sure the ini file is fetched as well if necessary if self.addonsType != self.INI_TYPE_DEFAULT: customFile = str(addon.getSetting('addons.ini.file')) if os.path.exists(customFile): # uses local file provided by user! xbmc.log('[%s] Use local file: %s' % (ADDON.getAddonInfo('id'), customFile), xbmc.LOGDEBUG) else: # Probably a remote file xbmc.log('[%s] Use remote file: %s' % (ADDON.getAddonInfo('id'), customFile), xbmc.LOGDEBUG) self.updateLocalFile(customFile, addon, True, force=force) '''
def download(link, filename): sub_file = [] if xbmcvfs.exists(__tempfolder__): shutil.rmtree(__tempfolder__) xbmcvfs.mkdirs(__tempfolder__) file = os.path.join(__tempfolder__, filename.decode('utf8')) dfile = get_sub(link) file_handler = open(file, "wb") file_handler.write(dfile.encode('UTF-8')) file_handler.close sub_file.append(file) return sub_file
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 process_image(image_url, art_type, imdb_id): '''animated gifs need to be stored locally, otherwise they won't work''' # make sure that our local path for the gif images exists addon = xbmcaddon.Addon(ADDON_ID) gifs_path = "%sanimatedgifs/" % addon.getAddonInfo('profile') del addon if not xbmcvfs.exists(gifs_path): xbmcvfs.mkdirs(gifs_path) # only process existing images if not image_url or not xbmcvfs.exists(image_url): return None # copy the image to our local path and return the new path as value local_filename = "%s%s_%s.gif" % (gifs_path, imdb_id, art_type) if xbmcvfs.exists(local_filename): xbmcvfs.delete(local_filename) # we don't use xbmcvfs.copy because we want to wait for the action to complete img = xbmcvfs.File(image_url) img_data = img.readBytes() img.close() img = xbmcvfs.File(local_filename, 'w') img.write(img_data) img.close() return local_filename
def download_image(filename, url): '''download specific image to local folder''' if not url: return url refresh_needed = False if xbmcvfs.exists(filename) and filename == url: # only overwrite if new image is different return filename else: if xbmcvfs.exists(filename): xbmcvfs.delete(filename) refresh_needed = True if xbmcvfs.copy(url, filename): if refresh_needed: refresh_image(filename) return filename return url
def album_info(self, album_id): '''get album metadata by musicbrainz id''' details = {"art": {}} params = {'method': 'album.getInfo', 'mbid': album_id} data = self.get_data(params) if data and data.get("album"): if isinstance(data["album"], list): lfmdetails = data["album"][0] else: lfmdetails = data["album"] if lfmdetails.get("image"): for image in lfmdetails["image"]: if image["size"] in ["mega", "extralarge"] and xbmcvfs.exists(image["#text"]): details["art"]["thumbs"] = [image["#text"]] details["art"]["thumb"] = image["#text"] if lfmdetails.get("listeners"): details["lastfm.listeners"] = lfmdetails["listeners"] if lfmdetails.get("playcount"): details["lastfm.playcount"] = lfmdetails["playcount"] if lfmdetails.get("tags") and lfmdetails["tags"].get("tag"): details["lastfm.tags"] = [tag["name"] for tag in lfmdetails["tags"]["tag"]] if lfmdetails.get("wiki"): details["plot"] = strip_newlines(lfmdetails["wiki"].get("content", "").split(' <a')[0])
def search_kodi(self, searchphrase): '''search kodi json api for channel logo''' result = "" if xbmc.getCondVisibility("PVR.HasTVChannels"): results = self.kodidb.get_json( 'PVR.GetChannels', fields=["thumbnail"], returntype="tvchannels", optparam=( "channelgroupid", "alltv")) for item in results: if item["label"] == searchphrase: channelicon = get_clean_image(item['thumbnail']) if channelicon and xbmcvfs.exists(channelicon): result = channelicon break return result
def read_from_file(path="", raw=False): if path == "": return False if not xbmcvfs.exists(path): return False try: with open(path) as f: logger.info("opened textfile %s." % (path)) if not raw: result = json.load(f) else: result = f.read() return result except: logger.info("failed to load textfile: " + path) return False
def playTrack(asin): content = trackPostUnicodeGetHLSPage('https://music.amazon.de/dmls/', asin) temp_file_path = addonUserDataFolder if forceDVDPlayer: temp_file_path += "/temp.mp4" else: temp_file_path += "/temp.m3u8" if xbmcvfs.exists(temp_file_path): xbmcvfs.delete(temp_file_path) m3u_temp_file = xbmcvfs.File(temp_file_path, 'w') manifest_match = re.compile('manifest":"(.+?)"',re.DOTALL).findall(content) if manifest_match: m3u_string = manifest_match[0] m3u_string = m3u_string.replace("\\n", os.linesep) m3u_temp_file.write(m3u_string.encode("ascii")) m3u_temp_file.close() play_item = xbmcgui.ListItem(path=temp_file_path) play_item = setPlayItemInfo(play_item) xbmcplugin.setResolvedUrl(pluginhandle, True, listitem=play_item)
def make_dir(mypath, dirname): ''' Creates sub-directories if they are not found. ''' import xbmcvfs if not xbmcvfs.exists(mypath): try: xbmcvfs.mkdirs(mypath) except: xbmcvfs.mkdir(mypath) subpath = os.path.join(mypath, dirname) if not xbmcvfs.exists(subpath): try: xbmcvfs.mkdirs(subpath) except: xbmcvfs.mkdir(subpath) return subpath # -----------------------------------------------------------------------------------------------------------------
def _get_all(self, xml_contents): return_list = [] for match in re.finditer('lang_code="(?P<language>[^"]+?)"', xml_contents, re.IGNORECASE): language = match.group('language') fname = self.srt_filename(language) if xbmcvfs.exists(fname): self.context.log_debug('Subtitle exists for: %s, filename: %s' % (language, fname)) return_list.append(fname) continue result = requests.get(self.subtitle_url(language), headers=self.headers, verify=False, allow_redirects=True) if result.text: self.context.log_debug('Subtitle found for: %s' % language) result = self._write_file(fname, result.text) if result: return_list.append(fname) continue else: self.context.log_debug('Failed to retrieve subtitles for: %s' % language) continue if not return_list: self.context.log_debug('No subtitles found') return return_list
def _by_regex(self, reg_exp, xml_contents): match = re.search(reg_exp, xml_contents, re.IGNORECASE) if match: language = match.group('language') fname = self.srt_filename(language) if xbmcvfs.exists(fname): self.context.log_debug('Subtitle exists for: %s, filename: %s' % (language, fname)) return [fname] result = requests.get(self.subtitle_url(language), headers=self.headers, verify=False, allow_redirects=True) if result.text: self.context.log_debug('Subtitle found for: %s' % language) result = self._write_file(fname, result.text) if result: return [fname] else: return [] else: self.context.log_debug('Failed to retrieve subtitles for: %s' % language) return [] else: self.context.log_debug('No subtitles found for: %s' % reg_exp) return []
def copyUserDefinedFiles(): # Copy everything in the user directory to the addon directory infoTrace("vpnproviders.py", "Copying user defined files from userdata directory") source_path = getUserDataPath((user_def_str)+"/") dest_path = getAddonPath(True, user_def_str + "/") # Get the list of connection profiles and another list of strings to abuse for the selection screen try: files = getUserDataList(user_def_str, "*") if len(files) == 0: errorTrace("vpnproviders.py", "No User Defined files available to copy from " + source_path) return False for file in files: name = file[file.rfind(getSeparator())+1:] dest_file = dest_path + getSeparator() + name xbmcvfs.copy(file, dest_file) if not xbmcvfs.exists(dest_file): raise IOError('Failed to copy user def file ' + file + " to " + dest_file) return True except Exception as e: errorTrace("vpnproviders.py", "Error copying files from " + source_path + " to " + dest_path) errorTrace("vpnproviders.py", str(e)) return False
def populateSupportingFromGit(vpn_provider): # Copy all files from download to the directory that are not .ovpn, ignoring the metadata try: filelist = getDownloadList(vpn_provider, "*") debugTrace("Copying supporting files into addon directory for " + vpn_provider) for file in filelist: if not file.endswith(".ovpn") and not file.endswith("METADATA.txt"): name = os.path.basename(file) fullname = getAddonPath(True, vpn_provider + "/" + name) xbmcvfs.copy(file, fullname) if not xbmcvfs.exists(fullname): raise IOError('Failed to copy supporting file ' + file + " to " + fullname) return True except Exception as e: errorTrace("vpnproviders.py", "Can't copy " + file + " for VPN " + vpn_provider) errorTrace("vpnproviders.py", str(e)) return False
def clearUserData(): # Deleting everything here, but not deleting 'DEFAULT.txt' as # any existing user and password info will get deleted path = getUserDataPath("UserDefined" + "/*.*") debugTrace("Deleting contents of User Defined directory" + path) files = glob.glob(path) try: for file in files: if not file.endswith("DEFAULT.txt") and xbmcvfs.exists(file): debugTrace("Deleting " + file) xbmcvfs.delete(file) except Exception as e: errorTrace("import.py", "Couldn't clear the UserDefined directory") errorTrace("import.py", str(e)) return False return True
def fixKeymaps(): # Fix the keymap file name if it's been changed or the old name was being used name = getKeyMapsFileName() old = getOldKeyMapsFileName() dir = getKeyMapsPath("*") full_name = getKeyMapsPath(name) try: debugTrace("Getting contents of keymaps directory " + dir) files = (glob.glob(dir)) if not full_name in files and len(files) > 0: for file in files: if (name in file) or (old in file): infoTrace("common.py", "Renaming " + file + " to " + full_name) xbmcvfs.rename(file, full_name) xbmc.sleep(100) # Wait 10 seconds for rename to happen otherwise quit and let it fail in the future for i in range(0, 9): if xbmcvfs.exists(full_name): break xbmc.sleep(1000) return True except Exception as e: errorTrace("common.py", "Problem fixing the keymap filename.") errorTrace("common.py", str(e)) return False
def copySystemdFiles(): # Delete any existing openvpn.service and copy openvpn service file to config directory service_source = getAddonPath(True, "openvpn.service") service_dest = getSystemdPath("system.d/openvpn.service") debugTrace("Copying openvpn.service " + service_source + " to " + service_dest) if not fakeSystemd(): if xbmcvfs.exists(service_dest): xbmcvfs.delete(service_dest) xbmcvfs.copy(service_source, service_dest) if not xbmcvfs.exists(service_dest): raise IOError('Failed to copy service ' + service_source + " to " + service_dest) # Delete any existing openvpn.config and copy first VPN to openvpn.config config_source = sudo_setting = xbmcaddon.Addon("service.vpn.manager").getSetting("1_vpn_validated") if service_source == "": errorTrace("platform.py", "Nothing has been validated") config_dest = getSystemdPath("openvpn.config") debugTrace("Copying openvpn.config " + config_source + " to " + config_dest) if not fakeSystemd(): if xbmcvfs.exists(config_dest): xbmcvfs.delete(config_dest) xbmcvfs.copy(config_source, config_dest) if not xbmcvfs.exists(config_dest): raise IOError('Failed to copy service ovpn ' + config_source + " to " + config_dest)
def checkVPNInstall(addon): # Check that openvpn plugin exists (this was an issue with OE6), there's # another check below that validates that the command actually works if not fakeConnection(): p = getPlatform() dialog_msg = "" if p == platforms.RPI: command_path = getAddonPath(False, "network.openvpn/bin/openvpn") if xbmcvfs.exists(command_path): # Check the version that's installed vpn_addon = xbmcaddon.Addon("network.openvpn") version = vpn_addon.getAddonInfo("version") version = version.replace(".", "") if int(version) >= 600: return True dialog_msg = "OpenVPN executable not available. Install the openvpn plugin, version 6.0.1 or greater from the OpenELEC unofficial repo." # Display error message xbmcgui.Dialog().ok(addon.getAddonInfo("name"), dialog_msg) return True
def __init__(self): self.userthemes_path = u"special://profile/addon_data/%s/themes/" % xbmc.getSkinDir() if not xbmcvfs.exists(self.userthemes_path): xbmcvfs.mkdir(self.userthemes_path) self.skinthemes_path = u"special://skin/extras/skinthemes/" if xbmcvfs.exists("special://home/addons/resource.skinthemes.%s/resources/" % get_skin_name()): self.skinthemes_path = u"special://home/addons/resource.skinthemes.%s/resources/" % get_skin_name() self.addon = xbmcaddon.Addon(ADDON_ID)
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 backup_skinshortcuts_images(shortcutfile, dest_path): '''parse skinshortcuts file and copy images to backup location''' shortcutfile = xbmc.translatePath(shortcutfile).decode("utf-8") doc = parse(shortcutfile) listing = doc.documentElement.getElementsByTagName('shortcut') for shortcut in listing: defaultid = shortcut.getElementsByTagName('defaultID') if defaultid: defaultid = defaultid[0].firstChild if defaultid: defaultid = defaultid.data if not defaultid: defaultid = shortcut.getElementsByTagName('label')[0].firstChild.data thumb = shortcut.getElementsByTagName('thumb') if thumb: thumb = thumb[0].firstChild if thumb: thumb = thumb.data if thumb and (thumb.endswith(".jpg") or thumb.endswith(".png") or thumb.endswith(".gif")): thumb = get_clean_image(thumb) extension = thumb.split(".")[-1] newthumb = os.path.join(dest_path, "%s-thumb-%s.%s" % (xbmc.getSkinDir(), normalize_string(defaultid), extension)) newthumb_vfs = "special://profile/addon_data/script.skinshortcuts/%s-thumb-%s.%s" % ( xbmc.getSkinDir(), normalize_string(defaultid), extension) if xbmcvfs.exists(thumb): copy_file(thumb, newthumb) shortcut.getElementsByTagName('thumb')[0].firstChild.data = newthumb_vfs # write changes to skinshortcuts file shortcuts_file = xbmcvfs.File(shortcutfile, "w") shortcuts_file.write(doc.toxml(encoding='utf-8')) shortcuts_file.close()
def create_temp(): '''create temp folder for skin backup/restore''' temp_path = u'%stemp/' % ADDON_DATA # workaround weird slashes behaviour on some platforms. temp_path = temp_path.replace("//","/").replace("special:/","special://") if xbmcvfs.exists(temp_path): recursive_delete_dir(temp_path) xbmc.sleep(2000) xbmcvfs.mkdirs(temp_path) xbmcvfs.mkdirs(temp_path + "skinbackup/") return temp_path
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 copy_file(source, destination, do_wait=False): '''copy a file on the filesystem, wait for the action to be completed''' if xbmcvfs.exists(destination): delete_file(destination) xbmcvfs.copy(source, destination) if do_wait: count = 20 while count: xbmc.sleep(500) # this first sleep is intentional if xbmcvfs.exists(destination): break count -= 1
def delete_file(filepath, do_wait=False): '''delete a file on the filesystem, wait for the action to be completed''' xbmcvfs.delete(filepath) if do_wait: count = 20 while count: xbmc.sleep(500) # this first sleep is intentional if not xbmcvfs.exists(filepath): break count -= 1
def Download(link, filename): subtitle_list = [] exts = [".srt", ".sub", ".txt", ".smi", ".ssa", ".ass"] if link: downloadlink = link log(__name__, "Downloadlink %s" % link) class MyOpener(urllib.FancyURLopener): version = "User-Agent=Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3 ( .NET CLR 3.5.30729)" my_urlopener = MyOpener() my_urlopener.addheader('Referer', link) postparams = None log(__name__, "Fetching subtitles using url '%s' with referer header '%s' and post parameters '%s'" % (link, link, postparams)) response = my_urlopener.open(link, postparams) local_tmp_file = os.path.join(__temp__, "sub.srt") if xbmcvfs.exists(__temp__): shutil.rmtree(__temp__) xbmcvfs.mkdirs(__temp__) try: log(__name__, "Saving subtitles to '%s'" % local_tmp_file) local_file_handle = open(local_tmp_file, "wb") local_file_handle.write(response.read()) local_file_handle.close() subtitle_list.append(local_tmp_file) log(__name__, "=== returning subtitle file %s" % file) except: log(__name__, "Failed to save subtitle to %s" % local_tmp_file) return subtitle_list
def data_dir(): """"get user data directory of this addon. according to http://wiki.xbmc.org/index.php?title=Add-on_Rules#Requirements_for_scripts_and_plugins """ __datapath__ = xbmc.translatePath( __Addon.getAddonInfo('profile') ).decode('utf-8') if not xbmcvfs.exists(__datapath__): xbmcvfs.mkdir(__datapath__) return __datapath__
def playlist_path(pcs_file_path, stream): user_info = get_user_info() user_name = user_info['username'] user_cookie = user_info['cookie'] user_tokens = user_info['tokens'] if stream: playlist_data = pcs.get_streaming_playlist(user_cookie, pcs_file_path, stream) if playlist_data: raw_dir = os.path.dirname(pcs_file_path) m = re.search('\/(.*)', raw_dir) dirname = m.group(1) basename = os.path.basename(pcs_file_path) r = re.search('(.*)\.(.*)$', basename) filename = ''.join([r.group(1), stream, '.m3u8']) dirpath = os.path.join(utils.data_dir(), user_name, dirname) if not xbmcvfs.exists(dirpath): xbmcvfs.mkdirs(dirpath) filepath = os.path.join(dirpath, filename) tmpFile = xbmcvfs.File(filepath, 'w') tmpFile.write(bytearray(playlist_data, 'utf-8')) return filepath else: dialog.notification('', u'??????', xbmcgui.NOTIFICATION_INFO, 4000) return None else: url = pcs.stream_download(user_cookie, user_tokens, pcs_file_path) if url: return url else: dialog.notification('', u'??????????????', xbmcgui.NOTIFICATION_INFO, 4000) return None
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 ##