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
python类mkdirs()的实例源码
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 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
# -----------------------------------------------------------------------------------------------------------------
backuprestore.py 文件源码
项目:script.skin.helper.skinbackup
作者: marcelveldt
项目源码
文件源码
阅读 24
收藏 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
def unzip_fromfile(zip_path, dest_path):
'''method to unzip a zipfile to a destination path'''
import shutil
import zipfile
zip_path = xbmc.translatePath(zip_path).decode("utf-8")
dest_path = xbmc.translatePath(dest_path).decode("utf-8")
log_msg("START UNZIP of file %s to path %s " % (zip_path, dest_path))
zip_file = zipfile.ZipFile(zip_path, 'r')
for fileinfo in zip_file.infolist():
filename = fileinfo.filename
if not isinstance(filename, unicode):
filename = filename.decode("utf-8")
log_msg("unzipping: " + filename)
splitter = None
if "\\" in filename:
xbmcvfs.mkdirs(os.path.join(dest_path, filename.rsplit("\\", 1)[0]))
splitter = "\\"
elif "/" in filename:
xbmcvfs.mkdirs(os.path.join(dest_path, filename.rsplit("/", 1)[0]))
splitter = "/"
filename = os.path.join(dest_path, filename)
if not (splitter and filename.endswith(splitter)):
try:
# newer python uses unicode
outputfile = open(filename, "wb")
except Exception:
# older python uses utf-8
outputfile = open(filename.encode("utf-8"), "wb")
# use shutil to support non-ascii formatted files in the zip
shutil.copyfileobj(zip_file.open(fileinfo.filename), outputfile)
outputfile.close()
zip_file.close()
log_msg("UNZIP DONE of file %s to path %s " % (zip_path, dest_path))
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 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 setSRT(self, service):
if not constants.CONST.SRT:
return
#load cachePath if not already loaded
if not service.settings.cacheSRT and self.cachePath == '':
self.cachePath = service.settings.cachePath
#only makes sense to cache SRT if the cachePath exists
if service.settings.cacheSRT and self.cachePath != '':
cachePath = str(self.cachePath) + '/' + str(self.package.file.id)+'/'
if not xbmcvfs.exists(cachePath):
xbmcvfs.mkdirs(cachePath)
srt = service.getSRT(self.package)
if srt:
for file in srt:
if not xbmcvfs.exists(str(cachePath) + str(file[0])):
service.downloadGeneralFile(file[1], str(cachePath) + str(file[0]))
self.srt.append(str(cachePath) + str(file[0]))
#fetch SRT URLs but we won't cache the files
else:
srt = service.getSRT(self.package)
if srt:
for file in srt:
self.srt.append(str(file[1]) + '|' + service.getHeadersEncoded())
##
# set the CC for the video file
##
def setCC(self, service):
if not constants.CONST.CC:
return
#load cachePath if not already loaded
if self.cachePath == '':
self.cachePath = service.settings.cachePath
# there is no cache path setting or the setting is unset -- we should assume user does not want to use caching
# CC files need to be cached (so they can be converted to SRT) -- don't do anything if we don't have the cachePath
if self.cachePath == '':
return
else:
cachePath = str(self.cachePath) + '/' + str(self.package.file.id)+'/'
if not xbmcvfs.exists(cachePath):
xbmcvfs.mkdirs(cachePath)
cachePath = str(cachePath) + str(self.package.file.id)
cc = service.getTTS(self.package.file.srtURL)
if cc:
for file in cc:
if not xbmcvfs.exists(cachePath + str(file[0])):
service.downloadTTS(file[1], str(cachePath) + str(file[0]))
self.srt.append(str(cachePath) + str(file[0]))
##
# fetch the SRT
##
def _get_database(self):
'''get reference to our sqllite _database - performs basic integrity check'''
addon = xbmcaddon.Addon(ADDON_ID)
dbpath = addon.getAddonInfo('profile')
dbfile = xbmc.translatePath("%s/simplecache.db" % dbpath).decode('utf-8')
if not xbmcvfs.exists(dbpath):
xbmcvfs.mkdirs(dbpath)
del addon
try:
connection = sqlite3.connect(dbfile, timeout=30, isolation_level=None)
connection.execute('SELECT * FROM simplecache LIMIT 1')
return connection
except Exception as error:
# our _database is corrupt or doesn't exist yet, we simply try to recreate it
if xbmcvfs.exists(dbfile):
xbmcvfs.delete(dbfile)
try:
connection = sqlite3.connect(dbfile, timeout=30, isolation_level=None)
connection.execute(
"""CREATE TABLE IF NOT EXISTS simplecache(
id TEXT UNIQUE, expires INTEGER, data TEXT, checksum INTEGER)""")
return connection
except Exception as error:
self._log_msg("Exception while initializing _database: %s" % str(error), xbmc.LOGWARNING)
self.close()
return None
def add_item_to_library(self, item_path, item_url):
error = False
new = False
item_path = xbmc.validatePath(item_path)
if item_path:
item_path = xbmc.translatePath(item_path)
dir = os.path.dirname(item_path)
if not xbmcvfs.exists(dir):
try:
xbmcvfs.mkdirs(dir)
except Exception:
error = True
util.error('[SC] Failed to create directory 1: ' + dir)
if not xbmcvfs.exists(item_path):
try:
file_desc = xbmcvfs.File(item_path, 'w')
file_desc.write(str(item_url))
file_desc.close()
new = True
except Exception, e:
util.error('[SC] Failed to create .strm file: ' + item_path + " | " + str(e))
error = True
else:
error = True
util.debug("[SC] add item: %s" % item_path)
return (error, new)
def _get_database(self):
'''get reference to our sqllite _database - performs basic integrity check'''
addon = xbmcaddon.Addon(ADDON_ID)
dbpath = addon.getAddonInfo('profile')
dbfile = xbmc.translatePath("%s/simplecache.db" % dbpath).decode('utf-8')
if not xbmcvfs.exists(dbpath):
xbmcvfs.mkdirs(dbpath)
del addon
try:
connection = sqlite3.connect(dbfile, timeout=30, isolation_level=None)
connection.execute('SELECT * FROM simplecache LIMIT 1')
return connection
except Exception as error:
# our _database is corrupt or doesn't exist yet, we simply try to recreate it
if xbmcvfs.exists(dbfile):
xbmcvfs.delete(dbfile)
try:
connection = sqlite3.connect(dbfile, timeout=30, isolation_level=None)
connection.execute(
"""CREATE TABLE IF NOT EXISTS simplecache(
id TEXT UNIQUE, expires INTEGER, data TEXT, checksum INTEGER)""")
return connection
except Exception as error:
self._log_msg("Exception while initializing _database: %s" % str(error), xbmc.LOGWARNING)
self.close()
return None
def make_dir(self, mypath):
''' Creates sub-directories if they are not found. '''
try:
if not xbmcvfs.exists(mypath): xbmcvfs.mkdirs(mypath)
except:
if not os.path.exists(mypath): os.makedirs(mypath)
def make_dir(mypath, dirname):
''' Creates sub-directories if they are not found. '''
subpath = os.path.join(mypath, dirname)
try:
if not xbmcvfs.exists(subpath): xbmcvfs.mkdirs(subpath)
except:
if not os.path.exists(subpath): os.makedirs(subpath)
return subpath
def onInitialized(success):
if success:
channelList = database.getChannelList(onlyVisible=False)
xbmcvfs.mkdirs("special://profile/addon_data/script.tvguide.fullscreen/channel_logos/")
for channel in channelList:
from_file = channel.logo
regex = '[%s]' % re.escape('[]/\:')
xbmc.log(regex)
to_file = "special://profile/addon_data/script.tvguide.fullscreen/channel_logos/%s.png" % re.sub(regex,' ',channel.title)
xbmcvfs.copy(from_file,to_file)
database.close(onAutoplaysCleared)
else:
database.close()
def getLogo(title,ask=False,force=True):
infile = xbmc.translatePath("special://profile/addon_data/script.tvguide.fullscreen/logos/temp.png")
outfile = xbmc.translatePath("special://profile/addon_data/script.tvguide.fullscreen/logos/%s.png" % title)
if not force and xbmcvfs.exists(outfile):
return outfile
xbmcvfs.mkdirs("special://profile/addon_data/script.tvguide.fullscreen/logos")
db_url = "http://www.thelogodb.com/api/json/v1/4423/tvchannel.php?s=%s" % re.sub(' ','+',title)
try: json = requests.get(db_url).json()
except: pass
if json and "channels" in json:
channels = json["channels"]
if channels:
if ask:
names = ["%s [%s]" % (c["strChannel"],c["strCountry"]) for c in channels]
d = xbmcgui.Dialog()
selected = d.select("Logo Source: %s" % title,names)
else:
selected = 0
if selected > -1:
logo = channels[selected]["strLogoWide"]
if not logo:
return None
logo = re.sub('^https','http',logo)
data = requests.get(logo).content
f = xbmcvfs.File("special://profile/addon_data/script.tvguide.fullscreen/logos/temp.png","wb")
f.write(data)
f.close()
from PIL import Image, ImageOps
image = Image.open(infile)
border = 0
image = autocrop_image(image, border)
image.save(outfile)
logo = outfile
return logo
def save_to_file(content, filename, path=""):
if path == "":
return False
if not xbmcvfs.exists(path):
xbmcvfs.mkdirs(path)
text_file_path = os.path.join(path, filename + ".txt")
now = time.time()
text_file = xbmcvfs.File(text_file_path, "w")
json.dump(content, text_file)
text_file.close()
logger.info("saved textfile %s. Time: %f" % (text_file_path, time.time() - now))
return True
def __init__(self):
self.getSettings()
if not xbmcvfs.exists(PROFILE):
xbmcvfs.mkdirs(PROFILE)
files = self.getFiles()
for item in files:
filetype = item[0]
if filetype == 'log':
error = LANGUAGE(32011)
name = LANGUAGE(32031)
elif filetype == 'oldlog':
error = LANGUAGE(32012)
name = LANGUAGE(32032)
elif filetype == 'crashlog':
error = LANGUAGE(32013)
name = LANGUAGE(32033)
succes, data = self.readLog(item[1])
if succes:
content = self.cleanLog(data)
succes, result = self.postLog(content)
if succes:
self.showResult(LANGUAGE(32006) % (name, result), result)
else:
self.showResult('%s[CR]%s' % (error, result))
else:
self.showResult('%s[CR]%s' % (error, result))
def __replace_gif(url):
""" put gifs in local cache
try to put gif in cache to enable motion
Keyword Arguments:
url -- url pointing to gif
"""
if not url.endswith(".gif"):
return url
else:
base_folder = xbmcaddon.Addon().getSetting("cache_folder")
dest_folder = os.path.join(xbmc.translatePath(base_folder), "artcache")
xbmcvfs.mkdirs(dest_folder)
parts = url.split("/")
dest = xbmc.makeLegalFilename(
# TODO make sure this is unique
os.path.join(dest_folder, parts[-2] + parts[-1]))
if not xbmcvfs.exists(dest):
try:
response = requests.get(url, timeout=10, verify=False)
except:
return None
if response.status_code == 200:
with open(dest, 'wb') as out_file:
data = response.content
response.close()
out_file.write(data)
# shutil.copyfileobj(response.raw, out_file)
del data
del response
if os.path.getsize(dest) == 0:
koding.dolog("0 size gif: " + repr(dest))
os.remove(dest)
return None
else:
koding.dolog("size: " + repr(os.path.getsize(dest)))
else:
koding.Text_Box(xbmcaddon.Addon().getAddonInfo('name'),
_("gif not found: ") + url)
return None
xbmc.log("gif done: " + repr(dest))
return dest
def __replace_gif(url):
""" put gifs in local cache
try to put gif in cache to enable motion
Keyword Arguments:
url -- url pointing to gif
"""
if not url.endswith(".gif"):
return url
else:
base_folder = xbmcaddon.Addon().getSetting("cache_folder")
dest_folder = os.path.join(xbmc.translatePath(base_folder), "artcache")
xbmcvfs.mkdirs(dest_folder)
parts = url.split("/")
dest = xbmc.makeLegalFilename(
# TODO make sure this is unique
os.path.join(dest_folder, parts[-2] + parts[-1]))
if not xbmcvfs.exists(dest):
try:
response = requests.get(url, timeout=10, verify=False)
except:
return None
if response.status_code == 200:
with open(dest, 'wb') as out_file:
data = response.content
response.close()
out_file.write(data)
# shutil.copyfileobj(response.raw, out_file)
del data
del response
if os.path.getsize(dest) == 0:
koding.dolog("0 size gif: " + repr(dest))
os.remove(dest)
return None
else:
koding.dolog("size: " + repr(os.path.getsize(dest)))
else:
koding.Text_Box(xbmcaddon.Addon().getAddonInfo('name'),
_("gif not found: ") + url)
return None
xbmc.log("gif done: " + repr(dest))
return dest
def setThumbnail(self, service, url=''):
if not constants.CONST.CACHE:
return url
#load cachePath if not already loaded
if self.cachePath == '':
self.cachePath = service.settings.cachePath
# there is no cache path setting or the setting is unset -- we should assume user does not want to use caching
if not service.settings.cacheThumbnails or self.cachePath == '':
if url == '':
return self.package.file.thumbnail
else:
return url
if url == '':
url = self.package.file.thumbnail
#simply no thumbnail
if url == '':
return ""
#user doesn't want to cache thumbnails
if not service.settings.cacheThumbnails:
return url
cachePath = str(self.cachePath) + str(self.package.file.id) + '/'
cacheFile = str(self.cachePath) + str(self.package.file.id) + '.jpg'
if not xbmcvfs.exists(cachePath):
xbmcvfs.mkdirs(cachePath)
if not xbmcvfs.exists(cacheFile):
cacheFile = service.downloadGeneralFile(url, cacheFile)
if cacheFile is None:
return url
return cacheFile
##
# get the thumbnail
##
def add_movie(self, title, alt_title, year, video_id, build_url):
"""Adds a movie to the local db, generates & persists the strm file
Parameters
----------
title : :obj:`str`
Title of the show
alt_title : :obj:`str`
Alternative title given by the user
year : :obj:`int`
Release year of the show
video_id : :obj:`str`
ID of the video to be played
build_url : :obj:`fn`
Function to generate the stream url
"""
title = re.sub(r'[?|$|!|:|#]', r'', title)
movie_meta = '%s (%d)' % (title, year)
folder = re.sub(r'[?|$|!|:|#]', r'', alt_title)
dirname = self.kodi_helper.check_folder_path(
path=os.path.join(self.movie_path, folder))
filename = os.path.join(dirname, movie_meta + '.strm')
progress = xbmcgui.DialogProgress()
progress.create(self.kodi_helper.get_local_string(650), movie_meta)
if xbmcvfs.exists(filename):
return
if not xbmcvfs.exists(dirname):
xbmcvfs.mkdirs(dirname)
if self.movie_exists(title=title, year=year) is False:
progress.update(50)
time.sleep(0.5)
self.db[self.movies_label][movie_meta] = {'alt_title': alt_title}
self._update_local_db(filename=self.db_filepath, db=self.db)
url = build_url({'action': 'play_video', 'video_id': video_id})
self.write_strm_file(path=filename, url=url, title_player=movie_meta)
progress.update(100)
time.sleep(1)
progress.close()
def add_show(self, title, alt_title, episodes, build_url):
"""Adds a show to the local db, generates & persists the strm files
Note: Can also used to store complete seasons or single episodes,
it all depends on what is present in the episodes dictionary
Parameters
----------
title : :obj:`str`
Title of the show
alt_title : :obj:`str`
Alternative title given by the user
episodes : :obj:`dict` of :obj:`dict`
Episodes that need to be added
build_url : :obj:`fn`
Function to generate the stream url
"""
title = re.sub(r'[?|$|!|:|#]', r'', title)
show_meta = '%s' % (title)
folder = re.sub(r'[?|$|!|:|#]', r'', alt_title.encode('utf-8'))
show_dir = self.kodi_helper.check_folder_path(
path=os.path.join(self.tvshow_path, folder))
progress = xbmcgui.DialogProgress()
progress.create(self.kodi_helper.get_local_string(650), show_meta)
count = 1
if not xbmcvfs.exists(show_dir):
xbmcvfs.mkdirs(show_dir)
if self.show_exists(title) is False:
self.db[self.series_label][show_meta] = {
'seasons': [],
'episodes': [],
'alt_title': alt_title}
episode_count_total = len(episodes)
step = round(100.0 / episode_count_total, 1)
percent = step
for episode in episodes:
desc = self.kodi_helper.get_local_string(20373) + ': '
desc += str(episode.get('season'))
long_desc = self.kodi_helper.get_local_string(20359) + ': '
long_desc += str(episode.get('episode'))
progress.update(
percent=int(percent),
line1=show_meta,
line2=desc,
line3=long_desc)
self._add_episode(
show_dir=show_dir,
title=title,
season=episode.get('season'),
episode=episode.get('episode'),
video_id=episode.get('id'),
build_url=build_url)
percent += step
time.sleep(0.05)
self._update_local_db(filename=self.db_filepath, db=self.db)
time.sleep(1)
progress.close()
return show_dir