def _enableKeymap(self): try: xbmcvfs.copy(self.KEYMAPSOURCEFILE, self.KEYMAPDESTFILE) xbmc.executebuiltin('Action(reloadkeymaps)') log("SonosVolumeRedirect: Installed custom keymap") except: log("SonosVolumeRedirect: Failed to copy & load custom keymap: %s" % traceback.format_exc(), xbmc.LOGERROR)
def pchkmedia(): try: KmediaDir = "plugin.video.kmediatorrent" f = open(os.path.join(addonspath,KmediaDir,"addon.xml"), 'r') AddOnId=f.read() f.close except: try: KmediaDir = "plugin.video.kmediatorrent-2.3.7" f = open(os.path.join(addonspath,KmediaDir,"addon.xml"), 'r') AddOnId=f.read() f.close except: return False #if AddOnId == "" : return False if not 'version="2.3.7"' in AddOnId: return False destino = os.path.join(addonspath,KmediaDir,"resources","settings.xml") if os.path.isfile(destino): if not xbmcvfs.copy(os.path.join(__cwd__ , "resources" , "parches" , "kmediatorrent" , "settings.xml") , destino) : return False else: return False destino = os.path.join(addonspath,KmediaDir,"resources","site-packages","kmediatorrent","player.py") if os.path.isfile(destino): if not xbmcvfs.copy(os.path.join(__cwd__ , "resources" , "parches" , "kmediatorrent" , "player.py") , destino) : return False else: return False return True
def pchplexusstreams(): proceso = 0 proceso2 = 0 destinoset = os.path.join(addonspath,"plugin.video.plexus-streams","resources","settings.xml") if os.path.isfile(destinoset): md5sum = txtmd5(destinoset) if md5sum == "d9ff4538382826cb676f83fad177d8a9": proceso = 1 elif md5sum == "bde9fe5ba3d7d0159f0c5b127a5e0181": proceso = 2 else: proceso = 3 else: proceso = 0 destinoace = os.path.join(addonspath,"plugin.video.plexus-streams","resources","core","acestream.py") if os.path.isfile(destinoace): md5sum = txtmd5(destinoace) if md5sum == "5e06800233f5d49fa2e11353ef33533f": proceso2 = 1 elif md5sum == "63267830d43361a408e8b34695cbb073": proceso = 2 else: proceso = 3 else: proceso = 0 if proceso == 1 and proceso2 == 1: if not xbmcvfs.copy(os.path.join(__cwd__ , "resources" , "parches" , "plexus-streams" , "settings.xml") , destinoset) : return 0 if not xbmcvfs.copy(os.path.join(__cwd__ , "resources" , "parches" , "plexus-streams" , "acestream.py") , destinoace) : return 0 return proceso else: return proceso
def _download( self, src, dst, dst2 ): if (not xbmc.abortRequested): tmpname = xbmc.translatePath('special://profile/addon_data/%s/temp/%s' % ( addonname , xbmc.getCacheThumbName(src) )) lw.log( ['the tmpname is ' + tmpname] ) if xbmcvfs.exists(tmpname): success, loglines = deleteFile( tmpname ) lw.log( loglines ) success, loglines, urldata = imgURL.Get( src, params=self.params ) lw.log( loglines ) if success: success, loglines = writeFile( urldata, tmpname ) lw.log( loglines ) if not success: return False if xbmcvfs.Stat( tmpname ).st_size() > 999: image_ext = getImageType( tmpname ) if not xbmcvfs.exists ( dst + image_ext ): lw.log( ['copying %s to %s' % (tmpname, dst2 + image_ext)] ) xbmcvfs.copy( tmpname, dst2 + image_ext ) lw.log( ['moving %s to %s' % (tmpname, dst + image_ext)] ) xbmcvfs.rename( tmpname, dst + image_ext ) return True else: lw.log( ['image already exists, deleting temporary file'] ) success, loglines = deleteFile( tmpname ) lw.log( loglines ) return False else: success, loglines = deleteFile( tmpname ) lw.log( loglines ) return False
def copy(file, path): try: # Post Dharma import xbmcvfs size_file, hash_file = xbmc.subHashAndFileSize(file) try: size_dest, hash_dest = xbmc.subHashAndFileSize(os.path.join(path, os.path.basename(file))) except: size_dest = 0 hash_dest = "" if hash_file != hash_dest: xbmcvfs.copy(file, os.path.join(path, os.path.basename(file))) if __settings__.getSetting( "delete" ) == "true": size_dest, hash_dest = xbmc.subHashAndFileSize(os.path.join(path, os.path.basename(file))) if hash_file == hash_dest: xbmcvfs.delete(file) log("Deleted %s" % file) except: # Dharma import shutil, filecmp if not os.path.exists(os.path.join(path, os.path.basename(file))): shutil.copy(file,os.path.join(path, os.path.basename(file))) if filecmp.cmp(file, os.path.join(path, os.path.basename(file))) and __settings__.getSetting( "delete" ) == "true": os.remove(file) log("Deleted %s" % file)
def blur(input_img, radius=25): if not input_img: return {} if not xbmcvfs.exists(IMAGE_PATH): xbmcvfs.mkdir(IMAGE_PATH) input_img = utils.translate_path(urllib.unquote(input_img.encode("utf-8"))) input_img = input_img.replace("image://", "").rstrip("/") cachedthumb = xbmc.getCacheThumbName(input_img) filename = "%s-radius_%i.png" % (cachedthumb, radius) targetfile = os.path.join(IMAGE_PATH, filename) vid_cache_file = os.path.join("special://profile/Thumbnails/Video", cachedthumb[0], cachedthumb) cache_file = os.path.join("special://profile/Thumbnails", cachedthumb[0], cachedthumb[:-4] + ".jpg") if xbmcvfs.exists(targetfile): img = PIL.Image.open(targetfile) return {"ImageFilter": targetfile, "ImageColor": get_colors(img)} try: if xbmcvfs.exists(cache_file): utils.log("image already in xbmc cache: " + cache_file) img = PIL.Image.open(utils.translate_path(cache_file)) elif xbmcvfs.exists(vid_cache_file): utils.log("image already in xbmc video cache: " + vid_cache_file) img = PIL.Image.open(utils.translate_path(vid_cache_file)) else: xbmcvfs.copy(input_img, targetfile) img = PIL.Image.open(targetfile) img.thumbnail((200, 200), PIL.Image.ANTIALIAS) imgfilter = MyGaussianBlur(radius=radius) img = img.convert('RGB').filter(imgfilter) img.save(targetfile) except Exception: utils.log("Could not get image for %s" % input_img) return {} return {"ImageFilter": targetfile, "ImageColor": get_colors(img)}
def _copy_moviethumbs( self ): count = 0 processeditems = 0 json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.GetMovies", "params": {"properties": ["file", "title", "thumbnail", "year"], "filter": {"field": "path", "operator": "contains", "value": "%s"}}, "id": 1}' % self.path) json_query = unicode(json_query, 'utf-8', errors='ignore') json_response = json.loads(json_query) if json_response.has_key('result') and (json_response['result'] != None) and (json_response['result'].has_key('movies')): totalitems = len( json_response['result']['movies'] ) for item in json_response['result']['movies']: if self.dialog.iscanceled(): log('script cancelled') return processeditems = processeditems + 1 self.dialog.update( int( float( processeditems ) / float( totalitems ) * 100), LANGUAGE(32005) + ': ' + str( count + 1 ) ) name = item['title'] year = str(item['year']) artwork = item['thumbnail'] tmp_filename = name + ' (' + year + ')' + '.jpg' filename = clean_filename( tmp_filename ) # test file path with movie_content to find source name moviethumbspath = self.moviethumbspath if self.split_movies_sources == "true" and self.movies_content.has_key(str(item['file'])): moviethumbspath = os.path.join( self.moviethumbspath, self.movies_content[str(item['file'])]) if artwork != '': try: xbmcvfs.copy( xbmc.translatePath( artwork ), os.path.join( moviethumbspath, filename ) ) count += 1 except: log( 'failed to copy moviethumb' ) log( 'moviethumbs copied: %s' % count )
def run(self): #get a list of all the settings we can manipulate via json json_response = json.loads(xbmc.executeJSONRPC('{"jsonrpc":"2.0", "id":1, "method":"Settings.GetSettings","params":{"level":"advanced"}}')) settings = json_response['result']['settings'] for aSetting in settings: self.settings_allowed.append(aSetting['id']) #parse the existing xml file and get all the settings root_nodes = self.__parseNodes(self.doc.documentElement) for aNode in root_nodes: secondary_list = self.__parseNodes(self.doc.getElementsByTagName(aNode.name)[0]) for secondNode in secondary_list: #if the node does not have children and is not default if(not secondNode.hasChildren and not secondNode.isDefault): if(secondNode.json_name() in self.settings_allowed): self.found_settings.append(secondNode) #go through all the found settings and update them for aSetting in self.found_settings: utils.log("updating: " + aSetting.json_name() + ", value: " + aSetting.value) #check for boolean and numeric values if(aSetting.value.isdigit() or (aSetting.value == 'true' or aSetting.value == 'false')): xbmc.executeJSONRPC('{"jsonrpc":"2.0", "id":1, "method":"Settings.SetSettingValue","params":{"setting":"' + aSetting.json_name() + '","value":' + aSetting.value + '}}') else: xbmc.executeJSONRPC('{"jsonrpc":"2.0", "id":1, "method":"Settings.SetSettingValue","params":{"setting":"' + aSetting.json_name() + '","value":"' + utils.encode(aSetting.value) + '"}}') #make a copy of the guisettings file to make user based restores easier xbmcvfs.copy(self.settingsFile, xbmc.translatePath("special://home/userdata/guisettings.xml.restored"))
def setup_subs(self, label, path): iterator = 0 subs = self.torrent.getSubsIds(label) # print str(subs) if len(subs) > 0: showMessage(Localization.localize('Information'), Localization.localize('Downloading and copy subtitles. Please wait.'), forced=True) for ind, title in subs: self.torrent.continueSession(ind) while iterator < 100: xbmc.sleep(1000) self.torrent.debug() status = self.torrent.torrentHandle.status() iterator = int(status.progress * 100) # xbmc.sleep(2000) for ind, title in subs: folder = title.split(os.sep)[0] temp = os.path.basename(title) addition = os.path.dirname(title).lstrip(folder + os.sep).replace(os.sep, '.').replace(' ', '_').strip() ext = temp.split('.')[-1] temp = temp[:len(temp) - len(ext) - 1] + '.' + addition + '.' + ext newFileName = os.path.join(os.path.dirname(path), temp) # print str((os.path.join(os.path.dirname(os.path.dirname(path)),title),newFileName)) if not xbmcvfs.exists(newFileName): xbmcvfs.copy(os.path.join(os.path.dirname(os.path.dirname(path)), title), newFileName)
def HubSwap(): # Swap Org/Hub versions if 'Hub Installer' found. xbmc.log('script.pseudotv.live-service: HubSwap') try:#unknown Amazon firetv error encountered here, requires investigation icon = ADDON_PATH + '/icon' HUB = chanlist.plugin_ok('plugin.program.addoninstaller') if HUB == True: xbmc.log('script.pseudotv.live-service: HubSwap - Hub Edition') REAL_SETTINGS.setSetting("Hub","true") try: xbmcvfs.delete(icon + '.png') except: pass try: xbmcvfs.copy(icon + 'HUB', icon + '.png') except: pass if NOTIFY == 'true': xbmc.executebuiltin("Notification( %s, %s, %d, %s)" % ("PseudoTV Live","Hub-Edition Activated", 4000, THUMB) ) else: xbmc.log('script.pseudotv.live-service: HubSwap - Master') REAL_SETTINGS.setSetting("Hub","false") try: xbmcvfs.delete(icon + '.png') except: pass try: xbmcvfs.copy(icon + 'OEM', icon + '.png') except: pass except: REAL_SETTINGS.setSetting("Hub","false") pass
def Transform(): if addon.get_setting('transform') == 'true': return if xbmcvfs.exists(xbmc.translatePath('special://masterprofile/sources.xml')): with open(xbmc.translatePath(os.path.join( addon.get_path(), 'resources', 'sourcesapp.xml'))) as f: sourcesapp = f.read() f.close() with open(xbmc.translatePath('special://masterprofile/sources.xml'), 'r+') as f: my_file = f.read() if re.search(r'http://transform.mega-tron.tv/', my_file): addon.log('Transform Source Found in sources.xml, Not adding.') return addon.log('Adding Transform source in sources.xml') my_file = re.split(r'</files>\n</sources>\n', my_file) my_file = my_file[0]+sourcesapp f.seek(0) f.truncate() f.write(my_file) f.close() Addon.setSetting(id='transform', value='true') else: xbmcvfs.copy(xbmc.translatePath(os.path.join( addon.get_path(), 'resources', 'sources.xml')), xbmc.translatePath('special://masterprofile/sources.xml')) Addon.setSetting(id='transform', value='true')
def _handle_compressed_subs(workdir, compressed_file, ext): """ Uncompress 'compressed_file' in 'workdir'. """ if ext == 'rar' and kodi_major_version >= 18: src = 'archive' + '://' + quote_plus(compressed_file) + '/' (cdirs, cfiles) = xbmcvfs.listdir(src) for cfile in cfiles: fsrc = '%s%s' % (src, cfile) xbmcvfs.copy(fsrc, workdir + cfile) else: xbmc.executebuiltin("XBMC.Extract(%s, %s)" % ( compressed_file.encode("utf-8"), workdir.encode("utf-8")), True) files = os.listdir(workdir) files = [f for f in files if is_subs_file(f)] found_files = [] for fname in files: if not isinstance(fname, unicode): fname = fname.decode('utf-8') found_files.append({ 'forced': is_forced_subs_file(fname), 'path': pjoin(workdir, fname) }) if not found_files: log(u"Failed to unpack subtitles", level=LOGSEVERE) return found_files
def restoreColorTheme(): import shutil import zipfile zip_path = None userThemesPath = os.path.join(userThemesDir,"themes") + os.sep zip_path = get_browse_dialog(dlg_type=1,heading=ADDON.getLocalizedString(32020),mask=".zip") if zip_path and zip_path != "protocol://": #create temp path temp_path = xbmc.translatePath('special://temp/skinbackup/').decode("utf-8") if xbmcvfs.exists(temp_path): shutil.rmtree(temp_path) xbmcvfs.mkdir(temp_path) #unzip to temp if "\\" in zip_path: delim = "\\" else: delim = "/" zip_temp = xbmc.translatePath('special://temp/' + zip_path.split(delim)[-1]).decode("utf-8") xbmcvfs.copy(zip_path,zip_temp) zfile = zipfile.ZipFile(zip_temp) zfile.extractall(temp_path) zfile.close() xbmcvfs.delete(zip_temp) dirs, files = xbmcvfs.listdir(temp_path) for file in files: if file.endswith(".theme") or file.endswith(".jpg"): sourcefile = os.path.join(temp_path,file) destfile = os.path.join(userThemesPath,file) xbmcvfs.copy(sourcefile,destfile) xbmcgui.Dialog().ok(ADDON.getLocalizedString(32022), ADDON.getLocalizedString(32021))
def downloadURL(self,targetdir,url,fname=None,final_target_dir=None): if not fname: fname = os.path.basename(urlparse.urlsplit(url)[2]) if not fname: fname = 'file' f,e = os.path.splitext(fname) fn = f ct=0 while ct < 1000: ct += 1 path = os.path.join(targetdir,fn + e) finalPath = os.path.join(final_target_dir,fn + e) if not xbmcvfs.exists(path): break fn = f + str(ct) else: raise Exception try: self.current = 0 self.display = '{0}: {1}'.format(T(32100),os.path.basename(path)) self.prog.update(0,self.message,self.display) t,ftype = self.getUrlFile(url,path,callback=self.progCallback) #@UnusedVariable except: ERROR('DOWNLOAD URL ERROR') self.prog.close() return (None,'') finally: self.prog.close() if final_target_dir: xbmcvfs.copy(path,finalPath) xbmcvfs.delete(path) return (os.path.basename(path),ftype)
def save_skin_image(self, skinstring="", multi_image=False, header=""): '''let the user select an image and save it to addon_data for easy backup''' cur_value = xbmc.getInfoLabel("Skin.String(%s)" % skinstring).decode("utf-8") cur_value_org = xbmc.getInfoLabel("Skin.String(%s.org)" % skinstring).decode("utf-8") if not multi_image: # single image (allow copy to addon_data) value = xbmcgui.Dialog().browse(2, header, 'files', '', True, True, cur_value_org).decode("utf-8") if value: ext = value.split(".")[-1] newfile = (u"special://profile/addon_data/%s/custom_images/%s.%s" % (xbmc.getSkinDir(), skinstring + time.strftime("%Y%m%d%H%M%S", time.gmtime()), ext)) if "special://profile/addon_data/%s/custom_images/" % xbmc.getSkinDir() in cur_value: xbmcvfs.delete(cur_value) xbmcvfs.copy(value, newfile) xbmc.executebuiltin("Skin.SetString(%s.org,%s)" % (skinstring.encode("utf-8"), value.encode("utf-8"))) value = newfile else: # multi image if not cur_value_org.startswith("$"): delim = "\\" if "\\" in cur_value_org else "/" curdir = cur_value_org.rsplit(delim, 1)[0] + delim else: curdir = "" value = xbmcgui.Dialog().browse(0, self.addon.getLocalizedString(32005), 'files', '', True, True, curdir).decode("utf-8") return value
def copyNode(self, dirs, files, target, origin): for file in files: xbmcvfs.copy( os.path.join( origin, file ), os.path.join( target, file ) ) for dir in dirs: nextDirs, nextFiles = xbmcvfs.listdir( os.path.join( origin, dir ) ) self.copyNode( nextDirs, nextFiles, os.path.join( target, dir ), os.path.join( origin, dir ) )
def _copy_albumthumbs( self ): count = 0 processeditems = 0 json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "AudioLibrary.GetAlbums", "params": {"properties": ["title", "thumbnail", "artist"]}, "id": 1}') json_query = unicode(json_query, 'utf-8', errors='ignore') json_response = json.loads(json_query) if json_response.has_key('result') and (json_response['result'] != None) and (json_response['result'].has_key('albums')): totalitems = len( json_response['result']['albums'] ) for item in json_response['result']['albums']: if self.dialog.iscanceled(): log('script cancelled') return processeditems = processeditems + 1 self.dialog.update( int( float( processeditems ) / float( totalitems ) * 100), LANGUAGE(32011) + ': ' + str( count + 1 ) ) name = item['title'] artist = item['artist'][0] artwork = item['thumbnail'] tmp_filename = artist + ' - ' + name + '.jpg' filename = clean_filename( tmp_filename ) if artwork != '': try: xbmcvfs.copy( xbmc.translatePath( artwork ), os.path.join( self.albumthumbspath, filename ) ) count += 1 except: log( 'failed to copy albumthumb' ) log( 'albumthumbs copied: %s' % count )
def _copy_musicvideothumbs( self ): count = 0 processeditems = 0 json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.GetMusicVideos", "params": {"properties": ["title", "thumbnail", "artist"], "filter": {"field": "path", "operator": "contains", "value": "%s"}}, "id": 1}' % self.path) json_query = unicode(json_query, 'utf-8', errors='ignore') json_response = json.loads(json_query) if json_response.has_key('result') and (json_response['result'] != None) and (json_response['result'].has_key('musicvideos')): totalitems = len( json_response['result']['musicvideos'] ) for item in json_response['result']['musicvideos']: if self.dialog.iscanceled(): log('script cancelled') return processeditems = processeditems + 1 self.dialog.update( int( float( processeditems ) / float( totalitems ) * 100), LANGUAGE(32009) + ': ' + str( count + 1 ) ) name = item['title'] artwork = item['thumbnail'] if item['artist']: # bug workaround, musicvideos can end up in the database without an artistname artist = item['artist'][0] tmp_filename = artist + ' - ' + name + '.jpg' else: tmp_filename = name + '.jpg' filename = clean_filename( tmp_filename ) if artwork != '': try: xbmcvfs.copy( xbmc.translatePath( artwork ), os.path.join( self.musicvideothumbspath, filename ) ) count += 1 except: log( 'failed to copy musicvideothumb' ) log( 'musicvideothumbs copied: %s' % count )
def nestedCopy(rootSourceDir, rootTargetDir): log("nestedCopy: Copy %s to %s" % (rootSourceDir, rootTargetDir)) # Make sure the target directory exists xbmcvfs.mkdirs(rootTargetDir) dirs, files = xbmcvfs.listdir(rootSourceDir) for file in files: try: file = file.decode("utf-8") except: pass sourceFile = "%s%s" % (rootSourceDir, file) targetFile = "%s%s" % (rootTargetDir, file) log("nestedCopy: Copy file %s to %s" % (sourceFile, targetFile)) xbmcvfs.copy(sourceFile, targetFile) for adir in dirs: try: adir = adir.decode("utf-8") except: pass sourceDir = "%s%s/" % (rootSourceDir, adir) targetDir = "%s%s/" % (rootTargetDir, adir) log("nestedCopy: Copy directory %s to %s" % (sourceDir, targetDir)) nestedCopy(sourceDir, targetDir)
def ffmpeg_location(): ffmpeg_src = xbmc.translatePath(ADDON.getSetting('autoplaywiths.ffmpeg')) if xbmc.getCondVisibility('system.platform.android'): ffmpeg_dst = '/data/data/%s/ffmpeg' % android_get_current_appid() if (ADDON.getSetting('autoplaywiths.ffmpeg') != ADDON.getSetting('ffmpeg.last')) or (not xbmcvfs.exists(ffmpeg_dst) and ffmpeg_src != ffmpeg_dst): xbmcvfs.copy(ffmpeg_src, ffmpeg_dst) ADDON.setSetting('ffmpeg.last',ADDON.getSetting('autoplaywiths.ffmpeg')) ffmpeg = ffmpeg_dst else: ffmpeg = ffmpeg_src log(ffmpeg) if ffmpeg: try: st = os.stat(ffmpeg) if not (st.st_mode & stat.S_IXUSR): log(st) try: os.chmod(ffmpeg, st.st_mode | stat.S_IXUSR) except Exception as e: log(e) except Exception as e: log(e) if xbmcvfs.exists(ffmpeg): return ffmpeg else: xbmcgui.Dialog().notification("TVGF", "ffmpeg exe not found!")
def parser_check(): dirs,files = xbmcvfs.listdir(base_dir) if not dirs: dirpackages,filespackages = xbmcvfs.listdir(parser_packages_folder) if filespackages: for fich in filespackages: shutil.copyfile(os.path.join(parser_packages_folder,fich), os.path.join(parser_core_folder,fich)) xbmc.sleep(100) import tarfile if tarfile.is_tarfile(os.path.join(parser_core_folder,fich)): download_tools().extract(os.path.join(parser_core_folder,fich),parser_core_folder) download_tools().remove(os.path.join(parser_core_folder,fich)) else: dirsuserdata,files = xbmcvfs.listdir(parser_folder) for fich in files: dictionary_module = eval(readfile(os.path.join(parser_folder,fich))) if "url" in dictionary_module.keys(): add_new_parser(dictionary_module["url"]) else: xbmcvfs.copy(os.path.join(parser_packages_folder,fich.replace('.txt','.tar.gz')),os.path.join(parser_core_folder,fich.replace('.txt','.tar.gz'))) import tarfile if tarfile.is_tarfile(os.path.join(parser_core_folder,fich.replace('.txt','.tar.gz'))): download_tools().extract(os.path.join(parser_core_folder,fich.replace('.txt','.tar.gz')),parser_core_folder) download_tools().remove(os.path.join(parser_core_folder,fich.replace('.txt','.tar.gz'))) else: pass return
def create_color_swatch_image(self, colorstring): '''helper method to generate a colorized image using PIL''' if colorstring: paths = [] paths.append(u"%s%s.png" % (COLORFILES_PATH, colorstring)) if xbmcvfs.exists(SKINCOLORFILE): paths.append(u"%s%s.png" % (SKINCOLORFILES_PATH, colorstring)) for color_image_file in paths: if not xbmcvfs.exists(color_image_file): if SUPPORTS_PIL: # create image with PIL try: colorstring = colorstring.strip() if colorstring[0] == '#': colorstring = colorstring[1:] a, r, g, b = colorstring[:2], colorstring[2:4], colorstring[4:6], colorstring[6:] a, r, g, b = [int(n, 16) for n in (a, r, g, b)] color = (r, g, b, a) img = Image.new("RGBA", (16, 16), color) img.save(color_image_file) del img except Exception as exc: log_exception(__name__, exc) else: # create image with online service if no pil support xbmcvfs.copy( "https://dummyimage.com/16/%s/%s.png" % (colorstring[2:],colorstring[2:]), color_image_file ) log_msg("Local PIL module not available, generating color swatch image with online service", xbmc.LOGWARNING) return color_image_file
def _copy_episodethumbs( self ): count = 0 processeditems = 0 json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodes", "params": {"properties": ["file", "title", "thumbnail", "season", "episode", "showtitle"], "filter": {"field": "path", "operator": "contains", "value": "%s"}}, "id": 1}' % self.path) json_query = unicode(json_query, 'utf-8', errors='ignore') json_response = json.loads(json_query) if json_response.has_key('result') and (json_response['result'] != None) and (json_response['result'].has_key('episodes')): totalitems = len( json_response['result']['episodes'] ) for item in json_response['result']['episodes']: if self.dialog.iscanceled(): log('script cancelled') return processeditems = processeditems + 1 self.dialog.update( int( float( processeditems ) / float( totalitems ) * 100), LANGUAGE(32008) + ': ' + str( count + 1 ) ) name = item['title'] tvshow = item['showtitle'] artwork = item['thumbnail'] season = item['season'] episode = item['episode'] episodenumber = "s%.2d%.2d" % (int( season ), int( episode )) tmp_filename = tvshow + ' - ' + episodenumber + ' - ' + name + '.jpg' filename = clean_filename( tmp_filename ) # test file path with tv_content to find source name episodethumbspath = self.episodethumbspath if self.split_tvshows_sources == "true" and self.tvshows_content.has_key(str(item['file'])): episodethumbspath = os.path.join( self.episodethumbspath, self.tvshows_content[str(item['file'])]) if artwork != '': try: xbmcvfs.copy( xbmc.translatePath( artwork ), os.path.join( episodethumbspath, filename ) ) count += 1 except: log( 'failed to copy episodethumb' ) log( 'episodethumbs copied: %s' % count )
def VideoWindow(): log("VideoWindow, VWPath = " + str(VWPath)) FreshInstall = False #Copy VideoWindow Patch file try: if xbmcgui.Window(10000).getProperty("PseudoTVRunning") != "True": if not FileAccess.exists(VWPath): log("VideoWindow, VWPath not found") FreshInstall = True xbmcvfs.copy(flePath, VWPath) if FileAccess.exists(VWPath): log('custom_script.pseudotv.live_9506.xml Copied') VideoWindowPatch() if FreshInstall == True: xbmc.executebuiltin("ReloadSkin()") else: raise else: log("VideoWindow, VWPath found") VideoWindowPatch() except Exception: VideoWindowUninstall() VideoWindowUnpatch() Error = True pass
def _copy_tvshowposters( self ): count = 0 processeditems = 0 json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.GetTVShows", "params": {"properties": ["file", "title", "art"], "filter": {"field": "path", "operator": "contains", "value": "%s"}}, "id": 1}' % self.path) json_query = unicode(json_query, 'utf-8', errors='ignore') json_response = json.loads(json_query) if json_response.has_key('result') and (json_response['result'] != None) and (json_response['result'].has_key('tvshows')): totalitems = len( json_response['result']['tvshows'] ) for item in json_response['result']['tvshows']: if self.dialog.iscanceled(): log('script cancelled') return processeditems = processeditems + 1 self.dialog.update( int( float( processeditems ) / float( totalitems ) * 100), LANGUAGE(32014) + ': ' + str( count + 1 ) ) name = item['title'] artwork = item['art'].get('poster') tmp_filename = name + '.jpg' filename = clean_filename( tmp_filename ) # test file path with tv_content to find source name tvshowposterspath = self.tvshowposterspath if self.split_tvshows_sources == "true": for tv_file_path, source_name in self.tvshows_content.items(): if tv_file_path.startswith(item['file']): tvshowposterspath = os.path.join( self.tvshowposterspath, source_name ) break if artwork != '': try: xbmcvfs.copy( xbmc.translatePath( artwork ), os.path.join( tvshowposterspath, filename ) ) count += 1 except: log( 'failed to copy tvshowposter' ) log( 'tvshowposters copied: %s' % count )
def Filter_Fakelight(filterimage, pixels): md5 = hashlib.md5(filterimage).hexdigest() filename = md5 + "fakelight" + str(pixels) + ".png" targetfile = os.path.join(ADDON_DATA_PATH, filename) cachedthumb = xbmc.getCacheThumbName(filterimage) xbmc_vid_cache_file = os.path.join("special://profile/Thumbnails/Video", cachedthumb[0], cachedthumb) xbmc_cache_file = os.path.join("special://profile/Thumbnails/", cachedthumb[0], cachedthumb[:-4] + ".jpg") if filterimage == "": return "" if not xbmcvfs.exists(targetfile): img = None for i in range(1, 4): try: if xbmcvfs.exists(xbmc_cache_file): img = Image.open(xbmc.translatePath(xbmc_cache_file)) break elif xbmcvfs.exists(xbmc_vid_cache_file): img = Image.open(xbmc.translatePath(xbmc_vid_cache_file)) break else: filterimage = urllib.unquote(filterimage.replace("image://", "")).decode('utf8') if filterimage.endswith("/"): filterimage = filterimage[:-1] xbmcvfs.copy(filterimage, targetfile) img = Image.open(targetfile) break except: xbmc.sleep(300) if not img: return "" img = fake_light(img,pixels) img.save(targetfile) return targetfile
def getRealFileName(filename, isTemp=False): #get the filename path accessible by python if possible... if not xbmcvfs.exists(filename): log.warn("File does not exist! %s" % filename) return (False, "") #if we use os.path method on older python versions (sunch as some android builds), we need to pass arguments as string if os.path.supports_unicode_filenames: checkfile = filename else: checkfile = filename.encode("utf-8") # determine if our python module is able to access the file directly... if os.path.exists(checkfile): filename = filename elif os.path.exists(checkfile.replace("smb://","\\\\").replace("/","\\")): filename = filename.replace("smb://","\\\\").replace("/","\\") else: #file can not be accessed by python directly, we copy it for processing... isTemp = True if "/" in filename: filepart = filename.split("/")[-1] else: filepart = filename.split("\\")[-1] tempfile = "special://temp/"+filepart xbmcvfs.copy(filename, tempfile) filename = xbmc.translatePath(tempfile).decode("utf-8") return (isTemp,filename)
def getExtraFanArt(embyId,embyPath): emby = embyserver.Read_EmbyServer() art = artwork.Artwork() # Get extrafanart for listitem # will be called by skinhelper script to get the extrafanart try: # for tvshows we get the embyid just from the path if not embyId: if "plugin.video.emby" in embyPath: embyId = embyPath.split("/")[-2] if embyId: #only proceed if we actually have a emby id utils.logMsg("EMBY", "Requesting extrafanart for Id: %s" % embyId, 0) # We need to store the images locally for this to work # because of the caching system in xbmc fanartDir = xbmc.translatePath("special://thumbnails/emby/%s/" % embyId).decode('utf-8') if not xbmcvfs.exists(fanartDir): # Download the images to the cache directory xbmcvfs.mkdirs(fanartDir) item = emby.getItem(embyId) if item: backdrops = art.getAllArtwork(item)['Backdrop'] tags = item['BackdropImageTags'] count = 0 for backdrop in backdrops: # Same ordering as in artwork tag = tags[count] if os.path.supports_unicode_filenames: fanartFile = os.path.join(fanartDir, "fanart%s.jpg" % tag) else: fanartFile = os.path.join(fanartDir.encode("utf-8"), "fanart%s.jpg" % tag.encode("utf-8")) li = xbmcgui.ListItem(tag, path=fanartFile) xbmcplugin.addDirectoryItem( handle=int(sys.argv[1]), url=fanartFile, listitem=li) xbmcvfs.copy(backdrop, fanartFile) count += 1 else: utils.logMsg("EMBY", "Found cached backdrop.", 2) # Use existing cached images dirs, files = xbmcvfs.listdir(fanartDir) for file in files: fanartFile = os.path.join(fanartDir, file.decode('utf-8')) li = xbmcgui.ListItem(file, path=fanartFile) xbmcplugin.addDirectoryItem( handle=int(sys.argv[1]), url=fanartFile, listitem=li) except Exception as e: utils.logMsg("EMBY", "Error getting extrafanart: %s" % e, 0) # Always do endofdirectory to prevent errors in the logs xbmcplugin.endOfDirectory(int(sys.argv[1]))
def enable(self): try: xbmcvfs.copy(self.KEYMAPSOURCEFILE, self.KEYMAPDESTFILE) self.keymapCopied = True xbmc.executebuiltin('Action(reloadkeymaps)') log("KeyMaps: Installed custom keymap") except: log("KeyMaps: Failed to copy & load custom keymap: %s" % traceback.format_exc(), xbmc.LOGERROR)
def copyKeyboardModImages(skinPath): dst = os.path.join(skinPath,'media','forum-browser-keyboard') #if os.path.exists(dst): return if not os.path.exists(dst): os.makedirs(dst) src = os.path.join(xbmc.translatePath(__addon__.getAddonInfo('path')),'keyboard','images') for f in os.listdir(src): s = os.path.join(src,f) d = os.path.join(dst,f) if not os.path.exists(d) and not f.startswith('.'): xbmcvfs.copy(s,d)
def backup(self, filters=None, backup_file="", silent=False): '''create skin backup''' if not filters: filters = [] if not backup_file: return # create temp path temp_path = self.create_temp() # backup skinshortcuts preferences if not filters or (filters and "skinshortcuts" in filters): self.backup_skinshortcuts(temp_path + "skinshortcuts/") # backup skin settings if "skinshortcutsonly" not in filters: skinsettings_path = os.path.join(temp_path, u"guisettings.txt") self.backup_skinsettings(skinsettings_path, filters, temp_path) # zip the backup zip_temp = u'special://temp/skinbackup-%s.zip' % datetime.now( ).strftime('%Y-%m-%d %H.%M') zip_temp = xbmc.translatePath(zip_temp).decode("utf-8") zip_tofile(temp_path, zip_temp) # copy to final location if xbmcvfs.exists(backup_file): xbmcvfs.delete(backup_file) xbmcvfs.copy(zip_temp, backup_file) # cleanup temp recursive_delete_dir(temp_path) xbmcvfs.delete(zip_temp) # show success message if not silent: xbmcgui.Dialog().ok(self.addon.getLocalizedString(32004), self.addon.getLocalizedString(32005))
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): xbmcvfs.copy(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 setup_subs(self, label, path): iterator = 0 subs = self.torrent.getSubsIds(label) debug('[setup_subs] subs: ' + str(subs)) if len(subs) > 0: self.torrent.startSession() showMessage( self.localize('Information'), self.localize('Downloading and copy subtitles. Please wait.')) for ind, title in subs: self.torrent.continueSession(ind) while iterator < 100: xbmc.sleep(1000) self.torrent.debug() status = self.torrent.torrentHandle.status() iterator = int(status.progress * 100) # xbmc.sleep(2000) for ind, title in subs: folder = title.split(os.sep)[0] temp = os.path.basename(title) addition = os.path.dirname(title).lstrip(folder + os.sep).replace( os.sep, '.').replace( ' ', '_').strip() ext = temp.split('.')[-1] temp = temp[:len(temp) - len(ext) - 1] + '.' + addition + '.' + ext newFileName = os.path.join( ensure_str(os.path.dirname(decode_str(path))), ensure_str(temp)) debug('[setup_subs]: {} {}'.format(newFileName, title)) if not xbmcvfs.exists(newFileName): fileName = os.path.join( ensure_str( os.path.dirname(os.path.dirname( decode_str(path)))), ensure_str(title)) xbmcvfs.copy(fileName, newFileName)
def applyID3(self): if ADDON.getSetting('keep_downloads')=='false': return if not xbmcvfs.exists(self.filename): return if self.track < 1: return log('Applying ID3 tags to %s' % self.title) temp = self.filename.rsplit(os.sep, 1)[-1] temp = os.path.join(TEMP, temp) doCopy = self.filename != temp if doCopy: xbmcvfs.copy(self.filename, temp) #Remove track number from title title=self.title try: title=title[title.find('. ')+2:] except: title=title audio = MP3(temp, ID3=EasyID3) audio['title'] = title audio['artist'] = self.artist audio['album'] = self.album audio['tracknumber'] = str(self.track) audio['date'] = '' audio['genre'] = '' audio.save(v1=2) log(audio.pprint()) if doCopy: del audio deleteFile(self.filename) xbmcvfs.copy(temp, self.filename) deleteFile(temp)
def emby_backup(): # Create a backup at specified location path = settings('backupPath') # filename default_value = "Kodi%s.%s" % (xbmc.getInfoLabel('System.BuildVersion')[:2], xbmc.getInfoLabel('System.Date(dd-mm-yy)')) folder_name = dialog(type_="input", heading=lang(33089), defaultt=default_value) if not folder_name: return backup = os.path.join(path, folder_name) log.info("Backup: %s", backup) # Create directory if xbmcvfs.exists(backup+"\\"): log.info("Existing directory!") if not dialog(type_="yesno", heading="{emby}", line1=lang(33090)): return emby_backup() shutil.rmtree(backup) # Addon_data addon_data = xbmc.translatePath("special://profile/addon_data/emby.for.kodi").decode('utf-8') try: shutil.copytree(src=addon_data, dst=os.path.join(backup, "addon_data", "emby.for.kodi")) except shutil.Error as error: log.error(error) # Database files database_folder = os.path.join(backup, "Database") if not xbmcvfs.mkdir(database_folder): try: os.makedirs(database_folder) except OSError as error: log.error(error) dialog(type_="ok", heading="{emby}", line1="Failed to create backup") return # Emby database emby_path = database.emby_database() xbmcvfs.copy(emby_path, os.path.join(database_folder, ntpath.basename(emby_path))) # Videos database video_path = database.video_database() xbmcvfs.copy(video_path, os.path.join(database_folder, ntpath.basename(video_path))) # Music database if settings('enableMusic') == "true": music_path = database.music_database() xbmcvfs.copy(music_path, os.path.join(database_folder, ntpath.basename(music_path))) dialog(type_="ok", heading="{emby}", line1="%s: %s" % (lang(33091), backup))
def copy_files( self, subtitle_file, file_path ): subtitle_set = False try: if VFS: xbmcvfs.copy(subtitle_file, file_path) log( __name__ ,"vfs module copy %s -> %s" % (subtitle_file, file_path)) else: shutil.copy(subtitle_file, file_path) subtitle_set = True except : import filecmp try: if filecmp.cmp(subtitle_file, file_path): subtitle_set = True except: dialog = xbmcgui.Dialog() selected = dialog.yesno( __scriptname__ , _( 748 ), _( 750 ),"" ) if selected == 1: file_path = subtitle_file subtitle_set = True return subtitle_set, file_path
def Check_XBMC_Internal(targetfile, filterimage): cachedthumb = xbmc.getCacheThumbName(filterimage) xbmc_vid_cache_file = os.path.join("special://profile/Thumbnails/Video", cachedthumb[0], cachedthumb) xbmc_cache_filep = os.path.join("special://profile/Thumbnails/", cachedthumb[0], cachedthumb[:-4] + ".jpg") xbmc_cache_filej = os.path.join("special://profile/Thumbnails/", cachedthumb[0], cachedthumb[:-4] + ".png") if xbmcvfs.exists(xbmc_cache_filej): return xbmc.translatePath(xbmc_cache_filej) elif xbmcvfs.exists(xbmc_cache_filep): return xbmc.translatePath(xbmc_cache_filep) elif xbmcvfs.exists(xbmc_vid_cache_file): return xbmc.translatePath(xbmc_vid_cache_file) else: filterimage = urllib.unquote(filterimage.replace("image://", "")).decode('utf8') if filterimage.endswith("/"): filterimage = filterimage[:-1] xbmcvfs.copy(filterimage, targetfile) return targetfile return
def copy_guide_to_destination(): done = xbmcvfs.copy(guide_temp, guide_dest) if done == True: xbmc.sleep(3000) notify(addon_name, loc(32350), icon=xbmcgui.NOTIFICATION_INFO) log(loc(32350), xbmc.LOGNOTICE) ## Write new setting last_download with open(grabber_cron, 'r') as f: data = json.load(f) data['last_download'] = str(int(time.time())) with open(grabber_cron_tmp, 'w') as f: json.dump(data, f, indent=4) ## rename temporary file replacing old file xbmcvfs.copy(grabber_cron_tmp, grabber_cron) xbmcvfs.delete(grabber_cron_tmp) f.close() else: notify(addon_name, loc(32351), icon=xbmcgui.NOTIFICATION_ERROR) log(loc(32351), xbmc.LOGERROR)
def VideoWindow(): log("VideoWindow, VWPath = " + str(VWPath)) #Copy VideoWindow Patch file try: if xbmcgui.Window(10000).getProperty("PseudoTVRunning") != "True": if not xbmcvfs.exists(VWPath): log("VideoWindow, VWPath not found") FreshInstall = True xbmcvfs.copy(flePath, VWPath) if xbmcvfs.exists(VWPath): log('custom_script.pseudotv.lite_9506.xml Copied') VideoWindowPatch() else: raise else: log("VideoWindow, VWPath found") VideoWindowPatch() except Exception: VideoWindowUninstall() VideoWindowUnpatch() Error = True pass
def extractCoverImage(self): if self.book is None: return None coverTargetName = None try: # Get the cover for the book from the eBook file coverItem = self.bookFile.get_item('cover') # Make sure the cover found is not the text linking to it if coverItem is not None: if '.htm' in coverItem.href: coverItem = None if coverItem is None: # No cover found yet, try again coverItem = self.bookFile.get_item('cover-image') if coverItem is not None: if '.htm' in coverItem.href: coverItem = None if coverItem is None: # No cover found yet, try again coverItem = self.bookFile.get_item('cover-jpg') if coverItem is not None: if '.htm' in coverItem.href: coverItem = None if coverItem is not None: # Check the name of the cover file, as we want to know the extension oldCoverName, newExt = os.path.splitext(coverItem.href) coverFileName, oldExt = os.path.splitext(self.fileName) cacheCoverName = "%s%s" % (coverFileName, newExt) coverTargetName = os_path_join(Settings.getCoverCacheLocation(), cacheCoverName) # Extract the cover to the temp target - it will get the same name as in # the compressed file extractedFile = self.bookFile.extract_item(coverItem, Settings.getTempLocation()) log("EPubEBook: Extracted cover to: %s" % extractedFile) # Now move the file to the covers cache directory copy = xbmcvfs.copy(extractedFile, coverTargetName) if copy: log("EPubEBook: copy successful for %s" % coverTargetName) else: log("EPubEBook: copy failed from %s to %s" % (extractedFile, coverTargetName)) xbmcvfs.delete(extractedFile) except: log("EPubEBook: Failed to get cover for %s with error: %s" % (self.filePath, traceback.format_exc()), xbmc.LOGERROR) return coverTargetName
def getUpdate(data=None): if data is None: url = 'http://community-links.googlecode.com/svn/trunk/' data = makeRequest(url) soup = BeautifulSoup(data, convertEntities=BeautifulSoup.HTML_ENTITIES) files = soup('ul')[0]('li')[1:] try: R = open(REV, "w") R.write(data) R.close() except: print "there was a problem writing REV to profile." for i in files: name = i('a')[0]['href'] url = 'http://community-links.googlecode.com/svn/trunk/' + name link = makeRequest(url) if not xbmcvfs.exists(addon.getSetting('save_location')): success = xbmcvfs.mkdir(addon.getSetting('save_location')) save_location = addon.getSetting('save_location').decode('utf-8') if 'smb:' in save_location: file_name = xbmc.makeLegalFilename( os.path.join(profile, 'temp', name)) f = open(os.path.join(profile, 'temp', name), "w") f.write(link) f.close() copy = xbmcvfs.copy(os.path.join(profile, 'temp', name), os.path.join(save_location, name)) if copy: xbmcvfs.delete( xbmc.translatePath(os.path.join(profile, 'temp', name))) else: print '------ Error smb: makeLegalFilename -----' else: try: file_name = xbmc.makeLegalFilename( os.path.join(save_location, name)) f = open(os.path.join(save_location, name), "w") f.write(link) f.close() except: print "there was a problem writing to save location." return if not xbmcvfs.exists(os.path.join(profile, 'update_time')): xbmc.makeLegalFilename(os.path.join(profile, 'update_time')) u = open(update_time, "w") u.write(str(datetime.datetime.now())) u.close() print 'Update Time: ' + str(datetime.datetime.now()) xbmc.executebuiltin( "XBMC.Notification(LiveStreams,Community Lists Updated,5000," + icon + ")")
def save_skin_image(self, skinstring="", multi_image=False, header=""): '''let the user select an image and save it to addon_data for easy backup''' cur_value = try_decode( xbmc.getInfoLabel("Skin.String(%s)" % skinstring)) cur_value_org = try_decode( xbmc.getInfoLabel("Skin.String(%s.org)" % skinstring)) if not multi_image: # single image (allow copy to addon_data) value = try_decode(xbmcgui.Dialog().browse(2, header, 'files', '', True, True, cur_value_org)) if value: ext = value.split(".")[-1] newfile = ( "special://profile/addon_data/%s/custom_images/%s.%s" % (xbmc.getSkinDir(), skinstring + time.strftime("%Y%m%d%H%M%S", time.gmtime()), ext)) if "special://profile/addon_data/%s/custom_images/" % xbmc.getSkinDir( ) in cur_value: xbmcvfs.delete(cur_value) xbmcvfs.copy(value, newfile) xbmc.executebuiltin( "Skin.SetString(%s.org,%s)" % (try_encode(skinstring), try_encode(value))) value = newfile else: # multi image if not cur_value_org.startswith("$"): delim = "\\" if "\\" in cur_value_org else "/" curdir = cur_value_org.rsplit(delim, 1)[0] + delim else: curdir = "" value = try_decode(xbmcgui.Dialog().browse( 0, self.addon.getLocalizedString(32005), 'files', '', True, True, curdir)) return value
def HubSwap(): # Swap Org/Hub versions if 'Hub Installer' found. xbmc.log('script.pseudotv.live-service: HubSwap') try: #unknown Amazon firetv error encountered here, requires investigation icon = ADDON_PATH + '/icon' HUB = chanlist.plugin_ok('plugin.program.addoninstaller') if HUB == True: xbmc.log('script.pseudotv.live-service: HubSwap - Hub Edition') if REAL_SETTINGS.getSetting('Hub') == 'false': if NOTIFY == 'true': xbmc.executebuiltin("Notification( %s, %s, %d, %s)" % ("PseudoTV Live", "Hub-Edition Activated", 4000, THUMB)) REAL_SETTINGS.setSetting("Hub", "true") try: xbmcvfs.delete(icon + '.png') except: pass try: xbmcvfs.copy(icon + 'HUB', icon + '.png') except: pass else: xbmc.log('script.pseudotv.live-service: HubSwap - Master') REAL_SETTINGS.setSetting("Hub", "false") try: xbmcvfs.delete(icon + '.png') except: pass try: xbmcvfs.copy(icon + 'OEM', icon + '.png') except: pass except: REAL_SETTINGS.setSetting("Hub", "false") pass
def restoreColorTheme(): import shutil import zipfile zip_path = None userThemesPath = os.path.join(userThemesDir, "themes") + os.sep zip_path = get_browse_dialog(dlg_type=1, heading=ADDON.getLocalizedString(32020), mask=".zip") if zip_path and zip_path != "protocol://": #create temp path temp_path = xbmc.translatePath('special://temp/skinbackup/').decode( "utf-8") if xbmcvfs.exists(temp_path): shutil.rmtree(temp_path) xbmcvfs.mkdir(temp_path) #unzip to temp if "\\" in zip_path: delim = "\\" else: delim = "/" zip_temp = xbmc.translatePath( 'special://temp/' + zip_path.split(delim)[-1]).decode("utf-8") xbmcvfs.copy(zip_path, zip_temp) zfile = zipfile.ZipFile(zip_temp) zfile.extractall(temp_path) zfile.close() xbmcvfs.delete(zip_temp) dirs, files = xbmcvfs.listdir(temp_path) for file in files: if file.endswith(".theme") or file.endswith(".jpg"): sourcefile = os.path.join(temp_path, file) destfile = os.path.join(userThemesPath, file) xbmcvfs.copy(sourcefile, destfile) xbmcgui.Dialog().ok(ADDON.getLocalizedString(32022), ADDON.getLocalizedString(32021))
def __init__(self, name, addon=None, default=None, path=None, connect=True): try: self.mName = name self.mAddon = addon self.mDatabase = None if name == None: name = hashlib.sha256(path).hexdigest().upper() global DatabaseLocks if not name in DatabaseLocks: DatabaseLocks[name] = threading.Lock() self.mLock = DatabaseLocks[name] global DatabaseLocksCustom if not name in DatabaseLocksCustom: DatabaseLocksCustom[name] = threading.Lock() self.mLockCustom = DatabaseLocksCustom[name] if path == None: if not name.endswith(Database.Extension): name += Database.Extension self.mPath = os.path.join( xbmc.translatePath( self._addon().getAddonInfo('profile').decode('utf-8')), name) if default and not xbmcvfs.exists(self.mPath): xbmcvfs.copy(os.path.join(default, name), self.mPath) else: if not path.endswith(Database.Extension): path += Database.Extension self.mPath = path if connect: self._connect() except Exception as error: xbmc.log('GAIA ERROR [Database]: ' + str(error), xbmc.LOGERROR)
def backup(): ''' Emby backup. ''' from helper.utils import delete_folder, copytree path = settings('backupPath') folder_name = "Kodi%s.%s" % (xbmc.getInfoLabel('System.BuildVersion')[:2], xbmc.getInfoLabel('System.Date(dd-mm-yy)')) folder_name = dialog("input", heading=_(33089), defaultt=folder_name) if not folder_name: return backup = os.path.join(path, folder_name) if xbmcvfs.exists(backup + '/'): if not dialog("yesno", heading="{emby}", line1=_(33090)): return backup() delete_folder(backup) addon_data = xbmc.translatePath( "special://profile/addon_data/plugin.video.emby").decode('utf-8') destination_data = os.path.join(backup, "addon_data", "plugin.video.emby") destination_databases = os.path.join(backup, "Database") if not xbmcvfs.mkdirs(path) or not xbmcvfs.mkdirs(destination_databases): LOG.info("Unable to create all directories") dialog("notification", heading="{emby}", icon="{emby}", message=_(33165), sound=False) return copytree(addon_data, destination_data) db = xbmc.translatePath("special://database/").decode('utf-8') dirs, files = xbmcvfs.listdir(db) for Temp in files: if 'MyVideos' in Temp: xbmcvfs.copy(os.path.join(db, Temp), os.path.join(destination_databases, Temp)) LOG.info("copied %s", Temp) elif 'emby' in Temp: xbmcvfs.copy(os.path.join(db, Temp), os.path.join(destination_databases, Temp)) LOG.info("copied %s", Temp) elif 'MyMusic' in Temp: xbmcvfs.copy(os.path.join(db, Temp), os.path.join(destination_databases, Temp)) LOG.info("copied %s", Temp) LOG.info("backup completed") dialog("ok", heading="{emby}", line1="%s %s" % (_(33091), backup))
def _copy_episodethumbs( self ): count = 0 processeditems = 0 json_query = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodes", "params": {"properties": ["file", "title", "thumbnail", "season", "episode", "showtitle"], "filter": {"field": "path", "operator": "contains", "value": "%s"}}, "id": 1}' % self.path) json_query = unicode(json_query, 'utf-8', errors='ignore') json_response = json.loads(json_query) if json_response.has_key('result') and (json_response['result'] != None) and (json_response['result'].has_key('episodes')): totalitems = len( json_response['result']['episodes'] ) for item in json_response['result']['episodes']: if self.dialog.iscanceled(): log('script cancelled') return processeditems = processeditems + 1 self.dialog.update( int( float( processeditems ) / float( totalitems ) * 100), LANGUAGE(32008) + ': ' + str( count + 1 ) ) name = item['title'] tvshow = item['showtitle'] artwork = item['thumbnail'] season = item['season'] episode = item['episode'] episodenumber = "s%.2d%.2d" % (int( season ), int( episode )) tmp_filename = tvshow + ' - ' + episodenumber + ' - ' + name + '.jpg' filename = clean_filename( tmp_filename ) if self.normalize_names == "true": filename = video_library._normalize_string(filename) # test file path with tv_content to find source name episodethumbspath = self.episodethumbspath if self.split_tvshows_sources == "true" and item['file'] in self.tvshows_content: source_name = self.tvshows_content[item['file']] if self.normalize_names == "true": source_name = video_library._normalize_string(source_name) episodethumbspath = os.path.join( self.episodethumbspath, source_name) if artwork != '': try: xbmcvfs.copy( xbmc.translatePath( artwork ), os.path.join( episodethumbspath, filename ) ) count += 1 except: log( 'failed to copy episodethumb' ) log( 'episodethumbs copied: %s' % count )
def copyThumb(self, tbn2="", ignore_errors=0, force=False): ok = False try: tbn1 = "".join(TBN.get_thumb(self.actor["name"])) tbn2 = tbn2 or TBN.BASE_THUMB_PATH + self.actor["thumbs"][0] force = force or (not xbmcvfs.exists(tbn1)) if tbn1 and force and xbmcvfs.exists(tbn2): ok = xbmcvfs.copy(tbn2, tbn1) print "%r xbmcvfs.copy( %r, %r )" % (ok, tbn2, tbn1) except: if not ignore_errors: print_exc() if ok: globals().update({"CONTAINER_REFRESH": True}) return ok
def copyTree(source, target): pct = 0 mod = 5 if not source or not target: return if not os.path.isdir(source): return sourcelen = len(source) if not source.endswith(os.path.sep): sourcelen += 1 for path, dirs, files in os.walk(source): # @UnusedVariable subpath = path[sourcelen:] xbmcvfs.mkdir(os.path.join(target, subpath)) for f in files: xbmcvfs.copy(os.path.join(path, f), os.path.join(target, subpath, f)) pct += mod if pct > 100: pct = 95 mod = -5 elif pct < 0: pct = 5 mod = 5
def thumbnail_copy(art_path, thumb_path, type_="artwork"): if not thumb_path.startswith("http://") or not thumb_path.startswith( "image://"): if xbmcvfs.exists(art_path): if xbmcvfs.copy(art_path, thumb_path): log("Successfully copied %s" % type_, xbmc.LOGDEBUG) else: log("Failed to copy to %s" % type_, xbmc.LOGDEBUG) log("Source Path: %s" % repr(art_path), xbmc.LOGDEBUG) log("Destination Path: %s" % repr(thumb_path), xbmc.LOGDEBUG) elif thumb_path.startswith("http://") or thumb_path.startswith("image://"): log( "Destination Path is not able to be copied to: %s" % repr(thumb_path), xbmc.LOGDEBUG)
def __init__(self, addon, cachePath): super(XMLTVSource, self).__init__(addon, cachePath) self.logoFolder = addon.getSetting('xmltv.logo.folder') self.xmlTvFileLastChecked = datetime.datetime.fromtimestamp(0) self.xmltvFile = addon.getSetting('xmltv.file') if not self.xmltvFile or not xbmcvfs.exists(self.xmltvFile): raise SourceNotConfiguredException() tempFile = os.path.join(self.cachePath, '%s.xmltv.tmp' % self.KEY) xbmc.log('[script.tvguide] Caching XMLTV file...') xbmcvfs.copy(addon.getSetting('xmltv.file'), tempFile) if not os.path.exists(tempFile): raise SourceException('XML TV file was not cached, does it exist?') # if xmlTvFile doesn't exists or the file size is different from tempFile # we copy the tempFile to xmlTvFile which in turn triggers a reload in self._isChannelListCacheExpired(..) if not os.path.exists(self.xmlTvFile) or os.path.getsize( self.xmlTvFile) != os.path.getsize(tempFile): if os.path.exists(self.xmlTvFile): os.unlink(self.xmlTvFile) os.rename(tempFile, self.xmlTvFile)
def download_thumb(self, thumburl, destfilename): log.info("begin download_thumb using requests module: thumburl = %s" % thumburl) # Download file to tmp folder tmp = util.joinPath(util.getTempDir(), os.path.basename(destfilename)) log.info("download_thumb: start downloading to temp file: %s" % tmp) response = requests.get(thumburl, headers=WebScraper._headers, stream=True) log.info("download_thumb: status code = %s" % response.status_code) if response.status_code != 200: log.info("download_thumb: invalid response status code. Can't download image.") return with open(tmp, 'wb') as f: response.raw.decode_content = True shutil.copyfileobj(response.raw, f) log.info("download_thumb: copy from temp file to final destination: %s" % destfilename) # Copy from the tmp folder to the target location xbmcvfs.copy(tmp, destfilename) xbmcvfs.delete(tmp) log.info("end download_thumb")
def get_clean_image(image): """helper to strip all kodi tags/formatting of an image path/url""" if not image: return "" if "music@" in image: # fix for embedded images thumbcache = xbmc.getCacheThumbName(image).replace(".tbn", ".jpg") thumbcache = "special://thumbnails/%s/%s" % (thumbcache[0], thumbcache) if not xbmcvfs.exists(thumbcache): xbmcvfs.copy(image, thumbcache) image = thumbcache if image and "image://" in image: image = image.replace("image://", "") if sys.version_info.major == 3: image = unquote(image) else: image = unquote(image.encode("utf-8")) if image.endswith("/"): image = image[:-1] if sys.version_info.major < 3: if not isinstance(image, unicode): image = image.decode("utf8") return image
def replace(url): if not url: return src_folders = "special://profile/addon_data/%s/folders/" % (addon_id()) dst_folders = "special://profile/addon_data/%s/folders.last/" % (addon_id()) cleanFolder(dst_folders) success = xbmcvfs.rename(src_folders,dst_folders) dst = 'special://profile/addon_data/%s/folders.zip' % (addon_id()) success = xbmcvfs.copy(url,dst) path = xbmc.translatePath('special://profile/addon_data/%s/folders.zip' % (addon_id())) f = open(path,'rb') zf = zipfile.ZipFile(f) addon_data = "special://profile/addon_data/%s/" % (addon_id()) zf.extractall(xbmc.translatePath(addon_data))
def cdart_single_backup(source, artist, album, disc_num=1): log("Backup: %s - %s" % (artist, album), xbmc.LOGNOTICE) log(" source: %s" % source, xbmc.LOGNOTICE) if xbmcvfs.exists(source): target = cdart_get_backup_filename(artist, album, disc_num) log(" target: %s" % target, xbmc.LOGNOTICE) if xbmcvfs.exists(target): log(" target exists, skipping", xbmc.LOGNOTICE) else: try: if not xbmcvfs.exists(os.path.dirname(target)): xbmcvfs.mkdirs(os.path.dirname(target)) log(" target path created", xbmc.LOGDEBUG) xbmcvfs.copy(source, target) log("Backup succesful.", xbmc.LOGNOTICE) return True except Exception as e: log("copying error, check path and file permissions", xbmc.LOGNOTICE) log(e.message, xbmc.LOGWARNING) else: log("Backup source does not exist, skipped.", xbmc.LOGNOTICE) return False
def xbmcvfs_copytree(src, dst): if not xbmcvfs.exists(dst): xbmcvfs.mkdirs(dst) dirs, files = xbmcvfs.listdir(src) for file in files: srcname = os.path.join(src, file) dstname = os.path.join(dst, file) ok = xbmcvfs.copy(srcname, dstname) print "%r xbmcvfs.copy( %r, %r )" % (bool(ok), srcname, dstname) for dir in dirs: srcname = os.path.join(src, dir) dstname = os.path.join(dst, dir) xbmcvfs_copytree(srcname, dstname)
def backup_theme(self, themename): '''backup a colortheme to a zipfile''' import zipfile backup_path = xbmcgui.Dialog().browse(3, self.addon.getLocalizedString(32029), "files") if backup_path: backup_name = try_encode("%s ColorTheme - %s" % (get_skin_name().capitalize(), themename)) backupfile = os.path.join(backup_path, backup_name + try_encode(".zip")) zip_temp = try_encode('special://temp/%s.zip' % backup_name) xbmcvfs.delete(zip_temp) xbmcvfs.delete(backupfile) zip_temp = xbmcvfs.translatePath(zip_temp) zip_file = zipfile.ZipFile(zip_temp, "w", zipfile.ZIP_DEFLATED) abs_src = os.path.abspath(xbmcvfs.translatePath(self.userthemes_path)) for filename in xbmcvfs.listdir(self.userthemes_path)[1]: if (filename.startswith("%s_" % themename) or filename.replace(".theme", "").replace(".jpg", "") == themename): filename = filename filepath = xbmcvfs.translatePath(self.userthemes_path + filename) absname = os.path.abspath(filepath) arcname = absname[len(abs_src) + 1:] zip_file.write(absname, arcname) zip_file.close() xbmcvfs.copy(zip_temp, backupfile)
def copyLog(): addon = xbmcaddon.Addon("service.zomboided.tools") addon_name = addon.getAddonInfo("name") # Copy the log file log_path = "" dest_path = "" try: log_path = xbmc.translatePath("special://logpath/kodi.log") start_dir = "" dest_folder = xbmcgui.Dialog().browse( 0, "Select folder to copy log file into", "files", "", False, False, start_dir, False) dest_path = "kodi " + datetime.datetime.now().strftime( "%y-%m-%d %H-%M-%S") + ".log" dest_path = dest_folder + dest_path.replace(" ", "_") debugTrace("Copying " + log_path + " to " + dest_path) addon = xbmcaddon.Addon("service.zomboided.tools") infoTrace( "managefiles.py", "Copying log file to " + dest_path + ". Using version " + addon.getSetting("version_number")) xbmcvfs.copy(log_path, dest_path) if not xbmcvfs.exists(dest_path): raise IOError('Failed to copy log ' + log_path + " to " + dest_path) dialog_message = "Copied log file to:\n" + dest_path except: errorTrace("managefiles.py", "Failed to copy log from " + log_path + " to " + dest_path) if xbmcvfs.exists(log_path): dialog_message = "Error copying log, try copying it to a different location." else: dialog_messsage = "Could not find the kodi.log file." errorTrace("managefiles.py", dialog_message + " " + log_path + ", " + dest_path) xbmcgui.Dialog().ok("Log Copy", dialog_message)
def build_playlist(channels): playlist_path = os.path.join(SAVE_LOCATION, 'playlist.m3u') playlist_copy = os.path.join(COPY_LOCATION, 'playlist.m3u') m3u_file = open(playlist_path, "w") m3u_file.write("#EXTM3U") m3u_file.write("\n") for channel_id, title, logo in channels: url = 'plugin://plugin.video.psvue/?url=' url += urllib.quote(CHANNEL_URL + '/' + channel_id) url += '&mode=900' url += '&title='+title url += '&program_id=0000000' url += '&series_id=00000' url += '&channel_id='+channel_id url += '&airing_id=00000000' url += '&tms_id=EP000000000000' url += '&icon='+logo m3u_file.write("\n") channel_info = '#EXTINF:-1 tvg-id="' + channel_id + '" tvg-name="' + title + '"' if logo is not None: channel_info += ' tvg-logo="' + logo + '"' channel_info += ' group_title="PS Vue",' + title m3u_file.write(channel_info + "\n") m3u_file.write(url + "\n") m3u_file.close() if ADDON.getSetting(id='custom_directory') == 'true': xbmc.log("Copying Playlist... ") xbmcvfs.copy(playlist_path, playlist_copy) xbmc.log("COPIED Playlist!!! ") check_iptv_setting('epgTSOverride', 'true') check_iptv_setting('m3uPathType', '0') check_iptv_setting('m3uPath', playlist_path) check_iptv_setting('logoFromEpg', '1') check_iptv_setting('logoPathType', '1')
def download(self): xbmcvfs.mkdirs(self.dest_path) for libname in get_libname(self.platform): dest = os.path.join(self.dest_path, libname) log("try to fetch %s" % libname) url = "%s/%s/%s/%s.zip" % (__libbaseurl__, self.platform['system'], self.platform['version'], libname) if libname != 'liblibtorrent.so': try: self.http = HTTP() self.http.fetch(url, download=dest + ".zip", progress=True) log("%s -> %s" % (url, dest)) xbmc.executebuiltin( 'XBMC.Extract("%s.zip","%s")' % (dest, self.dest_path), True) xbmcvfs.delete(dest + ".zip") except: text = 'Failed download %s!' % libname xbmc.executebuiltin("XBMC.Notification(%s,%s,%s,%s)" % (__plugin__, text, 750, __icon__)) else: xbmcvfs.copy(os.path.join(self.dest_path, 'libtorrent.so'), dest) return True