split backup and restore into separate functions

This commit is contained in:
robweber 2019-07-29 16:58:00 -05:00
parent dcc8482d73
commit 83a01a48bf
3 changed files with 903 additions and 887 deletions

View File

@ -1,77 +1,79 @@
import urlparse import sys, urlparse
import xbmcgui import xbmcgui
import resources.lib.utils as utils import resources.lib.utils as utils
from resources.lib.backup import XbmcBackup from resources.lib.backup import XbmcBackup
def get_params(): def get_params():
param = {} param = {}
if(len(sys.argv) > 1): if(len(sys.argv) > 1):
for i in sys.argv: for i in sys.argv:
args = i args = i
if(args.startswith('?')): if(args.startswith('?')):
args = args[1:] args = args[1:]
param.update(dict(urlparse.parse_qsl(args))) param.update(dict(urlparse.parse_qsl(args)))
return param return param
#the program mode #the program mode
mode = -1 mode = -1
params = get_params() params = get_params()
if("mode" in params): if("mode" in params):
if(params['mode'] == 'backup'): if(params['mode'] == 'backup'):
mode = 0 mode = 0
elif(params['mode'] == 'restore'): elif(params['mode'] == 'restore'):
mode = 1 mode = 1
#if mode wasn't passed in as arg, get from user #if mode wasn't passed in as arg, get from user
if(mode == -1): if(mode == -1):
#figure out if this is a backup or a restore from the user #figure out if this is a backup or a restore from the user
mode = xbmcgui.Dialog().select(utils.getString(30010) + " - " + utils.getString(30023),[utils.getString(30016),utils.getString(30017),utils.getString(30099)]) mode = xbmcgui.Dialog().select(utils.getString(30010) + " - " + utils.getString(30023),[utils.getString(30016),utils.getString(30017),utils.getString(30099)])
#check if program should be run #check if program should be run
if(mode != -1): if(mode != -1):
#run the profile backup #run the profile backup
backup = XbmcBackup() backup = XbmcBackup()
if(mode == 2): if(mode == 2):
#open the settings dialog #open the settings dialog
utils.openSettings() utils.openSettings()
elif(backup.remoteConfigured()): elif(backup.remoteConfigured()):
if(mode == backup.Restore): if(mode == backup.Restore):
#get list of valid restore points #get list of valid restore points
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])
selectedRestore = -1 selectedRestore = -1
if("archive" in params): if("archive" in params):
#check that the user give archive exists #check that the user give archive exists
if(params['archive'] in folderNames): if(params['archive'] in folderNames):
#set the index #set the index
selectedRestore = folderNames.index(params['archive']) selectedRestore = folderNames.index(params['archive'])
utils.log(str(selectedRestore) + " : " + params['archive']) utils.log(str(selectedRestore) + " : " + params['archive'])
else: else:
utils.showNotification(utils.getString(30045)) utils.showNotification(utils.getString(30045))
utils.log(params['archive'] + ' is not a valid restore point') utils.log(params['archive'] + ' is not a valid restore point')
else: else:
#allow user to select the backup to restore from #allow user to select the backup to restore from
selectedRestore = xbmcgui.Dialog().select(utils.getString(30010) + " - " + utils.getString(30021),pointNames) selectedRestore = xbmcgui.Dialog().select(utils.getString(30010) + " - " + utils.getString(30021),pointNames)
if(selectedRestore != -1): if(selectedRestore != -1):
backup.selectRestore(restorePoints[selectedRestore][0]) backup.selectRestore(restorePoints[selectedRestore][0])
backup.run(mode) backup.restore()
else: else:
#can't go any further backup.backup()
xbmcgui.Dialog().ok(utils.getString(30010),utils.getString(30045)) else:
utils.openSettings() #can't go any further
xbmcgui.Dialog().ok(utils.getString(30010),utils.getString(30045))
utils.openSettings()

File diff suppressed because it is too large Load Diff

View File

@ -1,196 +1,196 @@
import xbmc import xbmc
import xbmcvfs import xbmcvfs
import xbmcgui import xbmcgui
import datetime import datetime
import time import time
import os import os
import resources.lib.utils as utils import resources.lib.utils as utils
from resources.lib.croniter import croniter from resources.lib.croniter import croniter
from resources.lib.backup import XbmcBackup from resources.lib.backup import XbmcBackup
UPGRADE_INT = 1 #to keep track of any upgrade notifications UPGRADE_INT = 1 #to keep track of any upgrade notifications
class BackupScheduler: class BackupScheduler:
monitor = None monitor = None
enabled = "false" enabled = "false"
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")
self.next_run_path = xbmc.translatePath(utils.data_dir()) + 'next_run.txt' self.next_run_path = xbmc.translatePath(utils.data_dir()) + 'next_run.txt'
if(self.enabled == "true"): if(self.enabled == "true"):
nr = 0 nr = 0
if(xbmcvfs.exists(self.next_run_path)): if(xbmcvfs.exists(self.next_run_path)):
fh = xbmcvfs.File(self.next_run_path) fh = xbmcvfs.File(self.next_run_path)
try: try:
#check if we saved a run time from the last run #check if we saved a run time from the last run
nr = float(fh.read()) nr = float(fh.read())
except ValueError: except ValueError:
nr = 0 nr = 0
fh.close() fh.close()
#if we missed and the user wants to play catch-up #if we missed and the user wants to play catch-up
if(0 < nr <= time.time() and utils.getSetting('schedule_miss') == 'true'): if(0 < nr <= time.time() and utils.getSetting('schedule_miss') == 'true'):
utils.log("scheduled backup was missed, doing it now...") utils.log("scheduled backup was missed, doing it now...")
progress_mode = int(utils.getSetting('progress_mode')) progress_mode = int(utils.getSetting('progress_mode'))
if(progress_mode == 0): if(progress_mode == 0):
progress_mode = 1 # Kodi just started, don't block it with a foreground progress bar progress_mode = 1 # Kodi just started, don't block it with a foreground progress bar
self.doScheduledBackup(progress_mode) self.doScheduledBackup(progress_mode)
self.setup() self.setup()
def setup(self): def setup(self):
#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
if(int(utils.getSetting('upgrade_notes')) < UPGRADE_INT): if(int(utils.getSetting('upgrade_notes')) < UPGRADE_INT):
xbmcgui.Dialog().ok(utils.getString(30010),utils.getString(30132)) xbmcgui.Dialog().ok(utils.getString(30010),utils.getString(30132))
utils.setSetting('upgrade_notes',str(UPGRADE_INT)) utils.setSetting('upgrade_notes',str(UPGRADE_INT))
#check if a backup should be resumed #check if a backup should be resumed
resumeRestore = self._resumeCheck() resumeRestore = self._resumeCheck()
if(resumeRestore): if(resumeRestore):
restore = XbmcBackup() restore = XbmcBackup()
restore.selectRestore(self.restore_point) restore.selectRestore(self.restore_point)
#skip the advanced settings check #skip the advanced settings check
restore.skipAdvanced() restore.skipAdvanced()
restore.run(XbmcBackup.Restore) restore.restore()
while(not xbmc.abortRequested): while(not xbmc.abortRequested):
if(self.enabled == "true"): if(self.enabled == "true"):
#scheduler is still on #scheduler is still on
now = time.time() now = time.time()
if(self.next_run <= now): if(self.next_run <= now):
progress_mode = int(utils.getSetting('progress_mode')) progress_mode = int(utils.getSetting('progress_mode'))
self.doScheduledBackup(progress_mode) self.doScheduledBackup(progress_mode)
#check if we should shut the computer down #check if we should shut the computer down
if(utils.getSetting("cron_shutdown") == 'true'): if(utils.getSetting("cron_shutdown") == 'true'):
#wait 10 seconds to make sure all backup processes and files are completed #wait 10 seconds to make sure all backup processes and files are completed
time.sleep(10) time.sleep(10)
xbmc.executebuiltin('ShutDown()') xbmc.executebuiltin('ShutDown()')
else: else:
#find the next run time like normal #find the next run time like normal
self.findNextRun(now) self.findNextRun(now)
xbmc.sleep(500) xbmc.sleep(500)
#delete monitor to free up memory #delete monitor to free up memory
del self.monitor del self.monitor
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.run(XbmcBackup.Backup,True) backup.backup(True)
else: else:
backup.run(XbmcBackup.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
self.enabled = "false" self.enabled = "false"
utils.setSetting('enable_scheduler','false') utils.setSetting('enable_scheduler','false')
else: else:
utils.showNotification(utils.getString(30045)) utils.showNotification(utils.getString(30045))
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()
cron_ob = croniter(cron_exp,datetime.datetime.fromtimestamp(now)) cron_ob = croniter(cron_exp,datetime.datetime.fromtimestamp(now))
new_run_time = cron_ob.get_next(float) new_run_time = cron_ob.get_next(float)
if(new_run_time != self.next_run): if(new_run_time != self.next_run):
self.next_run = new_run_time self.next_run = new_run_time
utils.log("scheduler will run again on " + datetime.datetime.fromtimestamp(self.next_run).strftime('%m-%d-%Y %H:%M')) utils.log("scheduler will run again on " + datetime.datetime.fromtimestamp(self.next_run).strftime('%m-%d-%Y %H:%M'))
#write the next time to a file #write the next time to a file
fh = xbmcvfs.File(self.next_run_path, 'w') fh = xbmcvfs.File(self.next_run_path, 'w')
fh.write(str(self.next_run)) fh.write(str(self.next_run))
fh.close() fh.close()
#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) + " " + datetime.datetime.fromtimestamp(self.next_run).strftime('%m-%d-%Y %H:%M')) utils.showNotification(utils.getString(30081) + " " + datetime.datetime.fromtimestamp(self.next_run).strftime('%m-%d-%Y %H:%M'))
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
self.setup() self.setup()
elif (current_enabled == "false" and self.enabled == "true"): elif (current_enabled == "false" and self.enabled == "true"):
#schedule was turn off #schedule was turn off
self.enabled = current_enabled self.enabled = current_enabled
if(self.enabled == "true"): if(self.enabled == "true"):
#always recheck the next run time after an update #always recheck the next run time after an update
self.findNextRun(time.time()) self.findNextRun(time.time())
def parseSchedule(self): def parseSchedule(self):
schedule_type = int(utils.getSetting("schedule_interval")) schedule_type = int(utils.getSetting("schedule_interval"))
cron_exp = utils.getSetting("cron_schedule") cron_exp = utils.getSetting("cron_schedule")
hour_of_day = utils.getSetting("schedule_time") hour_of_day = utils.getSetting("schedule_time")
hour_of_day = int(hour_of_day[0:2]) hour_of_day = int(hour_of_day[0:2])
if(schedule_type == 0 or schedule_type == 1): if(schedule_type == 0 or schedule_type == 1):
#every day #every day
cron_exp = "0 " + str(hour_of_day) + " * * *" cron_exp = "0 " + str(hour_of_day) + " * * *"
elif(schedule_type == 2): elif(schedule_type == 2):
#once a week #once a week
day_of_week = utils.getSetting("day_of_week") day_of_week = utils.getSetting("day_of_week")
cron_exp = "0 " + str(hour_of_day) + " * * " + day_of_week cron_exp = "0 " + str(hour_of_day) + " * * " + day_of_week
elif(schedule_type == 3): elif(schedule_type == 3):
#first day of month #first day of month
cron_exp = "0 " + str(hour_of_day) + " 1 * *" cron_exp = "0 " + str(hour_of_day) + " 1 * *"
return cron_exp return cron_exp
def _resumeCheck(self): def _resumeCheck(self):
shouldContinue = False shouldContinue = False
if(xbmcvfs.exists(xbmc.translatePath(utils.data_dir() + "resume.txt"))): if(xbmcvfs.exists(xbmc.translatePath(utils.data_dir() + "resume.txt"))):
rFile = xbmcvfs.File(xbmc.translatePath(utils.data_dir() + "resume.txt"),'r') rFile = xbmcvfs.File(xbmc.translatePath(utils.data_dir() + "resume.txt"),'r')
self.restore_point = rFile.read() self.restore_point = rFile.read()
rFile.close() rFile.close()
xbmcvfs.delete(xbmc.translatePath(utils.data_dir() + "resume.txt")) xbmcvfs.delete(xbmc.translatePath(utils.data_dir() + "resume.txt"))
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
def __init__(self,*args, **kwargs): def __init__(self,*args, **kwargs):
xbmc.Monitor.__init__(self) xbmc.Monitor.__init__(self)
self.update_method = kwargs['update_method'] self.update_method = kwargs['update_method']
def onSettingsChanged(self): def onSettingsChanged(self):
self.update_method() self.update_method()
BackupScheduler().start() BackupScheduler().start()