ui settings restore update

This commit is contained in:
Rob 2020-12-03 13:59:15 -06:00 committed by GitHub
parent adc6ee0c52
commit 49b3144baa
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 148 additions and 152 deletions

View File

@ -555,4 +555,16 @@ msgstr ""
msgctxt "#30141" msgctxt "#30141"
msgid "This will erase any current Advanced Editor settings" msgid "This will erase any current Advanced Editor settings"
msgstr "" msgstr ""
msgctxt "#30148"
msgid "Ask before restoring Kodi UI settings"
msgstr ""
msgctxt "#30149"
msgid "Restore Kodi UI Settings"
msgstr ""
msgctxt "#30150"
msgid "Restore saved Kodi system settings from backup?"
msgstr ""

View File

@ -12,12 +12,12 @@ from resources.lib.extractor import ZipExtractor
def folderSort(aKey): def folderSort(aKey):
result = aKey[0] result = aKey[0]
if(len(result) < 8): if(len(result) < 8):
result = result + "0000" result = result + "0000"
return result return result
class XbmcBackup: class XbmcBackup:
#constants for initiating a back or restore #constants for initiating a back or restore
@ -31,10 +31,10 @@ class XbmcBackup:
xbmc_vfs = None xbmc_vfs = None
remote_vfs = None remote_vfs = None
saved_remote_vfs = None saved_remote_vfs = None
restoreFile = None restoreFile = None
remote_base_path = None remote_base_path = None
#for the progress bar #for the progress bar
progressBar = None progressBar = None
filesLeft = 0 filesLeft = 0
@ -42,7 +42,7 @@ class XbmcBackup:
restore_point = None restore_point = None
skip_advanced = False #if we should check for the existance of advancedsettings in the restore skip_advanced = False #if we should check for the existance of advancedsettings in the restore
def __init__(self): def __init__(self):
self.xbmc_vfs = XBMCFileSystem(xbmc.translatePath('special://home')) self.xbmc_vfs = XBMCFileSystem(xbmc.translatePath('special://home'))
@ -78,10 +78,10 @@ class XbmcBackup:
#get all the folders in the current root path #get all the folders in the current root path
dirs,files = self.remote_vfs.listdir(self.remote_base_path) dirs,files = self.remote_vfs.listdir(self.remote_base_path)
for aDir in dirs: for aDir in dirs:
if(self.remote_vfs.exists(self.remote_base_path + aDir + "/xbmcbackup.val")): if(self.remote_vfs.exists(self.remote_base_path + aDir + "/xbmcbackup.val")):
#format the name according to regional settings #format the name according to regional settings
folderName = self._dateFormat(aDir) folderName = self._dateFormat(aDir)
@ -90,17 +90,17 @@ class XbmcBackup:
for aFile in files: for aFile in files:
file_ext = aFile.split('.')[-1] file_ext = aFile.split('.')[-1]
folderName = utils.encode(aFile.split('.')[0]) folderName = utils.encode(aFile.split('.')[0])
if(file_ext == 'zip' and len(folderName) == 12 and str.isdigit(folderName)): if(file_ext == 'zip' and len(folderName) == 12 and str.isdigit(folderName)):
#format the name according to regional settings #format the name according to regional settings
folderName = self._dateFormat(folderName) folderName = self._dateFormat(folderName)
result.append((aFile ,folderName)) result.append((aFile ,folderName))
result.sort(key=folderSort,reverse=reverse) result.sort(key=folderSort,reverse=reverse)
return result return result
def selectRestore(self,restore_point): def selectRestore(self,restore_point):
@ -129,7 +129,7 @@ class XbmcBackup:
if(int(utils.getSetting('backup_selection_type')) == 0): if(int(utils.getSetting('backup_selection_type')) == 0):
#read in a list of the directories to backup #read in a list of the directories to backup
selectedDirs = self._readBackupConfig(utils.addon_dir() + "/resources/data/default_files.json") selectedDirs = self._readBackupConfig(utils.addon_dir() + "/resources/data/default_files.json")
#simple mode - get file listings for all enabled directories #simple mode - get file listings for all enabled directories
for aDir in self.simple_directory_list: for aDir in self.simple_directory_list:
#if this dir enabled #if this dir enabled
@ -142,74 +142,74 @@ class XbmcBackup:
#get the set names #get the set names
keys = list(selectedDirs.keys()) keys = list(selectedDirs.keys())
#go through the custom sets #go through the custom sets
for aKey in keys: for aKey in keys:
#get the set #get the set
aSet = selectedDirs[aKey] aSet = selectedDirs[aKey]
#get file listing and append #get file listing and append
allFiles.append(self._addBackupDir(aKey,aSet['root'],aSet['dirs'])) allFiles.append(self._addBackupDir(aKey,aSet['root'],aSet['dirs']))
#create a validation file for backup rotation #create a validation file for backup rotation
writeCheck = self._createValidationFile(allFiles) writeCheck = self._createValidationFile(allFiles)
if(not writeCheck): if(not writeCheck):
#we may not be able to write to this destination for some reason #we may not be able to write to this destination for some reason
shouldContinue = xbmcgui.Dialog().yesno(utils.getString(30089),utils.getString(30090), utils.getString(30044),autoclose=25000) shouldContinue = xbmcgui.Dialog().yesno(utils.getString(30089),utils.getString(30090), utils.getString(30044),autoclose=25000)
if(not shouldContinue): if(not shouldContinue):
return return
orig_base_path = self.remote_vfs.root_path orig_base_path = self.remote_vfs.root_path
#backup all the files #backup all the files
self.filesLeft = self.filesTotal self.filesLeft = self.filesTotal
for fileGroup in allFiles: for fileGroup in allFiles:
self.xbmc_vfs.set_root(xbmc.translatePath(fileGroup['source'])) self.xbmc_vfs.set_root(xbmc.translatePath(fileGroup['source']))
self.remote_vfs.set_root(fileGroup['dest'] + fileGroup['name']) self.remote_vfs.set_root(fileGroup['dest'] + fileGroup['name'])
filesCopied = self._copyFiles(fileGroup['files'],self.xbmc_vfs,self.remote_vfs) filesCopied = self._copyFiles(fileGroup['files'],self.xbmc_vfs,self.remote_vfs)
if(not filesCopied): if(not filesCopied):
utils.showNotification(utils.getString(30092)) utils.showNotification(utils.getString(30092))
utils.log(utils.getString(30092)) utils.log(utils.getString(30092))
#reset remote and xbmc vfs #reset remote and xbmc vfs
self.xbmc_vfs.set_root("special://home/") self.xbmc_vfs.set_root("special://home/")
self.remote_vfs.set_root(orig_base_path) self.remote_vfs.set_root(orig_base_path)
if(utils.getSetting("compress_backups") == 'true'): if(utils.getSetting("compress_backups") == 'true'):
fileManager = FileManager(self.xbmc_vfs) fileManager = FileManager(self.xbmc_vfs)
#send the zip file to the real remote vfs #send the zip file to the real remote vfs
zip_name = self.remote_vfs.root_path[:-1] + ".zip" zip_name = self.remote_vfs.root_path[:-1] + ".zip"
self.remote_vfs.cleanup() self.remote_vfs.cleanup()
self.xbmc_vfs.rename(xbmc.translatePath("special://temp/xbmc_backup_temp.zip"), xbmc.translatePath("special://temp/" + zip_name)) self.xbmc_vfs.rename(xbmc.translatePath("special://temp/xbmc_backup_temp.zip"), xbmc.translatePath("special://temp/" + zip_name))
fileManager.addFile(xbmc.translatePath("special://temp/" + zip_name)) fileManager.addFile(xbmc.translatePath("special://temp/" + zip_name))
#set root to data dir home #set root to data dir home
self.xbmc_vfs.set_root(xbmc.translatePath("special://temp/")) self.xbmc_vfs.set_root(xbmc.translatePath("special://temp/"))
self.remote_vfs = self.saved_remote_vfs self.remote_vfs = self.saved_remote_vfs
self.progressBar.updateProgress(98, utils.getString(30088)) self.progressBar.updateProgress(98, utils.getString(30088))
fileCopied = self._copyFiles(fileManager.getFiles(),self.xbmc_vfs, self.remote_vfs) fileCopied = self._copyFiles(fileManager.getFiles(),self.xbmc_vfs, self.remote_vfs)
if(not fileCopied): if(not fileCopied):
#zip archive copy filed, inform the user #zip archive copy filed, inform the user
shouldContinue = xbmcgui.Dialog().ok(utils.getString(30089),utils.getString(30090), utils.getString(30091)) shouldContinue = xbmcgui.Dialog().ok(utils.getString(30089),utils.getString(30090), utils.getString(30091))
#delete the temp zip file #delete the temp zip file
self.xbmc_vfs.rmfile(xbmc.translatePath("special://temp/" + zip_name)) self.xbmc_vfs.rmfile(xbmc.translatePath("special://temp/" + zip_name))
#remove old backups #remove old backups
self._rotateBackups() self._rotateBackups()
#close any files #close any files
self._closeVFS() self._closeVFS()
def restore(self,progressOverride=False,selectedSets=None): def restore(self,progressOverride=False,selectedSets=None):
shouldContinue = self._setupVFS(self.Restore, progressOverride) shouldContinue = self._setupVFS(self.Restore, progressOverride)
if(shouldContinue): if(shouldContinue):
utils.log(utils.getString(30023) + " - " + utils.getString(30017)) utils.log(utils.getString(30023) + " - " + utils.getString(30017))
@ -217,38 +217,38 @@ class XbmcBackup:
if(self.restore_point.split('.')[-1] == 'zip'): if(self.restore_point.split('.')[-1] == 'zip'):
self.progressBar.updateProgress(2, utils.getString(30088)) self.progressBar.updateProgress(2, utils.getString(30088))
utils.log("copying zip file: " + self.restore_point) utils.log("copying zip file: " + self.restore_point)
#set root to data dir home #set root to data dir home
self.xbmc_vfs.set_root(xbmc.translatePath("special://temp/")) self.xbmc_vfs.set_root(xbmc.translatePath("special://temp/"))
if(not self.xbmc_vfs.exists(xbmc.translatePath("special://temp/" + self.restore_point))): if(not self.xbmc_vfs.exists(xbmc.translatePath("special://temp/" + self.restore_point))):
#copy just this file from the remote vfs #copy just this file from the remote vfs
zipFile = [] zipFile = []
zipFile.append(self.remote_base_path + self.restore_point) zipFile.append(self.remote_base_path + self.restore_point)
self._copyFiles(zipFile,self.remote_vfs, self.xbmc_vfs) self._copyFiles(zipFile,self.remote_vfs, self.xbmc_vfs)
else: else:
utils.log("zip file exists already") utils.log("zip file exists already")
#extract the zip file #extract the zip file
zip_vfs = ZipFileSystem(xbmc.translatePath("special://temp/"+ self.restore_point),'r') zip_vfs = ZipFileSystem(xbmc.translatePath("special://temp/"+ self.restore_point),'r')
extractor = ZipExtractor() extractor = ZipExtractor()
if(not extractor.extract(zip_vfs, xbmc.translatePath("special://temp/"), self.progressBar)): if(not extractor.extract(zip_vfs, xbmc.translatePath("special://temp/"), self.progressBar)):
#we had a problem extracting the archive, delete everything #we had a problem extracting the archive, delete everything
zip_vfs.cleanup() zip_vfs.cleanup()
self.xbmc_vfs.rmfile(xbmc.translatePath("special://temp/" + self.restore_point)) self.xbmc_vfs.rmfile(xbmc.translatePath("special://temp/" + self.restore_point))
xbmcgui.Dialog().ok(utils.getString(30010),utils.getString(30101)) xbmcgui.Dialog().ok(utils.getString(30010),utils.getString(30101))
return return
zip_vfs.cleanup() zip_vfs.cleanup()
self.progressBar.updateProgress(0,utils.getString(30049) + "......") self.progressBar.updateProgress(0,utils.getString(30049) + "......")
#set the new remote vfs and fix xbmc path #set the new remote vfs and fix xbmc path
self.remote_vfs = XBMCFileSystem(xbmc.translatePath("special://temp/" + self.restore_point.split(".")[0] + "/")) self.remote_vfs = XBMCFileSystem(xbmc.translatePath("special://temp/" + self.restore_point.split(".")[0] + "/"))
self.xbmc_vfs.set_root(xbmc.translatePath("special://home/")) self.xbmc_vfs.set_root(xbmc.translatePath("special://home/"))
#for restores remote path must exist #for restores remote path must exist
if(not self.remote_vfs.exists(self.remote_vfs.root_path)): if(not self.remote_vfs.exists(self.remote_vfs.root_path)):
xbmcgui.Dialog().ok(utils.getString(30010),utils.getString(30045),self.remote_vfs.root_path) xbmcgui.Dialog().ok(utils.getString(30010),utils.getString(30045),self.remote_vfs.root_path)
@ -262,7 +262,7 @@ class XbmcBackup:
utils.log(utils.getString(30051)) utils.log(utils.getString(30051))
allFiles = [] allFiles = []
fileManager = FileManager(self.remote_vfs) fileManager = FileManager(self.remote_vfs)
#check for the existance of an advancedsettings file #check for the existance of an advancedsettings file
if(self.remote_vfs.exists(self.remote_vfs.root_path + "config/advancedsettings.xml") and not self.skip_advanced): if(self.remote_vfs.exists(self.remote_vfs.root_path + "config/advancedsettings.xml") and not self.skip_advanced):
#let the user know there is an advanced settings file present #let the user know there is an advanced settings file present
@ -277,9 +277,15 @@ class XbmcBackup:
self._createResumeBackupFile() self._createResumeBackupFile()
#do not continue running #do not continue running
xbmcgui.Dialog().ok(utils.getString(30077),utils.getString(30078)) xbmcgui.Dialog().ok(utils.getString(30077),utils.getString(30078))
return return
# check if settings should be restored from this backup
restoreSettings = utils.getSetting('always_prompt_restore_settings') == 'false'
if(not restoreSettings and 'system_settings' in valFile):
# prompt the user to restore settings yes/no
restoreSettings = xbmcgui.Dialog().yesno(utils.getString(30149), utils.getString(30150))
#use a multiselect dialog to select sets to restore #use a multiselect dialog to select sets to restore
restoreSets = [n['name'] for n in valFile['directories']] restoreSets = [n['name'] for n in valFile['directories']]
@ -288,20 +294,20 @@ class XbmcBackup:
selectedSets = xbmcgui.Dialog().multiselect(utils.getString(30131),restoreSets) selectedSets = xbmcgui.Dialog().multiselect(utils.getString(30131),restoreSets)
else: else:
selectedSets = [restoreSets.index(n) for n in selectedSets if n in restoreSets] #if set name not found just skip it selectedSets = [restoreSets.index(n) for n in selectedSets if n in restoreSets] #if set name not found just skip it
if(selectedSets != None): if(selectedSets != None):
#go through each of the directories in the backup and write them to the correct location #go through each of the directories in the backup and write them to the correct location
for index in selectedSets: for index in selectedSets:
#add this directory #add this directory
aDir = valFile['directories'][index] aDir = valFile['directories'][index]
self.xbmc_vfs.set_root(xbmc.translatePath(aDir['path'])) self.xbmc_vfs.set_root(xbmc.translatePath(aDir['path']))
if(self.remote_vfs.exists(self.remote_vfs.root_path + aDir['name'] + '/')): if(self.remote_vfs.exists(self.remote_vfs.root_path + aDir['name'] + '/')):
#walk the directory #walk the directory
fileManager.walkTree(self.remote_vfs.root_path + aDir['name'] + '/') fileManager.walkTree(self.remote_vfs.root_path + aDir['name'] + '/')
self.filesTotal = self.filesTotal + fileManager.size() self.filesTotal = self.filesTotal + fileManager.size()
allFiles.append({"source":self.remote_vfs.root_path + aDir['name'],"dest":self.xbmc_vfs.root_path,"files":fileManager.getFiles()}) allFiles.append({"source":self.remote_vfs.root_path + aDir['name'],"dest":self.xbmc_vfs.root_path,"files":fileManager.getFiles()})
else: else:
utils.log("error path not found: " + self.remote_vfs.root_path + aDir['name']) utils.log("error path not found: " + self.remote_vfs.root_path + aDir['name'])
xbmcgui.Dialog().ok(utils.getString(30010),utils.getString(30045),self.remote_vfs.root_path + aDir['name']) xbmcgui.Dialog().ok(utils.getString(30010),utils.getString(30045),self.remote_vfs.root_path + aDir['name'])
@ -313,6 +319,12 @@ class XbmcBackup:
self.xbmc_vfs.set_root(fileGroup['dest']) self.xbmc_vfs.set_root(fileGroup['dest'])
self._copyFiles(fileGroup['files'],self.remote_vfs,self.xbmc_vfs) self._copyFiles(fileGroup['files'],self.remote_vfs,self.xbmc_vfs)
# update the Kodi settings - if we can
if('system_settings' in valFile and restoreSettings):
self.progressBar.updateProgress(98, "Restoring Kodi settings")
gui_settings = GuiSettingsManager()
gui_settings.restore(valFile['system_settings'])
self.progressBar.updateProgress(99,"Clean up operations .....") self.progressBar.updateProgress(99,"Clean up operations .....")
if(self.restore_point.split('.')[-1] == 'zip'): if(self.restore_point.split('.')[-1] == 'zip'):
@ -320,11 +332,6 @@ class XbmcBackup:
self.xbmc_vfs.rmfile(xbmc.translatePath("special://temp/" + self.restore_point)) self.xbmc_vfs.rmfile(xbmc.translatePath("special://temp/" + self.restore_point))
self.xbmc_vfs.rmdir(self.remote_vfs.root_path) self.xbmc_vfs.rmdir(self.remote_vfs.root_path)
#update the guisettings information (or what we can from it)
gui_settings = GuiSettingsManager()
gui_settings.run()
#call update addons to refresh everything #call update addons to refresh everything
xbmc.executebuiltin('UpdateLocalAddons') xbmc.executebuiltin('UpdateLocalAddons')
@ -332,7 +339,7 @@ class XbmcBackup:
#set windows setting to true #set windows setting to true
window = xbmcgui.Window(10000) window = xbmcgui.Window(10000)
window.setProperty(utils.__addon_id__ + ".running","true") window.setProperty(utils.__addon_id__ + ".running","true")
#append backup folder name #append backup folder name
progressBarTitle = utils.getString(30010) + " - " progressBarTitle = utils.getString(30010) + " - "
if(mode == self.Backup and self.remote_vfs.root_path != ''): if(mode == self.Backup and self.remote_vfs.root_path != ''):
@ -343,11 +350,11 @@ class XbmcBackup:
#we had some kind of error deleting the old file #we had some kind of error deleting the old file
xbmcgui.Dialog().ok(utils.getString(30010),utils.getString(30096),utils.getString(30097)) xbmcgui.Dialog().ok(utils.getString(30010),utils.getString(30096),utils.getString(30097))
return False return False
#save the remote file system and use the zip vfs #save the remote file system and use the zip vfs
self.saved_remote_vfs = self.remote_vfs self.saved_remote_vfs = self.remote_vfs
self.remote_vfs = ZipFileSystem(xbmc.translatePath("special://temp/xbmc_backup_temp.zip"),"w") self.remote_vfs = ZipFileSystem(xbmc.translatePath("special://temp/xbmc_backup_temp.zip"),"w")
self.remote_vfs.set_root(self.remote_vfs.root_path + time.strftime("%Y%m%d%H%M") + "/") self.remote_vfs.set_root(self.remote_vfs.root_path + time.strftime("%Y%m%d%H%M") + "/")
progressBarTitle = progressBarTitle + utils.getString(30023) + ": " + utils.getString(30016) progressBarTitle = progressBarTitle + utils.getString(30023) + ": " + utils.getString(30016)
elif(mode == self.Restore and self.restore_point != None and self.remote_vfs.root_path != ''): elif(mode == self.Restore and self.restore_point != None and self.remote_vfs.root_path != ''):
@ -362,7 +369,7 @@ class XbmcBackup:
utils.log(utils.getString(30047) + ": " + self.xbmc_vfs.root_path) utils.log(utils.getString(30047) + ": " + self.xbmc_vfs.root_path)
utils.log(utils.getString(30048) + ": " + self.remote_vfs.root_path) utils.log(utils.getString(30048) + ": " + self.remote_vfs.root_path)
#setup the progress bar #setup the progress bar
self.progressBar = BackupProgressBar(progressOverride) self.progressBar = BackupProgressBar(progressOverride)
self.progressBar.create(progressBarTitle,utils.getString(30049) + "......") self.progressBar.create(progressBarTitle,utils.getString(30049) + "......")
@ -384,11 +391,11 @@ class XbmcBackup:
utils.log("Source: " + source.root_path) utils.log("Source: " + source.root_path)
utils.log("Desintation: " + dest.root_path) utils.log("Desintation: " + dest.root_path)
#make sure the dest folder exists - can cause write errors if the full path doesn't exist #make sure the dest folder exists - can cause write errors if the full path doesn't exist
if(not dest.exists(dest.root_path)): if(not dest.exists(dest.root_path)):
dest.mkdir(dest.root_path) dest.mkdir(dest.root_path)
for aFile in fileList: for aFile in fileList:
if(not self.progressBar.checkCancel()): if(not self.progressBar.checkCancel()):
utils.log('Writing file: ' + aFile,xbmc.LOGDEBUG) utils.log('Writing file: ' + aFile,xbmc.LOGDEBUG)
@ -397,7 +404,7 @@ class XbmcBackup:
dest.mkdir(dest.root_path + aFile[len(source.root_path) + 1:]) dest.mkdir(dest.root_path + aFile[len(source.root_path) + 1:])
else: else:
self._updateProgress() self._updateProgress()
wroteFile = True wroteFile = True
destFile = dest.root_path + aFile[len(source.root_path):] destFile = dest.root_path + aFile[len(source.root_path):]
if(isinstance(source,DropboxFileSystem) or isinstance(source,GoogleDriveFilesystem)): if(isinstance(source,DropboxFileSystem) or isinstance(source,GoogleDriveFilesystem)):
@ -406,18 +413,18 @@ class XbmcBackup:
else: else:
#copy using normal method #copy using normal method
wroteFile = dest.put(aFile,destFile) wroteFile = dest.put(aFile,destFile)
#if result is still true but this file failed #if result is still true but this file failed
if(not wroteFile and result): if(not wroteFile and result):
result = False result = False
return result return result
def _addBackupDir(self,folder_name,root_path,dirList): def _addBackupDir(self,folder_name,root_path,dirList):
utils.log('Backup set: ' + folder_name) utils.log('Backup set: ' + folder_name)
fileManager = FileManager(self.xbmc_vfs) fileManager = FileManager(self.xbmc_vfs)
self.xbmc_vfs.set_root(xbmc.translatePath(root_path)) self.xbmc_vfs.set_root(xbmc.translatePath(root_path))
for aDir in dirList: for aDir in dirList:
fileManager.addDir(aDir) fileManager.addDir(aDir)
@ -426,16 +433,16 @@ class XbmcBackup:
fileManager.walk() fileManager.walk()
#update total files #update total files
self.filesTotal = self.filesTotal + fileManager.size() self.filesTotal = self.filesTotal + fileManager.size()
return {"name":folder_name,"source":root_path,"dest":self.remote_vfs.root_path,"files":fileManager.getFiles()} return {"name":folder_name,"source":root_path,"dest":self.remote_vfs.root_path,"files":fileManager.getFiles()}
def _dateFormat(self,dirName): def _dateFormat(self,dirName):
#create date_time object from foldername YYYYMMDDHHmm #create date_time object from foldername YYYYMMDDHHmm
date_time = datetime(int(dirName[0:4]),int(dirName[4:6]),int(dirName[6:8]),int(dirName[8:10]),int(dirName[10:12])) date_time = datetime(int(dirName[0:4]),int(dirName[4:6]),int(dirName[6:8]),int(dirName[8:10]),int(dirName[10:12]))
#format the string based on region settings #format the string based on region settings
result = utils.getRegionalTimestamp(date_time, ['dateshort','time']) result = utils.getRegionalTimestamp(date_time, ['dateshort','time'])
return result return result
def _updateProgress(self,message=None): def _updateProgress(self,message=None):
@ -444,11 +451,11 @@ class XbmcBackup:
def _rotateBackups(self): def _rotateBackups(self):
total_backups = int(utils.getSetting('backup_rotation')) total_backups = int(utils.getSetting('backup_rotation'))
if(total_backups > 0): if(total_backups > 0):
#get a list of valid backup folders #get a list of valid backup folders
dirs = self.listBackups(reverse=False) dirs = self.listBackups(reverse=False)
if(len(dirs) > total_backups): if(len(dirs) > total_backups):
#remove backups to equal total wanted #remove backups to equal total wanted
remove_num = 0 remove_num = 0
@ -458,30 +465,34 @@ class XbmcBackup:
while(remove_num < (len(dirs) - total_backups) and not self.progressBar.checkCancel()): while(remove_num < (len(dirs) - total_backups) and not self.progressBar.checkCancel()):
self._updateProgress(utils.getString(30054) + " " + dirs[remove_num][1]) self._updateProgress(utils.getString(30054) + " " + dirs[remove_num][1])
utils.log("Removing backup " + dirs[remove_num][0]) utils.log("Removing backup " + dirs[remove_num][0])
if(dirs[remove_num][0].split('.')[-1] == 'zip'): if(dirs[remove_num][0].split('.')[-1] == 'zip'):
#this is a file, remove it that way #this is a file, remove it that way
self.remote_vfs.rmfile(self.remote_vfs.clean_path(self.remote_base_path) + dirs[remove_num][0]) self.remote_vfs.rmfile(self.remote_vfs.clean_path(self.remote_base_path) + dirs[remove_num][0])
else: else:
self.remote_vfs.rmdir(self.remote_vfs.clean_path(self.remote_base_path) + dirs[remove_num][0] + "/") self.remote_vfs.rmdir(self.remote_vfs.clean_path(self.remote_base_path) + dirs[remove_num][0] + "/")
remove_num = remove_num + 1 remove_num = remove_num + 1
def _createValidationFile(self,dirList): def _createValidationFile(self,dirList):
valInfo = {"name":"XBMC Backup Validation File","xbmc_version":xbmc.getInfoLabel('System.BuildVersion'),"type":0} valInfo = {"name":"XBMC Backup Validation File","xbmc_version":xbmc.getInfoLabel('System.BuildVersion'),"type":0, "system_settings": []}
valDirs = [] valDirs = []
for aDir in dirList: for aDir in dirList:
valDirs.append({"name":aDir['name'],"path":aDir['source']}) valDirs.append({"name":aDir['name'],"path":aDir['source']})
valInfo['directories'] = valDirs valInfo['directories'] = valDirs
# dump all current Kodi settings
gui_settings = GuiSettingsManager()
valInfo['system_settings'] = gui_settings.backup()
vFile = xbmcvfs.File(xbmc.translatePath(utils.data_dir() + "xbmcbackup.val"),'w') vFile = xbmcvfs.File(xbmc.translatePath(utils.data_dir() + "xbmcbackup.val"),'w')
vFile.write(json.dumps(valInfo)) vFile.write(json.dumps(valInfo))
vFile.write("") vFile.write("")
vFile.close() vFile.close()
success = self.remote_vfs.put(xbmc.translatePath(utils.data_dir() + "xbmcbackup.val"),self.remote_vfs.root_path + "xbmcbackup.val") success = self.remote_vfs.put(xbmc.translatePath(utils.data_dir() + "xbmcbackup.val"),self.remote_vfs.root_path + "xbmcbackup.val")
#remove the validation file #remove the validation file
xbmcvfs.delete(xbmc.translatePath(utils.data_dir() + "xbmcbackup.val")) xbmcvfs.delete(xbmc.translatePath(utils.data_dir() + "xbmcbackup.val"))
@ -492,12 +503,12 @@ class XbmcBackup:
nmFile.close() nmFile.close()
success = self.remote_vfs.put(xbmc.translatePath(utils.data_dir() + ".nomedia"),self.remote_vfs.root_path + ".nomedia") success = self.remote_vfs.put(xbmc.translatePath(utils.data_dir() + ".nomedia"),self.remote_vfs.root_path + ".nomedia")
return success return success
def _checkValidationFile(self,path): def _checkValidationFile(self,path):
result = None result = None
#copy the file and open it #copy the file and open it
if(isinstance(self.remote_vfs,DropboxFileSystem) or isinstance(self.remote_vfs,GoogleDriveFilesystem)): if(isinstance(self.remote_vfs,DropboxFileSystem) or isinstance(self.remote_vfs,GoogleDriveFilesystem)):
self.remote_vfs.get_file(path + "xbmcbackup.val", xbmc.translatePath(utils.data_dir() + "xbmcbackup_restore.val")) self.remote_vfs.get_file(path + "xbmcbackup.val", xbmc.translatePath(utils.data_dir() + "xbmcbackup_restore.val"))
@ -519,7 +530,7 @@ class XbmcBackup:
if(not shouldContinue): if(not shouldContinue):
result = None result = None
except ValueError: except ValueError:
#may fail on older archives #may fail on older archives
result = None result = None
@ -542,7 +553,7 @@ class FileManager:
exclude_dir = [] exclude_dir = []
root_dirs = [] root_dirs = []
pathSep = '/' pathSep = '/'
def __init__(self,vfs): def __init__(self,vfs):
self.vfs = vfs self.vfs = vfs
self.fileArray = [] self.fileArray = []
@ -550,7 +561,7 @@ class FileManager:
self.root_dirs = [] self.root_dirs = []
def walk(self): def walk(self):
for aDir in self.root_dirs: for aDir in self.root_dirs:
self.addFile('-' + xbmc.translatePath(aDir['path'])) self.addFile('-' + xbmc.translatePath(aDir['path']))
self.walkTree(xbmc.translatePath(aDir['path']),aDir['recurse']) self.walkTree(xbmc.translatePath(aDir['path']),aDir['recurse'])
@ -559,7 +570,7 @@ class FileManager:
utils.log('walking ' + directory + ', recurse: ' + str(recurse)) utils.log('walking ' + directory + ', recurse: ' + str(recurse))
if(directory[-1:] == '/' or directory[-1:] == '\\'): if(directory[-1:] == '/' or directory[-1:] == '\\'):
directory = directory[:-1] directory = directory[:-1]
if(self.vfs.exists(directory + self.pathSep)): if(self.vfs.exists(directory + self.pathSep)):
dirs,files = self.vfs.listdir(directory) dirs,files = self.vfs.listdir(directory)
@ -571,7 +582,7 @@ class FileManager:
#check if directory is excluded #check if directory is excluded
if(not any(dirPath.startswith(exDir) for exDir in self.exclude_dir)): if(not any(dirPath.startswith(exDir) for exDir in self.exclude_dir)):
self.addFile("-" + dirPath) self.addFile("-" + dirPath)
#catch for "non directory" type files #catch for "non directory" type files
@ -580,10 +591,10 @@ class FileManager:
for s in file_ext: for s in file_ext:
if(s in self.not_dir): if(s in self.not_dir):
shouldWalk = False shouldWalk = False
if(shouldWalk): if(shouldWalk):
self.walkTree(dirPath) self.walkTree(dirPath)
#copy all the files #copy all the files
for aFile in files: for aFile in files:
filePath = xbmc.translatePath(directory + self.pathSep + aFile) filePath = xbmc.translatePath(directory + self.pathSep + aFile)
@ -594,13 +605,13 @@ class FileManager:
self.root_dirs.append({'path':dirMeta['path'],'recurse':dirMeta['recurse']}) self.root_dirs.append({'path':dirMeta['path'],'recurse':dirMeta['recurse']})
else: else:
self.excludeFile(xbmc.translatePath(dirMeta['path'])) self.excludeFile(xbmc.translatePath(dirMeta['path']))
def addFile(self,filename): def addFile(self,filename):
try: try:
filename = filename.decode('UTF-8') filename = filename.decode('UTF-8')
except UnicodeDecodeError: except UnicodeDecodeError:
filename = filename.decode('ISO-8859-2') filename = filename.decode('ISO-8859-2')
#write the full remote path name of this file #write the full remote path name of this file
utils.log("Add File: " + filename,xbmc.LOGDEBUG) utils.log("Add File: " + filename,xbmc.LOGDEBUG)
self.fileArray.append(filename) self.fileArray.append(filename)
@ -610,11 +621,11 @@ class FileManager:
filename = filename.decode('UTF-8') filename = filename.decode('UTF-8')
except UnicodeDecodeError: except UnicodeDecodeError:
filename = filename.decode('ISO-8859-2') filename = filename.decode('ISO-8859-2')
#remove trailing slash #remove trailing slash
if(filename[-1] == '/' or filename[-1] == '\\'): if(filename[-1] == '/' or filename[-1] == '\\'):
filename = filename[:-1] filename = filename[:-1]
#write the full remote path name of this file #write the full remote path name of this file
utils.log("Exclude File: " + filename) utils.log("Exclude File: " + filename)
self.exclude_dir.append(filename) self.exclude_dir.append(filename)
@ -624,7 +635,7 @@ class FileManager:
self.fileArray = [] self.fileArray = []
self.root_dirs = [] self.root_dirs = []
self.exclude_dir = [] self.exclude_dir = []
return result return result
def size(self): def size(self):

View File

@ -1,73 +1,45 @@
import json import json
import xbmc,xbmcvfs import xbmc,xbmcvfs
from . import utils as utils from . import utils as utils
from xml.dom import minidom
from xml.parsers.expat import ExpatError
class GuiSettingsManager: class GuiSettingsManager:
doc = None systemSettings = None
def __init__(self):
#first make a copy of the file
xbmcvfs.copy(xbmc.translatePath('special://home/userdata/guisettings.xml'), xbmc.translatePath("special://home/userdata/guisettings.xml.restored"))
#read in the copy
self._readFile(xbmc.translatePath('special://home/userdata/guisettings.xml.restored'))
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"}}').decode('utf-8', errors="ignore"))
settings = json_response['result']['settings']
currentSettings = {}
for aSetting in settings:
if('value' in aSetting):
currentSettings[aSetting['id']] = aSetting['value']
#parse the existing xml file and get all the settings we need to restore
restoreSettings = self.__parseNodes(self.doc.getElementsByTagName('setting'))
#get a list where the restore setting value != the current value
updateSettings = {k: v for k, v in list(restoreSettings.items()) if (k in currentSettings and currentSettings[k] != v)}
#go through all the found settings and update them
jsonObj = {"jsonrpc":"2.0","id":1,"method":"Settings.SetSettingValue","params":{"setting":"","value":""}}
for anId, aValue in list(updateSettings.items()):
utils.log("updating: " + anId + ", value: " + str(aValue))
jsonObj['params']['setting'] = anId
jsonObj['params']['value'] = aValue
xbmc.executeJSONRPC(json.dumps(jsonObj))
def __parseNodes(self,nodeList):
result = {}
for node in nodeList: def __init__(self):
nodeValue = '' # get all of the current Kodi settings
if(node.firstChild != None): json_response = json.loads(xbmc.executeJSONRPC('{"jsonrpc":"2.0", "id":1, "method":"Settings.GetSettings","params":{"level":"expert"}}').decode('utf-8', errors="ignore"))
nodeValue = node.firstChild.nodeValue
self.systemSettings = json_response['result']['settings']
#check for numbers and booleans
if(nodeValue.isdigit()): def backup(self):
nodeValue = int(nodeValue) utils.log('Backing up Kodi settings')
elif(nodeValue == 'true'):
nodeValue = True # return all current settings
elif(nodeValue == 'false'): return self.systemSettings
nodeValue = False
def restore(self, restoreSettings):
result[node.getAttribute('id')] = nodeValue utils.log('Restoring Kodi settings')
return result updateJson = {"jsonrpc": "2.0", "id": 1, "method": "Settings.SetSettingValue", "params": {"setting": "", "value": ""}}
def _readFile(self,fileLoc): # create a setting=value dict of the current settings
settingsDict = {}
if(xbmcvfs.exists(fileLoc)): for aSetting in self.systemSettings:
try: # ignore action types, no value
self.doc = minidom.parse(fileLoc) if(aSetting['type'] != 'action'):
except ExpatError: settingsDict[aSetting['id']] = aSetting['value']
utils.log("Can't read " + fileLoc)
restoreCount = 0
for aSetting in restoreSettings:
# only update a setting if its different than the current (action types have no value)
if(aSetting['type'] != 'action' and settingsDict[aSetting['id']] != aSetting['value']):
utils.log('%s different than current: %s' % (aSetting['id'], str(aSetting['value'])), xbmc.LOGDEBUG)
updateJson['params']['setting'] = aSetting['id']
updateJson['params']['value'] = aSetting['value']
xbmc.executeJSONRPC(json.dumps(updateJson))
restoreCount = restoreCount + 1
utils.log('Update %d settings' % restoreCount)

View File

@ -3,6 +3,7 @@
<category id="general" label="30011"> <category id="general" label="30011">
<setting id="compress_backups" type="bool" label="30087" default="false" /> <setting id="compress_backups" type="bool" label="30087" default="false" />
<setting id="backup_rotation" type="number" label="30026" default="0" /> <setting id="backup_rotation" type="number" label="30026" default="0" />
<setting id="always_prompt_restore_settings" type="bool" label="30148" default="false" />
<setting id="progress_mode" type="enum" label="30022" lvalues="30082|30083|30084" default="0" /> <setting id="progress_mode" type="enum" label="30022" lvalues="30082|30083|30084" default="0" />
<setting id="upgrade_notes" type="number" label="upgrade_notes" visible="false" default="1" /> <setting id="upgrade_notes" type="number" label="upgrade_notes" visible="false" default="1" />
</category> </category>