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
python类exists()的实例源码
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))
backuprestore.py 文件源码
项目:script.skin.helper.skinbackup
作者: marcelveldt
项目源码
文件源码
阅读 25
收藏 0
点赞 0
评论 0
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)
backuprestore.py 文件源码
项目:script.skin.helper.skinbackup
作者: marcelveldt
项目源码
文件源码
阅读 25
收藏 0
点赞 0
评论 0
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