pep8 spaces

This commit is contained in:
Rob Weber 2019-11-25 15:33:34 -06:00
parent fea7dca500
commit 0c79aef4e7
10 changed files with 158 additions and 168 deletions

View File

@ -33,7 +33,7 @@ if("mode" in params):
if(mode == -1): if(mode == -1):
# by default, Backup,Restore,Open Settings # by default, Backup,Restore,Open Settings
options = [utils.getString(30016),utils.getString(30017),utils.getString(30099)] options = [utils.getString(30016),utils.getString(30017),utils.getString(30099)]
# find out if we're using the advanced editor # find out if we're using the advanced editor
if(int(utils.getSetting('backup_selection_type')) == 1): if(int(utils.getSetting('backup_selection_type')) == 1):
options.append(utils.getString(30125)) options.append(utils.getString(30125))
@ -59,7 +59,7 @@ if(mode != -1):
restorePoints = backup.listBackups() restorePoints = backup.listBackups()
pointNames = [] pointNames = []
folderNames = [] folderNames = []
for aDir in restorePoints: for aDir in restorePoints:
pointNames.append(aDir[1]) pointNames.append(aDir[1])
folderNames.append(aDir[0]) folderNames.append(aDir[0])
@ -81,7 +81,7 @@ if(mode != -1):
if(selectedRestore != -1): if(selectedRestore != -1):
backup.selectRestore(restorePoints[selectedRestore][0]) backup.selectRestore(restorePoints[selectedRestore][0])
if('sets' in params): if('sets' in params):
backup.restore(selectedSets=params['sets'].split('|')) backup.restore(selectedSets=params['sets'].split('|'))
else: else:

View File

@ -4,7 +4,6 @@ import resources.lib.utils as utils
from resources.lib.authorizers import DropboxAuthorizer from resources.lib.authorizers import DropboxAuthorizer
from resources.lib.advanced_editor import AdvancedBackupEditor from resources.lib.advanced_editor import AdvancedBackupEditor
# launcher for various helpful functions found in the settings.xml area # launcher for various helpful functions found in the settings.xml area
def authorize_cloud(cloudProvider): def authorize_cloud(cloudProvider):

View File

@ -5,10 +5,10 @@ from . import utils as utils
class BackupSetManager: class BackupSetManager:
jsonFile = xbmc.translatePath(utils.data_dir() + "custom_paths.json") jsonFile = xbmc.translatePath(utils.data_dir() + "custom_paths.json")
paths = None paths = None
def __init__(self): def __init__(self):
self.paths = {} self.paths = {}
# try and read in the custom file # try and read in the custom file
self._readFile() self._readFile()
@ -33,7 +33,7 @@ class BackupSetManager:
#save the file #save the file
self._writeFile() self._writeFile()
def getSets(self): def getSets(self):
# list all current sets by name # list all current sets by name
keys = list(self.paths.keys()) keys = list(self.paths.keys())
@ -55,7 +55,7 @@ class BackupSetManager:
aFile = xbmcvfs.File(self.jsonFile,'w') aFile = xbmcvfs.File(self.jsonFile,'w')
aFile.write(json.dumps(self.paths)) aFile.write(json.dumps(self.paths))
aFile.close() aFile.close()
def _readFile(self): def _readFile(self):
if(xbmcvfs.exists(self.jsonFile)): if(xbmcvfs.exists(self.jsonFile)):
@ -84,7 +84,7 @@ class AdvancedBackupEditor:
def createSet(self): def createSet(self):
backupSet = None backupSet = None
name = self.dialog.input(utils.getString(30110),defaultt='Backup Set') name = self.dialog.input(utils.getString(30110),defaultt='Backup Set')
if(name != None): if(name != None):
@ -109,7 +109,7 @@ class AdvancedBackupEditor:
rootFolder = self.dialog.browse(type=0,heading=utils.getString(30119),shares='files',defaultt=rootFolder) rootFolder = self.dialog.browse(type=0,heading=utils.getString(30119),shares='files',defaultt=rootFolder)
backupSet = {'name':name,'root':rootFolder} backupSet = {'name':name,'root':rootFolder}
return backupSet return backupSet
def editSet(self,name,backupSet): def editSet(self,name,backupSet):
@ -130,9 +130,9 @@ class AdvancedBackupEditor:
if(optionSelected == 0 or optionSelected == 1): if(optionSelected == 0 or optionSelected == 1):
# add a folder, will equal root if cancel is hit # add a folder, will equal root if cancel is hit
addFolder = self.dialog.browse(type=0,heading=utils.getString(30120),shares='files',defaultt=backupSet['root']) addFolder = self.dialog.browse(type=0,heading=utils.getString(30120),shares='files',defaultt=backupSet['root'])
if(addFolder.startswith(rootPath)): if(addFolder.startswith(rootPath)):
if(not any(addFolder == aDir['path'] for aDir in backupSet['dirs'])): if(not any(addFolder == aDir['path'] for aDir in backupSet['dirs'])):
# cannot add root as an exclusion # cannot add root as an exclusion
if(optionSelected == 0 and addFolder != backupSet['root']): if(optionSelected == 0 and addFolder != backupSet['root']):
@ -149,13 +149,13 @@ class AdvancedBackupEditor:
elif(optionSelected == 2): elif(optionSelected == 2):
self.dialog.ok(utils.getString(30121),utils.getString(30130),backupSet['root']) self.dialog.ok(utils.getString(30121),utils.getString(30130),backupSet['root'])
elif(optionSelected > 2): elif(optionSelected > 2):
cOptions = ['Delete'] cOptions = ['Delete']
if(backupSet['dirs'][optionSelected - 3]['type'] == 'include'): if(backupSet['dirs'][optionSelected - 3]['type'] == 'include'):
cOptions.append('Toggle Sub Folders') cOptions.append('Toggle Sub Folders')
contextOption = self.dialog.contextmenu(cOptions) contextOption = self.dialog.contextmenu(cOptions)
if(contextOption == 0): if(contextOption == 0):
if(self.dialog.yesno(heading=utils.getString(30123),line1=utils.getString(30128))): if(self.dialog.yesno(heading=utils.getString(30123),line1=utils.getString(30128))):
# remove folder # remove folder
@ -165,7 +165,6 @@ class AdvancedBackupEditor:
backupSet['dirs'][optionSelected - 3]['recurse'] = not backupSet['dirs'][optionSelected - 3]['recurse'] backupSet['dirs'][optionSelected - 3]['recurse'] = not backupSet['dirs'][optionSelected - 3]['recurse']
return backupSet return backupSet
def showMainScreen(self): def showMainScreen(self):
exitCondition = "" exitCondition = ""
@ -177,14 +176,14 @@ class AdvancedBackupEditor:
while(exitCondition != -1): while(exitCondition != -1):
# load the custom paths # load the custom paths
options = [xbmcgui.ListItem(utils.getString(30126),'',utils.addon_dir() + '/resources/images/plus-icon.png')] options = [xbmcgui.ListItem(utils.getString(30126),'',utils.addon_dir() + '/resources/images/plus-icon.png')]
for index in range(0,len(customPaths.getSets())): for index in range(0,len(customPaths.getSets())):
aSet = customPaths.getSet(index) aSet = customPaths.getSet(index)
options.append(xbmcgui.ListItem(aSet['name'],utils.getString(30121) + ': ' + aSet['set']['root'],utils.addon_dir() + '/resources/images/folder-icon.png')) options.append(xbmcgui.ListItem(aSet['name'],utils.getString(30121) + ': ' + aSet['set']['root'],utils.addon_dir() + '/resources/images/folder-icon.png'))
# show the gui # show the gui
exitCondition = self.dialog.select(utils.getString(30125),options,useDetails=True) exitCondition = self.dialog.select(utils.getString(30125),options,useDetails=True)
if(exitCondition >= 0): if(exitCondition >= 0):
if(exitCondition == 0): if(exitCondition == 0):
newSet = self.createSet() newSet = self.createSet()
@ -201,13 +200,13 @@ class AdvancedBackupEditor:
if(menuOption == 0): if(menuOption == 0):
# get the set # get the set
aSet = customPaths.getSet(exitCondition -1) aSet = customPaths.getSet(exitCondition -1)
# edit the set # edit the set
updatedSet = self.editSet(aSet['name'],aSet['set']) updatedSet = self.editSet(aSet['name'],aSet['set'])
# save it # save it
customPaths.updateSet(aSet['name'],updatedSet) customPaths.updateSet(aSet['name'],updatedSet)
elif(menuOption == 1): elif(menuOption == 1):
if(self.dialog.yesno(heading=utils.getString(30127),line1=utils.getString(30128))): if(self.dialog.yesno(heading=utils.getString(30127),line1=utils.getString(30128))):
# delete this path - subtract one because of "add" item # delete this path - subtract one because of "add" item
@ -223,5 +222,4 @@ class AdvancedBackupEditor:
xbmcvfs.copy(source,dest) xbmcvfs.copy(source,dest)

View File

@ -18,14 +18,14 @@ class DropboxAuthorizer:
def setup(self): def setup(self):
result = True result = True
if(self.APP_KEY == '' and self.APP_SECRET == ''): if(self.APP_KEY == '' and self.APP_SECRET == ''):
# we can't go any farther, need these for sure # we can't go any farther, need these for sure
xbmcgui.Dialog().ok(utils.getString(30010),utils.getString(30027) + ' ' + utils.getString(30058),utils.getString(30059)) xbmcgui.Dialog().ok(utils.getString(30010),utils.getString(30027) + ' ' + utils.getString(30058),utils.getString(30059))
result = False result = False
return result return result
def isAuthorized(self): def isAuthorized(self):
user_token = self._getToken() user_token = self._getToken()
@ -37,7 +37,7 @@ class DropboxAuthorizer:
if(not self.setup()): if(not self.setup()):
return False return False
if(self.isAuthorized()): if(self.isAuthorized()):
# delete the token to start over # delete the token to start over
self._deleteToken() self._deleteToken()
@ -53,7 +53,7 @@ class DropboxAuthorizer:
# get the auth code # get the auth code
code = xbmcgui.Dialog().input(utils.getString(30027) + ' ' + utils.getString(30103)) code = xbmcgui.Dialog().input(utils.getString(30027) + ' ' + utils.getString(30103))
#if user authorized this will work #if user authorized this will work
try: try:
@ -62,7 +62,7 @@ class DropboxAuthorizer:
except Exception as e: except Exception as e:
utils.log("Error: %s" % (e,)) utils.log("Error: %s" % (e,))
result = False result = False
return result; return result;
# return the DropboxClient, or None if can't be created # return the DropboxClient, or None if can't be created
@ -81,7 +81,7 @@ class DropboxAuthorizer:
#this didn't work, delete the token file #this didn't work, delete the token file
self._deleteToken() self._deleteToken()
result = None result = None
return result return result
def _setToken(self,token): def _setToken(self,token):
@ -100,7 +100,7 @@ class DropboxAuthorizer:
return token return token
else: else:
return "" return ""
def _deleteToken(self): def _deleteToken(self):
if(xbmcvfs.exists(xbmc.translatePath(utils.data_dir() + "tokens.txt"))): if(xbmcvfs.exists(xbmc.translatePath(utils.data_dir() + "tokens.txt"))):
xbmcvfs.delete(xbmc.translatePath(utils.data_dir() + "tokens.txt")) xbmcvfs.delete(xbmc.translatePath(utils.data_dir() + "tokens.txt"))

View File

@ -11,12 +11,11 @@ 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
@ -30,10 +29,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
@ -41,7 +40,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'))
@ -74,7 +73,7 @@ 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")):
@ -86,17 +85,16 @@ class XbmcBackup:
for aFile in files: for aFile in files:
file_ext = aFile.split('.')[-1] file_ext = aFile.split('.')[-1]
folderName = aFile.split('.')[0] folderName = aFile.split('.')[0]
if(file_ext == 'zip' and len(folderName) == 12 and folderName.isdigit()): if(file_ext == 'zip' and len(folderName) == 12 and folderName.isdigit()):
# 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):
@ -125,7 +123,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
@ -138,74 +136,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))
@ -213,38 +211,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)
@ -258,7 +256,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
@ -284,14 +282,14 @@ 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
@ -316,7 +314,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) # update the guisettings information (or what we can from it)
gui_settings = GuiSettingsManager() gui_settings = GuiSettingsManager()
gui_settings.run() gui_settings.run()
@ -328,7 +325,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 != ''):
@ -339,11 +336,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 != ''):
@ -358,7 +355,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) + "......")
@ -380,11 +377,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)
@ -393,7 +390,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)): if(isinstance(source,DropboxFileSystem)):
@ -402,18 +399,17 @@ 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)
@ -422,16 +418,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):
@ -440,11 +436,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
@ -454,30 +450,30 @@ 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_base_path + dirs[remove_num][0]) self.remote_vfs.rmfile(self.remote_base_path + dirs[remove_num][0])
else: else:
self.remote_vfs.rmdir(self.remote_base_path + dirs[remove_num][0] + "/") self.remote_vfs.rmdir(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}
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
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"))
@ -488,12 +484,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)): if(isinstance(self.remote_vfs,DropboxFileSystem)):
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"))
@ -538,7 +534,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 = []
@ -546,7 +542,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'])
@ -555,7 +551,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)
@ -576,10 +572,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)
@ -590,18 +586,18 @@ 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):
# write the full remote path name of this file # write the full remote path name of this file
utils.log("Add File: " + filename) utils.log("Add File: " + filename)
self.fileArray.append(filename) self.fileArray.append(filename)
def excludeFile(self,filename): def excludeFile(self,filename):
# 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)
@ -611,7 +607,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

@ -7,41 +7,41 @@ from xml.parsers.expat import ExpatError
class GuiSettingsManager: class GuiSettingsManager:
doc = None doc = None
def __init__(self): def __init__(self):
# first make a copy of the file # first make a copy of the file
xbmcvfs.copy(xbmc.translatePath('special://home/userdata/guisettings.xml'), xbmc.translatePath("special://home/userdata/guisettings.xml.restored")) xbmcvfs.copy(xbmc.translatePath('special://home/userdata/guisettings.xml'), xbmc.translatePath("special://home/userdata/guisettings.xml.restored"))
# read in the copy # read in the copy
self._readFile(xbmc.translatePath('special://home/userdata/guisettings.xml.restored')) self._readFile(xbmc.translatePath('special://home/userdata/guisettings.xml.restored'))
def run(self): def run(self):
# get a list of all the settings we can manipulate via json # 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"}}')) json_response = json.loads(xbmc.executeJSONRPC('{"jsonrpc":"2.0", "id":1, "method":"Settings.GetSettings","params":{"level":"advanced"}}'))
settings = json_response['result']['settings'] settings = json_response['result']['settings']
currentSettings = {} currentSettings = {}
for aSetting in settings: for aSetting in settings:
if('value' in aSetting): if('value' in aSetting):
currentSettings[aSetting['id']] = aSetting['value'] currentSettings[aSetting['id']] = aSetting['value']
# parse the existing xml file and get all the settings we need to restore # parse the existing xml file and get all the settings we need to restore
restoreSettings = self.__parseNodes(self.doc.getElementsByTagName('setting')) restoreSettings = self.__parseNodes(self.doc.getElementsByTagName('setting'))
# get a list where the restore setting value != the current value # 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)} 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 # go through all the found settings and update them
jsonObj = {"jsonrpc":"2.0","id":1,"method":"Settings.SetSettingValue","params":{"setting":"","value":""}} jsonObj = {"jsonrpc":"2.0","id":1,"method":"Settings.SetSettingValue","params":{"setting":"","value":""}}
for anId, aValue in list(updateSettings.items()): for anId, aValue in list(updateSettings.items()):
utils.log("updating: " + anId + ", value: " + str(aValue)) utils.log("updating: " + anId + ", value: " + str(aValue))
jsonObj['params']['setting'] = anId jsonObj['params']['setting'] = anId
jsonObj['params']['value'] = aValue jsonObj['params']['value'] = aValue
xbmc.executeJSONRPC(json.dumps(jsonObj)) xbmc.executeJSONRPC(json.dumps(jsonObj))
def __parseNodes(self,nodeList): def __parseNodes(self,nodeList):
result = {} result = {}
@ -49,7 +49,7 @@ class GuiSettingsManager:
nodeValue = '' nodeValue = ''
if(node.firstChild != None): if(node.firstChild != None):
nodeValue = node.firstChild.nodeValue nodeValue = node.firstChild.nodeValue
# check for numbers and booleans # check for numbers and booleans
if(nodeValue.isdigit()): if(nodeValue.isdigit()):
nodeValue = int(nodeValue) nodeValue = int(nodeValue)
@ -57,17 +57,16 @@ class GuiSettingsManager:
nodeValue = True nodeValue = True
elif(nodeValue == 'false'): elif(nodeValue == 'false'):
nodeValue = False nodeValue = False
result[node.getAttribute('id')] = nodeValue result[node.getAttribute('id')] = nodeValue
return result return result
def _readFile(self,fileLoc): def _readFile(self,fileLoc):
if(xbmcvfs.exists(fileLoc)): if(xbmcvfs.exists(fileLoc)):
try: try:
self.doc = minidom.parse(fileLoc) self.doc = minidom.parse(fileLoc)
except ExpatError: except ExpatError:
utils.log("Can't read " + fileLoc) utils.log("Can't read " + fileLoc)

View File

@ -9,10 +9,10 @@ class BackupProgressBar:
mode = 2 mode = 2
progressBar = None progressBar = None
override = False override = False
def __init__(self,progressOverride): def __init__(self,progressOverride):
self.override = progressOverride self.override = progressOverride
# check if we should use the progress bar # check if we should use the progress bar
if(int(utils.getSetting('progress_mode')) != 2): if(int(utils.getSetting('progress_mode')) != 2):
# check if background or normal # check if background or normal
@ -28,7 +28,7 @@ class BackupProgressBar:
self.progressBar.create(heading,message) self.progressBar.create(heading,message)
def updateProgress(self,percent,message=None): def updateProgress(self,percent,message=None):
# update the progress bar # update the progress bar
if(self.mode != self.NONE): if(self.mode != self.NONE):
if(message != None): if(message != None):

View File

@ -29,9 +29,9 @@ def getString(string_id):
def getRegionalTimestamp(date_time,dateformat=['dateshort']): def getRegionalTimestamp(date_time,dateformat=['dateshort']):
result = '' result = ''
for aFormat in dateformat: for aFormat in dateformat:
result = result + ("%s " % date_time.strftime(xbmc.getRegion(aFormat))) result = result + ("%s " % date_time.strftime(xbmc.getRegion(aFormat)))
return result.strip() return result.strip()

View File

@ -13,21 +13,21 @@ class Vfs:
def __init__(self,rootString): def __init__(self,rootString):
self.set_root(rootString) self.set_root(rootString)
def set_root(self,rootString): def set_root(self,rootString):
old_root = self.root_path old_root = self.root_path
self.root_path = rootString self.root_path = rootString
# fix slashes # fix slashes
self.root_path = self.root_path.replace("\\","/") self.root_path = self.root_path.replace("\\","/")
# check if trailing slash is included # check if trailing slash is included
if(self.root_path[-1:] != "/"): if(self.root_path[-1:] != "/"):
self.root_path = self.root_path + "/" self.root_path = self.root_path + "/"
# return the old root # return the old root
return old_root return old_root
def listdir(self,directory): def listdir(self,directory):
return {} return {}
@ -45,13 +45,13 @@ class Vfs:
def exists(self,aFile): def exists(self,aFile):
return True return True
def rename(self,aFile,newName): def rename(self,aFile,newName):
return True return True
def cleanup(self): def cleanup(self):
return True return True
class XBMCFileSystem(Vfs): class XBMCFileSystem(Vfs):
def listdir(self,directory): def listdir(self,directory):
@ -62,7 +62,7 @@ class XBMCFileSystem(Vfs):
def put(self,source,dest): def put(self,source,dest):
return xbmcvfs.copy(xbmc.translatePath(source),xbmc.translatePath(dest)) return xbmcvfs.copy(xbmc.translatePath(source),xbmc.translatePath(dest))
def rmdir(self,directory): def rmdir(self,directory):
return xbmcvfs.rmdir(directory,True) return xbmcvfs.rmdir(directory,True)
@ -77,39 +77,39 @@ class XBMCFileSystem(Vfs):
class ZipFileSystem(Vfs): class ZipFileSystem(Vfs):
zip = None zip = None
def __init__(self,rootString,mode): def __init__(self,rootString,mode):
self.root_path = "" self.root_path = ""
self.zip = zipfile.ZipFile(rootString,mode=mode,compression=zipfile.ZIP_DEFLATED,allowZip64=True) self.zip = zipfile.ZipFile(rootString,mode=mode,compression=zipfile.ZIP_DEFLATED,allowZip64=True)
def listdir(self,directory): def listdir(self,directory):
return [[],[]] return [[],[]]
def mkdir(self,directory): def mkdir(self,directory):
# self.zip.write(directory[len(self.root_path):]) # self.zip.write(directory[len(self.root_path):])
return False return False
def put(self,source,dest): def put(self,source,dest):
aFile = xbmcvfs.File(xbmc.translatePath(source),'r') aFile = xbmcvfs.File(xbmc.translatePath(source),'r')
self.zip.writestr(dest,aFile.readBytes()) self.zip.writestr(dest,aFile.readBytes())
return True return True
def rmdir(self,directory): def rmdir(self,directory):
return False return False
def exists(self,aFile): def exists(self,aFile):
return False return False
def cleanup(self): def cleanup(self):
self.zip.close() self.zip.close()
def extract(self,aFile,path): def extract(self,aFile,path):
# extract zip file to path # extract zip file to path
self.zip.extract(aFile,path) self.zip.extract(aFile,path)
def listFiles(self): def listFiles(self):
return self.zip.infolist() return self.zip.infolist()
@ -118,7 +118,7 @@ class DropboxFileSystem(Vfs):
client = None client = None
APP_KEY = '' APP_KEY = ''
APP_SECRET = '' APP_SECRET = ''
def __init__(self,rootString): def __init__(self,rootString):
self.set_root(rootString) self.set_root(rootString)
@ -133,7 +133,7 @@ class DropboxFileSystem(Vfs):
def listdir(self,directory): def listdir(self,directory):
directory = self._fix_slashes(directory) directory = self._fix_slashes(directory)
if(self.client != None and self.exists(directory)): if(self.client != None and self.exists(directory)):
files = [] files = []
dirs = [] dirs = []
@ -148,7 +148,6 @@ class DropboxFileSystem(Vfs):
return [dirs,files] return [dirs,files]
else: else:
return [[],[]] return [[],[]]
def mkdir(self,directory): def mkdir(self,directory):
directory = self._fix_slashes(directory) directory = self._fix_slashes(directory)
@ -163,20 +162,20 @@ class DropboxFileSystem(Vfs):
if(self.client != None and self.exists(directory)): if(self.client != None and self.exists(directory)):
# dropbox is stupid and will refuse to do this sometimes, need to delete recursively # dropbox is stupid and will refuse to do this sometimes, need to delete recursively
dirs,files = self.listdir(directory) dirs,files = self.listdir(directory)
for aDir in dirs: for aDir in dirs:
self.rmdir(aDir) self.rmdir(aDir)
# finally remove the root directory # finally remove the root directory
self.client.files_delete(directory) self.client.files_delete(directory)
return True return True
else: else:
return False return False
def rmfile(self,aFile): def rmfile(self,aFile):
aFile = self._fix_slashes(aFile) aFile = self._fix_slashes(aFile)
if(self.client != None and self.exists(aFile)): if(self.client != None and self.exists(aFile)):
self.client.files_delete(aFile) self.client.files_delete(aFile)
return True return True
@ -185,12 +184,12 @@ class DropboxFileSystem(Vfs):
def exists(self,aFile): def exists(self,aFile):
aFile = self._fix_slashes(aFile) aFile = self._fix_slashes(aFile)
if(self.client != None): if(self.client != None):
# can't list root metadata # can't list root metadata
if(aFile == ''): if(aFile == ''):
return True return True
try: try:
meta_data = self.client.files_get_metadata(aFile) meta_data = self.client.files_get_metadata(aFile)
# if we make it here the file does exist # if we make it here the file does exist
@ -202,12 +201,12 @@ class DropboxFileSystem(Vfs):
def put(self,source,dest,retry=True): def put(self,source,dest,retry=True):
dest = self._fix_slashes(dest) dest = self._fix_slashes(dest)
if(self.client != None): if(self.client != None):
# open the file and get its size # open the file and get its size
f = open(source,'rb') f = open(source,'rb')
f_size = os.path.getsize(source) f_size = os.path.getsize(source)
try: try:
if(f_size < self.MAX_CHUNK): if(f_size < self.MAX_CHUNK):
# use the regular upload # use the regular upload
@ -216,7 +215,7 @@ class DropboxFileSystem(Vfs):
# start the upload session # start the upload session
upload_session = self.client.files_upload_session_start(f.read(self.MAX_CHUNK)) upload_session = self.client.files_upload_session_start(f.read(self.MAX_CHUNK))
upload_cursor = UploadSessionCursor(upload_session.session_id,f.tell()) upload_cursor = UploadSessionCursor(upload_session.session_id,f.tell())
while(f.tell() < f_size): while(f.tell() < f_size):
# check if we should finish the upload # check if we should finish the upload
if((f_size - f.tell()) <= self.MAX_CHUNK): if((f_size - f.tell()) <= self.MAX_CHUNK):
@ -226,12 +225,12 @@ class DropboxFileSystem(Vfs):
# upload a part and store the offset # upload a part and store the offset
self.client.files_upload_session_append_v2(f.read(self.MAX_CHUNK),upload_cursor) self.client.files_upload_session_append_v2(f.read(self.MAX_CHUNK),upload_cursor)
upload_cursor.offset = f.tell() upload_cursor.offset = f.tell()
# if no errors we're good! # if no errors we're good!
return True return True
except Exception as anError: except Exception as anError:
utils.log(str(anError)) utils.log(str(anError))
# if we have an exception retry # if we have an exception retry
if(retry): if(retry):
return self.put(source,dest,False) return self.put(source,dest,False)

View File

@ -13,7 +13,7 @@ class BackupScheduler:
next_run = 0 next_run = 0
next_run_path = None next_run_path = None
restore_point = None restore_point = None
def __init__(self): def __init__(self):
self.monitor = UpdateMonitor(update_method = self.settingsChanged) self.monitor = UpdateMonitor(update_method = self.settingsChanged)
self.enabled = utils.getSetting("enable_scheduler") self.enabled = utils.getSetting("enable_scheduler")
@ -52,7 +52,7 @@ class BackupScheduler:
# scheduler was turned on, find next run time # scheduler was turned on, find next run time
utils.log("scheduler enabled, finding next run time") utils.log("scheduler enabled, finding next run time")
self.findNextRun(time.time()) self.findNextRun(time.time())
def start(self): def start(self):
# display upgrade messages if they exist # display upgrade messages if they exist
@ -69,9 +69,9 @@ class BackupScheduler:
# skip the advanced settings check # skip the advanced settings check
restore.skipAdvanced() restore.skipAdvanced()
restore.restore() restore.restore()
while(not self.monitor.abortRequested()): while(not self.monitor.abortRequested()):
if(self.enabled == "true"): if(self.enabled == "true"):
# scheduler is still on # scheduler is still on
now = time.time() now = time.time()
@ -97,16 +97,16 @@ class BackupScheduler:
def doScheduledBackup(self,progress_mode): def doScheduledBackup(self,progress_mode):
if(progress_mode != 2): if(progress_mode != 2):
utils.showNotification(utils.getString(30053)) utils.showNotification(utils.getString(30053))
backup = XbmcBackup() backup = XbmcBackup()
if(backup.remoteConfigured()): if(backup.remoteConfigured()):
if(int(utils.getSetting('progress_mode')) in [0,1]): if(int(utils.getSetting('progress_mode')) in [0,1]):
backup.backup(True) backup.backup(True)
else: else:
backup.backup(False) backup.backup(False)
# check if this is a "one-off" # check if this is a "one-off"
if(int(utils.getSetting("schedule_interval")) == 0): if(int(utils.getSetting("schedule_interval")) == 0):
# disable the scheduler after this run # disable the scheduler after this run
@ -117,7 +117,7 @@ class BackupScheduler:
def findNextRun(self,now): def findNextRun(self,now):
progress_mode = int(utils.getSetting('progress_mode')) progress_mode = int(utils.getSetting('progress_mode'))
# find the cron expression and get the next run time # find the cron expression and get the next run time
cron_exp = self.parseSchedule() cron_exp = self.parseSchedule()
@ -136,10 +136,10 @@ class BackupScheduler:
# only show when not in silent mode # only show when not in silent mode
if(progress_mode != 2): if(progress_mode != 2):
utils.showNotification(utils.getString(30081) + " " + utils.getRegionalTimestamp(datetime.fromtimestamp(self.next_run),['dateshort','time'])) utils.showNotification(utils.getString(30081) + " " + utils.getRegionalTimestamp(datetime.fromtimestamp(self.next_run),['dateshort','time']))
def settingsChanged(self): def settingsChanged(self):
current_enabled = utils.getSetting("enable_scheduler") current_enabled = utils.getSetting("enable_scheduler")
if(current_enabled == "true" and self.enabled == "false"): if(current_enabled == "true" and self.enabled == "false"):
# scheduler was just turned on # scheduler was just turned on
self.enabled = current_enabled self.enabled = current_enabled
@ -181,7 +181,6 @@ class BackupScheduler:
shouldContinue = xbmcgui.Dialog().yesno(utils.getString(30042),utils.getString(30043),utils.getString(30044)) shouldContinue = xbmcgui.Dialog().yesno(utils.getString(30042),utils.getString(30043),utils.getString(30044))
return shouldContinue return shouldContinue
class UpdateMonitor(xbmc.Monitor): class UpdateMonitor(xbmc.Monitor):
update_method = None update_method = None
@ -192,5 +191,5 @@ class UpdateMonitor(xbmc.Monitor):
def onSettingsChanged(self): def onSettingsChanged(self):
self.update_method() self.update_method()
BackupScheduler().start() BackupScheduler().start()