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