ui settings restore upgrade

* added ability to export/save settings as json using GetSettings

* added generic copyFile method instead of duplicating

* copy and load settings file after file restore (right now only reads)

* set settings values from backup when differ than current

* store settings as part of validation file

* prompt for settings restore or set always via toggle

* unused import

* added new strings for settings restore

* updated changelog

* fix pep8 syntax

* swap setting to always prompt instead of always restore (invert)
This commit is contained in:
Rob 2020-12-03 14:08:25 -06:00 committed by GitHub
parent b470412b4f
commit 71c8d9ae54
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 104 additions and 89 deletions

View File

@ -91,6 +91,7 @@
</assets> </assets>
<news>Version 1.6.4 <news>Version 1.6.4
- updated deprecated Kodi python methods - updated deprecated Kodi python methods
- added better system settings/restore functionality (enabled by default)
</news> </news>
</extension> </extension>
</addon> </addon>

View File

@ -6,11 +6,21 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
## [Unreleased](https://github.com/robweber/xbmcbackup/compare/matrix-1.6.3...matrix) ## [Unreleased](https://github.com/robweber/xbmcbackup/compare/matrix-1.6.3...matrix)
### Added
- merged duplicate copy code into ```_copyFile``` method
- added method to backup/restore Kodi settings via the GetSettings/SetSettingValue JSON methods in the validation file
- added setting to always restore settings or prompt at the time of backup
### Changed ### Changed
- updated script.module.future version to current - updated script.module.future version to current
- swapped xbmc.translatePath for xbmcvfs.translatePath, deprecated - swapped xbmc.translatePath for xbmcvfs.translatePath, deprecated
### Removed
- removed old xml GuiSettings parsing for settings restore
## [Version 1.6.3](https://github.com/robweber/xbmcbackup/compare/matrix-1.6.2...robweber:matrix-1.6.3) - 2020-06-15 ## [Version 1.6.3](https://github.com/robweber/xbmcbackup/compare/matrix-1.6.2...robweber:matrix-1.6.3) - 2020-06-15
### Changed ### Changed

View File

@ -581,3 +581,14 @@ msgctxt "#30147"
msgid "Toggle Sub Folders" msgid "Toggle Sub Folders"
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

@ -284,6 +284,12 @@ class XbmcBackup:
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 = not utils.getSettingBool('always_prompt_restore_settings')
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']]
@ -294,6 +300,7 @@ class XbmcBackup:
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 is not None): if(selectedSets is not 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:
@ -318,6 +325,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'):
@ -325,10 +338,6 @@ class XbmcBackup:
self.xbmc_vfs.rmfile(xbmcvfs.translatePath("special://temp/" + self.restore_point)) self.xbmc_vfs.rmfile(xbmcvfs.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')
@ -404,14 +413,8 @@ class XbmcBackup:
self._updateProgress('%s remaining, writing %s' % (utils.diskString(self.transferLeft), os.path.basename(aFile['file'][len(source.root_path):]))) self._updateProgress('%s remaining, writing %s' % (utils.diskString(self.transferLeft), os.path.basename(aFile['file'][len(source.root_path):])))
self.transferLeft = self.transferLeft - aFile['size'] self.transferLeft = self.transferLeft - aFile['size']
wroteFile = True # copy the file
destFile = dest.root_path + aFile['file'][len(source.root_path):] wroteFile = self._copyFile(source, dest, aFile['file'], dest.root_path + aFile['file'][len(source.root_path):])
if(isinstance(source, DropboxFileSystem)):
# if copying from cloud storage we need the file handle, use get_file
wroteFile = source.get_file(aFile['file'], destFile)
else:
# copy using normal method
wroteFile = dest.put(aFile['file'], 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):
@ -419,6 +422,18 @@ class XbmcBackup:
return result return result
def _copyFile(self, source, dest, sourceFile, destFile):
result = True
if(isinstance(source, DropboxFileSystem)):
# if copying from cloud storage we need the file handle, use get_file
result = source.get_file(sourceFile, destFile)
else:
# copy using normal method
result = dest.put(sourceFile, destFile)
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)
@ -472,19 +487,24 @@ class XbmcBackup:
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 = []
# save list of file sets
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(xbmcvfs.translatePath(utils.data_dir() + "xbmcbackup.val"), 'w') vFile = xbmcvfs.File(xbmcvfs.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(xbmcvfs.translatePath(utils.data_dir() + "xbmcbackup.val"), self.remote_vfs.root_path + "xbmcbackup.val") success = self._copyFile(self.xbmc_vfs, self.remote_vfs, xbmcvfs.translatePath(utils.data_dir() + "xbmcbackup.val"), self.remote_vfs.root_path + "xbmcbackup.val")
# remove the validation file # remove the validation file
xbmcvfs.delete(xbmcvfs.translatePath(utils.data_dir() + "xbmcbackup.val")) xbmcvfs.delete(xbmcvfs.translatePath(utils.data_dir() + "xbmcbackup.val"))
@ -495,7 +515,7 @@ class XbmcBackup:
nmFile = xbmcvfs.File(xbmcvfs.translatePath(utils.data_dir() + ".nomedia"), 'w') nmFile = xbmcvfs.File(xbmcvfs.translatePath(utils.data_dir() + ".nomedia"), 'w')
nmFile.close() nmFile.close()
success = self.remote_vfs.put(xbmcvfs.translatePath(utils.data_dir() + ".nomedia"), self.remote_vfs.root_path + ".nomedia") success = self._copyFile(self.xbmc_vfs, self.remote_vfs, xbmcvfs.translatePath(utils.data_dir() + ".nomedia"), self.remote_vfs.root_path + ".nomedia")
return success return success
@ -503,10 +523,7 @@ class XbmcBackup:
result = None result = None
# copy the file and open it # copy the file and open it
if(isinstance(self.remote_vfs, DropboxFileSystem)): self._copyFile(self.remote_vfs, self.xbmc_vfs, path + "xbmcbackup.val", xbmcvfs.translatePath(utils.data_dir() + "xbmcbackup_restore.val"))
self.remote_vfs.get_file(path + "xbmcbackup.val", xbmcvfs.translatePath(utils.data_dir() + "xbmcbackup_restore.val"))
else:
self.xbmc_vfs.put(path + "xbmcbackup.val", xbmcvfs.translatePath(utils.data_dir() + "xbmcbackup_restore.val"))
with xbmcvfs.File(xbmcvfs.translatePath(utils.data_dir() + "xbmcbackup_restore.val"), 'r') as vFile: with xbmcvfs.File(xbmcvfs.translatePath(utils.data_dir() + "xbmcbackup_restore.val"), 'r') as vFile:
jsonString = vFile.read() jsonString = vFile.read()

View File

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

View File

@ -3,6 +3,7 @@
<category id="general" label="30011" level="expert"> <category id="general" label="30011" level="expert">
<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 type="sep" /> <setting type="sep" />
<setting id="verbose_logging" type="bool" label="Enable Verbose Logging" default="false" /> <setting id="verbose_logging" type="bool" label="Enable Verbose Logging" default="false" />