This repository has been archived by the owner on Aug 31, 2023. It is now read-only.
/
BackupManager.py
1371 lines (1216 loc) · 55.6 KB
/
BackupManager.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# for localized messages
from boxbranding import getBoxType, getImageType, getImageDistro, getImageVersion, getImageBuild, getImageDevBuild, getMachineBrand, getMachineName
from os import path, stat, mkdir, listdir, remove, statvfs, chmod, walk
from time import localtime, time, strftime, mktime
from datetime import date, datetime
import tarfile, glob
from enigma import eTimer, eEnv, eDVBDB, quitMainloop
from . import _, PluginLanguageDomain
import Components.Task
from Components.About import about
from Components.ActionMap import ActionMap
from Components.Label import Label
from Components.Button import Button
from Components.MenuList import MenuList
from Components.config import configfile, config, ConfigSubsection, ConfigYesNo, ConfigSelection, ConfigText, ConfigNumber, ConfigLocations, NoSave, ConfigClock, ConfigDirectory
from Components.Harddisk import harddiskmanager
from Components.Sources.StaticText import StaticText
from Components.FileList import MultiFileSelectList, FileList
from Components.ScrollLabel import ScrollLabel
from Screens.Screen import Screen
from Components.Console import Console
from Screens.MessageBox import MessageBox
from Screens.Setup import Setup
from Tools.Notifications import AddPopupWithCallback
import fnmatch
autoBackupManagerTimer = None
SETTINGSRESTOREQUESTIONID = 'RestoreSettingsNotification'
PLUGINRESTOREQUESTIONID = 'RestorePluginsNotification'
NOPLUGINS = 'NoPluginsNotification'
hddchoises = []
for p in harddiskmanager.getMountedPartitions():
if path.exists(p.mountpoint):
d = path.normpath(p.mountpoint)
if p.mountpoint != '/':
hddchoises.append((p.mountpoint, d))
config.backupmanager = ConfigSubsection()
config.backupmanager.showboxname = ConfigYesNo(default=False)
defaultprefix = getImageDistro()[4:]
config.backupmanager.folderprefix = ConfigText(default=defaultprefix, fixed_size=False)
config.backupmanager.backuplocation = ConfigSelection(choices=hddchoises)
config.backupmanager.schedule = ConfigYesNo(default=False)
config.backupmanager.scheduletime = ConfigClock(default=0) # 1:00
config.backupmanager.repeattype = ConfigSelection(default="daily", choices=[("daily", _("Daily")), ("weekly", _("Weekly")), ("monthly", _("30 Days"))])
# Querying is enabled by default - asthat is what used to happen always
#
config.backupmanager.query = ConfigYesNo(default=True)
# If we do not yet have a record of a backup, assume it has never happened.
#
config.backupmanager.lastbackup = ConfigNumber(default=0)
# Max no. of backups to keep. 0 == keep them all
#
config.backupmanager.number_to_keep = ConfigNumber(default=0)
config.backupmanager.backupretry = ConfigNumber(default=30)
config.backupmanager.backupretrycount = NoSave(ConfigNumber(default=0))
config.backupmanager.nextscheduletime = NoSave(ConfigNumber(default=0))
config.backupmanager.backupdirs = ConfigLocations(
default=[eEnv.resolve('${sysconfdir}/enigma2/'), eEnv.resolve('${sysconfdir}/fstab'), eEnv.resolve('${sysconfdir}/hostname'), eEnv.resolve('${sysconfdir}/network/interfaces'), eEnv.resolve('${sysconfdir}/passwd'), eEnv.resolve('${sysconfdir}/shadow'), eEnv.resolve('${sysconfdir}/etc/shadow'),
eEnv.resolve('${sysconfdir}/resolv.conf'), eEnv.resolve('${sysconfdir}/ushare.conf'), eEnv.resolve('${sysconfdir}/inadyn.conf'), eEnv.resolve('${sysconfdir}/tuxbox/config/'), eEnv.resolve('${sysconfdir}/wpa_supplicant.conf'), '/usr/softcams/'])
config.backupmanager.xtraplugindir = ConfigDirectory(default='')
config.backupmanager.lastlog = ConfigText(default=' ', fixed_size=False)
def isRestorableSettings(imageversion):
minimum_version = 4.2
try:
imageversion = float(imageversion)
except:
return False
return imageversion >= minimum_version
def isRestorablePlugins(imageversion):
minimum_version = 4.2
try:
imageversion = float(imageversion)
except:
return False
return imageversion >= minimum_version
def isRestorableKernel(kernelversion):
# This check should no longer be necessary since auto-installed packages are no longer listed in the plugins backup.
# For more information please consult commit https://github.com/OpenViX/vix-core/commit/53a95067677651a3f2579a1b0d1f70172ccc493b
return True
#return kernelversion == about.getKernelVersionString()
def BackupManagerautostart(reason, session=None, **kwargs):
"""called with reason=1 to during /sbin/shutdown.sysvinit, with reason=0 at startup?"""
global autoBackupManagerTimer
global _session
now = int(time())
if reason == 0:
print "[BackupManager] AutoStart Enabled"
if session is not None:
_session = session
if autoBackupManagerTimer is None:
autoBackupManagerTimer = AutoBackupManagerTimer(session)
else:
if autoBackupManagerTimer is not None:
print "[BackupManager] Stop"
autoBackupManagerTimer.stop()
class VIXBackupManager(Screen):
skin = """<screen name="VIXBackupManager" position="center,center" size="560,400">
<ePixmap pixmap="skin_default/buttons/red.png" position="0,0" size="140,40" alphatest="on" />
<ePixmap pixmap="skin_default/buttons/green.png" position="140,0" size="140,40" alphatest="on" />
<ePixmap pixmap="skin_default/buttons/yellow.png" position="280,0" size="140,40" alphatest="on" />
<widget name="key_red" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
<widget name="key_green" position="140,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
<widget name="key_yellow" position="280,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#a08500" transparent="1" />
<ePixmap pixmap="skin_default/buttons/key_menu.png" position="0,40" size="35,25" alphatest="blend" transparent="1" zPosition="3" />
<ePixmap pixmap="skin_default/buttons/key_info.png" position="40,40" size="35,25" alphatest="blend" transparent="1" zPosition="3" />
<widget name="lab1" position="0,50" size="560,50" font="Regular; 18" zPosition="2" transparent="0" halign="center"/>
<widget name="list" position="10,105" size="540,260" scrollbarMode="showOnDemand" />
<widget name="backupstatus" position="10,370" size="400,30" font="Regular;20" zPosition="5" />
<applet type="onLayoutFinish">
self["list"].instance.setItemHeight(25)
</applet>
</screen>"""
def __init__(self, session, menu_path=""):
Screen.__init__(self, session)
screentitle = _("Backup manager")
self.menu_path = menu_path
if config.usage.show_menupath.value == 'large':
self.menu_path += screentitle
title = self.menu_path
self["menu_path_compressed"] = StaticText("")
self.menu_path += ' / '
elif config.usage.show_menupath.value == 'small':
title = screentitle
condtext = ""
if self.menu_path and not self.menu_path.endswith(' / '):
condtext = self.menu_path + " >"
elif self.menu_path:
condtext = self.menu_path[:-3] + " >"
self["menu_path_compressed"] = StaticText(condtext)
self.menu_path += screentitle + ' / '
else:
title = screentitle
self["menu_path_compressed"] = StaticText("")
Screen.setTitle(self, title)
self['lab1'] = Label()
self["backupstatus"] = Label()
self["key_green"] = Button()
self["key_yellow"] = Button(_("Restore"))
self["key_red"] = Button(_("Delete"))
self.BackupRunning = False
self.onChangedEntry = []
self.emlist = []
self['list'] = MenuList(self.emlist)
self.populate_List()
self.activityTimer = eTimer()
self.activityTimer.timeout.get().append(self.backupRunning)
self.activityTimer.start(10)
self.Console = Console()
if BackupTime > 0:
t = localtime(BackupTime)
backuptext = _("Next backup: ") + strftime(_("%a %e %b %-H:%M"), t)
else:
backuptext = _("Next backup: ")
self["backupstatus"].setText(str(backuptext))
if not self.selectionChanged in self["list"].onSelectionChanged:
self["list"].onSelectionChanged.append(self.selectionChanged)
def createSummary(self):
from Screens.PluginBrowser import PluginBrowserSummary
return PluginBrowserSummary
def selectionChanged(self):
item = self["list"].getCurrent()
desc = self["backupstatus"].text
if item:
name = item
else:
name = ""
for cb in self.onChangedEntry:
cb(name, desc)
def backupRunning(self):
self.populate_List()
self.BackupRunning = False
for job in Components.Task.job_manager.getPendingJobs():
if job.name.startswith(_("Backup manager")):
self.BackupRunning = True
if self.BackupRunning:
self["key_green"].setText(_("View progress"))
else:
self["key_green"].setText(_("New backup"))
self.activityTimer.startLongTimer(5)
def getJobName(self, job):
return "%s: %s (%d%%)" % (job.getStatustext(), job.name, int(100 * job.progress / float(job.end)))
def showJobView(self, job):
from Screens.TaskView import JobView
Components.Task.job_manager.in_background = False
self.session.openWithCallback(self.JobViewCB, JobView, job, cancelable=False, afterEventChangeable=False, afterEvent="close")
def JobViewCB(self, in_background):
Components.Task.job_manager.in_background = in_background
def populate_List(self):
imparts = []
for p in harddiskmanager.getMountedPartitions():
if path.exists(p.mountpoint):
d = path.normpath(p.mountpoint)
if p.mountpoint != '/':
imparts.append((p.mountpoint, d))
config.backupmanager.backuplocation.setChoices(imparts)
if config.backupmanager.backuplocation.value.endswith('/'):
mount = config.backupmanager.backuplocation.value, config.backupmanager.backuplocation.value[:-1]
else:
mount = config.backupmanager.backuplocation.value + '/', config.backupmanager.backuplocation.value
hdd = '/media/hdd/', '/media/hdd'
if mount not in config.backupmanager.backuplocation.choices.choices:
if hdd in config.backupmanager.backuplocation.choices.choices:
self['myactions'] = ActionMap(['ColorActions', 'OkCancelActions', 'DirectionActions', "MenuActions", "TimerEditActions"],
{
'cancel': self.close,
'ok': self.keyResstore,
'red': self.keyDelete,
'green': self.GreenPressed,
'yellow': self.keyResstore,
"menu": self.createSetup,
'log': self.showLog,
}, -1)
self.BackupDirectory = '/media/hdd/backup/'
config.backupmanager.backuplocation.value = '/media/hdd/'
config.backupmanager.backuplocation.save()
self['lab1'].setText(_("The chosen location does not exist, using /media/hdd") + "\n" + _("Select a backup to Restore:"))
else:
self['myactions'] = ActionMap(['ColorActions', 'OkCancelActions', 'DirectionActions', "MenuActions", "TimerEditActions"],
{
'cancel': self.close,
"menu": self.createSetup,
'log': self.showLog,
}, -1)
self['lab1'].setText(_("Device: none available") + "\n" + _("Select a backup to restore:"))
else:
self['myactions'] = ActionMap(['ColorActions', 'OkCancelActions', 'DirectionActions', "MenuActions", "TimerEditActions"],
{
'cancel': self.close,
'ok': self.keyResstore,
'red': self.keyDelete,
'green': self.GreenPressed,
'yellow': self.keyResstore,
"menu": self.createSetup,
'log': self.showLog,
}, -1)
self.BackupDirectory = config.backupmanager.backuplocation.value + 'backup/'
self['lab1'].setText(_("Device: ") + config.backupmanager.backuplocation.value + "\n" + _("Select a backup to restore:"))
try:
if not path.exists(self.BackupDirectory):
mkdir(self.BackupDirectory, 0755)
images = listdir(self.BackupDirectory)
del self.emlist[:]
mtimes = []
for fil in images:
if fil.endswith('.tar.gz'):
mtimes.append((fil, stat(self.BackupDirectory + fil).st_mtime)) # (filname, mtime)
for fil in [x[0] for x in sorted(mtimes, key=lambda x: x[1], reverse=True)]: # sort by mtime
self.emlist.append(fil)
self["list"].setList(self.emlist)
self["list"].show()
except:
self['lab1'].setText(_("Device: ") + config.backupmanager.backuplocation.value + "\n" + _("there is a problem with this device, please reformat it and try again."))
def createSetup(self):
self.session.openWithCallback(self.setupDone, VIXBackupManagerMenu, 'vixbackupmanager', 'SystemPlugins/ViX', self.menu_path, PluginLanguageDomain)
def showLog(self):
self.sel = self['list'].getCurrent()
if self.sel:
filename = self.BackupDirectory + self.sel
self.session.open(VIXBackupManagerLogView, self.menu_path, filename)
def setupDone(self, test=None):
if config.backupmanager.folderprefix.value == '':
config.backupmanager.folderprefix.value = defaultprefix
config.backupmanager.folderprefix.save()
self.populate_List()
self.doneConfiguring()
def doneConfiguring(self):
now = int(time())
if config.backupmanager.schedule.value:
if autoBackupManagerTimer is not None:
print "[BackupManager] Backup schedule enabled at", strftime("%c", localtime(now))
autoBackupManagerTimer.backupupdate()
else:
if autoBackupManagerTimer is not None:
global BackupTime
BackupTime = 0
print "[BackupManager] Backup schedule disabled at", strftime("%c", localtime(now))
autoBackupManagerTimer.backupstop()
if BackupTime > 0:
t = localtime(BackupTime)
backuptext = _("Next backup: ") + strftime(_("%a %e %b %-H:%M"), t)
else:
backuptext = _("Next backup: ")
self["backupstatus"].setText(str(backuptext))
def keyDelete(self):
self.sel = self['list'].getCurrent()
if self.sel:
message = _("Are you sure you want to delete this backup:\n ") + self.sel
ybox = self.session.openWithCallback(self.doDelete, MessageBox, message, MessageBox.TYPE_YESNO, default=False)
ybox.setTitle(_("Remove confirmation"))
else:
self.session.open(MessageBox, _("You have no backup to delete."), MessageBox.TYPE_INFO, timeout=10)
def doDelete(self, answer):
if answer is True:
self.sel = self['list'].getCurrent()
self["list"].instance.moveSelectionTo(0)
remove(self.BackupDirectory + self.sel)
self.populate_List()
def GreenPressed(self):
self.BackupRunning = False
for job in Components.Task.job_manager.getPendingJobs():
if job.name.startswith(_("Backup manager")):
self.BackupRunning = True
break
if self.BackupRunning:
self.showJobView(job)
else:
self.keyBackup()
def keyBackup(self):
self.BackupFiles = BackupFiles(self.session)
Components.Task.job_manager.AddJob(self.BackupFiles.createBackupJob())
self.BackupRunning = True
self["key_green"].setText(_("View progress"))
self["key_green"].show()
for job in Components.Task.job_manager.getPendingJobs():
if job.name.startswith(_("Backup manager")):
self.showJobView(job)
break
def keyResstore(self):
self.sel = self['list'].getCurrent()
if not self.BackupRunning:
if self.sel:
if path.exists('/tmp/ExtraInstalledPlugins'):
remove('/tmp/ExtraInstalledPlugins')
if path.exists('/tmp/backupkernelversion'):
remove('/tmp/backupkernelversion')
self.Console.ePopen("tar -xzvf " + self.BackupDirectory + self.sel + " tmp/ExtraInstalledPlugins tmp/backupkernelversion tmp/backupimageversion -C /", self.settingsRestoreCheck)
else:
self.session.open(MessageBox, _("You have no backups to restore."), MessageBox.TYPE_INFO, timeout=10)
else:
self.session.open(MessageBox, _("Backup in progress,\nPlease wait for it to finish, before trying again"), MessageBox.TYPE_INFO, timeout=10)
def settingsRestoreCheck(self, result, retval, extra_args=None):
if path.exists('/tmp/backupimageversion'):
imageversion = file('/tmp/backupimageversion').read()
print '[BackupManager] Backup Image:', imageversion
print '[BackupManager] Current Image:', about.getVersionString()
if imageversion == about.getVersionString() or isRestorableSettings(imageversion):
print '[BackupManager] Stage 1: Image ver OK'
self.keyResstore1()
else:
self.session.open(MessageBox, _("Sorry, but the file is not compatible with this image version."), MessageBox.TYPE_INFO, timeout=10)
else:
self.session.open(MessageBox, _("Sorry, but the file is not compatible with this image version."), MessageBox.TYPE_INFO, timeout=10)
def keyResstore1(self):
message = _("Are you sure you want to restore this backup:\n ") + self.sel
ybox = self.session.openWithCallback(self.doRestore, MessageBox, message, MessageBox.TYPE_YESNO)
ybox.setTitle(_("Restore Confirmation"))
def doRestore(self, answer):
if answer is True:
Components.Task.job_manager.AddJob(self.createRestoreJob())
self.BackupRunning = True
self["key_green"].setText(_("View progress"))
self["key_green"].show()
for job in Components.Task.job_manager.getPendingJobs():
if job.name.startswith(_("Backup manager")):
self.showJobView(job)
break
def myclose(self):
self.close()
def createRestoreJob(self):
self.pluginslist = ""
self.pluginslist2 = ""
self.didSettingsRestore = False
self.doPluginsRestore = False
self.didPluginsRestore = False
self.Stage1Completed = False
self.Stage2Completed = False
self.Stage3Completed = False
self.Stage4Completed = False
self.Stage5Completed = False
job = Components.Task.Job(_("Backup manager"))
task = Components.Task.PythonTask(job, _("Restoring backup..."))
task.work = self.JobStart
task.weighting = 1
task = Components.Task.PythonTask(job, _("Restoring backup..."))
task.work = self.Stage1
task.weighting = 1
task = Components.Task.ConditionTask(job, _("Restoring backup..."), timeoutCount=30)
task.check = lambda: self.Stage1Completed
task.weighting = 1
task = Components.Task.PythonTask(job, _("Creating list of installed plugins..."))
task.work = self.Stage2
task.weighting = 1
task = Components.Task.ConditionTask(job, _("Creating list of installed plugins..."), timeoutCount=300)
task.check = lambda: self.Stage2Completed
task.weighting = 1
task = Components.Task.PythonTask(job, _("Comparing against backup..."))
task.work = self.Stage3
task.weighting = 1
task = Components.Task.ConditionTask(job, _("Comparing against backup..."), timeoutCount=300)
task.check = lambda: self.Stage3Completed
task.weighting = 1
task = Components.Task.PythonTask(job, _("Restoring plugins..."))
task.work = self.Stage4
task.weighting = 1
task = Components.Task.ConditionTask(job, _("Restoring plugins..."), timeoutCount=300)
task.check = lambda: self.Stage4Completed
task.weighting = 1
task = Components.Task.PythonTask(job, _("Restoring plugins, this can take a long time..."))
task.work = self.Stage5
task.weighting = 1
task = Components.Task.ConditionTask(job, _("Restoring plugins, this can take a long time..."), timeoutCount=1200)
task.check = lambda: self.Stage5Completed
task.weighting = 1
task = Components.Task.PythonTask(job, _("Rebooting..."))
task.work = self.Stage6
task.weighting = 1
return job
def JobStart(self):
AddPopupWithCallback(self.Stage1,
_("Do you want to restore your enigma2 settings ?"),
MessageBox.TYPE_YESNO,
10,
SETTINGSRESTOREQUESTIONID
)
def Stage1(self, answer=None):
print '[BackupManager] Restoring Stage 1:'
if answer is True:
self.Console.ePopen("tar -xzvf " + self.BackupDirectory + self.sel + " -C /", self.Stage1SettingsComplete)
elif answer is False:
self.Console.ePopen("tar -xzvf " + self.BackupDirectory + self.sel + " tmp/ExtraInstalledPlugins tmp/backupkernelversion tmp/backupimageversion tmp/3rdPartyPlugins -C /", self.Stage1PluginsComplete)
def Stage1SettingsComplete(self, result, retval, extra_args):
print '[BackupManager] Restoring Stage 1 RESULT:', result
print '[BackupManager] Restoring Stage 1 retval:', retval
if retval == 0:
print '[BackupManager] Restoring Stage 1 Complete:'
self.didSettingsRestore = True
self.Stage1Completed = True
eDVBDB.getInstance().reloadServicelist()
eDVBDB.getInstance().reloadBouquets()
self.session.nav.PowerTimer.loadTimer()
self.session.nav.RecordTimer.loadTimer()
configfile.load()
else:
print '[BackupManager] Restoring Stage 1 Failed:'
AddPopupWithCallback(self.Stage2,
_("Sorry, but the restore failed."),
MessageBox.TYPE_INFO,
10,
'StageOneFailedNotification'
)
def Stage1PluginsComplete(self, result, retval, extra_args):
print '[BackupManager] Restoring Stage 1 Complete:'
self.Stage1Completed = True
def Stage2(self, result=False):
print '[BackupManager] Restoring Stage 2: Checking feeds'
self.Console.ePopen('opkg update', self.Stage2Complete)
def Stage2Complete(self, result, retval, extra_args):
print '[BackupManager] Restoring Stage 2: Result ', result
if result.find('wget returned 1') != -1 or result.find('wget returned 255') != -1 or result.find('404 Not Found') != -1:
self.feeds = 'DOWN'
self.Stage2Completed = True
elif result.find('bad address') != -1:
self.feeds = 'BAD'
self.Stage2Completed = True
elif result.find('Collected errors') != -1:
AddPopupWithCallback(self.Stage2,
_("A background update check is is progress, please try again."),
MessageBox.TYPE_INFO,
10,
NOPLUGINS
)
else:
print '[BackupManager] Restoring Stage 2: Complete'
self.feeds = 'OK'
self.Stage2Completed = True
def Stage3(self):
print '[BackupManager] Restoring Stage 3: Kernel Version/Feeds Checks'
if self.feeds == 'OK':
print '[BackupManager] Restoring Stage 3: Feeds are OK'
if path.exists('/tmp/backupkernelversion') and path.exists('/tmp/backupimageversion'):
kernelversion = file('/tmp/backupkernelversion').read()
imageversion = file('/tmp/backupimageversion').read()
print '[BackupManager] Backup Image:', imageversion
print '[BackupManager] Current Image:', about.getVersionString()
print '[BackupManager] Backup Kernel:', kernelversion
print '[BackupManager] Current Kernel:', about.getKernelVersionString()
if isRestorableKernel(kernelversion) and (imageversion == about.getVersionString() or isRestorablePlugins(imageversion)):
# print '[BackupManager] Restoring Stage 3: Kernel Version is same as backup'
self.kernelcheck = True
self.Console.ePopen('opkg list-installed', self.Stage3Complete)
else:
print '[BackupManager] Restoring Stage 3: Kernel or Image Version does not match, exiting'
self.kernelcheck = False
self.Stage6()
else:
print '[BackupManager] Restoring Stage 3: Kernel or Image Version check failed'
self.kernelcheck = False
self.Stage6()
elif self.feeds == 'DOWN':
print '[BackupManager] Restoring Stage 3: Feeds are down, plugin restore not possible'
self.kernelcheck = False
AddPopupWithCallback(self.Stage6,
_("Sorry feeds are down for maintenance, Please try again later."),
MessageBox.TYPE_INFO,
15,
NOPLUGINS
)
elif self.feeds == 'BAD':
print '[BackupManager] Restoring Stage 3: no network connection, plugin restore not possible'
self.kernelcheck = False
AddPopupWithCallback(self.Stage6,
_("Your %s %s is not connected to the internet, please check your network settings and try again.") % (getMachineBrand(), getMachineName()),
MessageBox.TYPE_INFO,
15,
NOPLUGINS
)
else:
print '[BackupManager] Restoring Stage 3: Feeds state is unknown aborting'
self.Stage6()
def Stage3Complete(self, result, retval, extra_args):
plugins = []
if path.exists('/tmp/ExtraInstalledPlugins') and self.kernelcheck:
self.pluginslist = []
for line in result.split('\n'):
if line:
parts = line.strip().split()
plugins.append(parts[0])
tmppluginslist = open('/tmp/ExtraInstalledPlugins', 'r').readlines()
for line in tmppluginslist:
if line:
parts = line.strip().split()
if len(parts) > 0 and parts[0] not in plugins:
self.pluginslist.append(parts[0])
if path.exists('/tmp/3rdPartyPlugins') and self.kernelcheck:
self.pluginslist2 = []
if config.backupmanager.xtraplugindir.value:
self.thirdpartyPluginsLocation = config.backupmanager.xtraplugindir.value
self.thirdpartyPluginsLocation = self.thirdpartyPluginsLocation.replace(' ', '%20')
elif path.exists('/tmp/3rdPartyPluginsLocation'):
self.thirdpartyPluginsLocation = open('/tmp/3rdPartyPluginsLocation', 'r').readlines()
self.thirdpartyPluginsLocation = "".join(self.thirdpartyPluginsLocation)
self.thirdpartyPluginsLocation = self.thirdpartyPluginsLocation.replace('\n', '')
self.thirdpartyPluginsLocation = self.thirdpartyPluginsLocation.replace(' ', '%20')
else:
self.thirdpartyPluginsLocation = " "
tmppluginslist2 = open('/tmp/3rdPartyPlugins', 'r').readlines()
available = None
for line in tmppluginslist2:
if line:
parts = line.strip().split('_')
if parts[0] not in plugins:
ipk = parts[0]
if path.exists(self.thirdpartyPluginsLocation):
available = listdir(self.thirdpartyPluginsLocation)
else:
for root, subFolders, files in walk('/media'):
for folder in subFolders:
# print "%s has subdirectory %s" % (root, folder)
if folder and folder == path.split(self.thirdpartyPluginsLocation[:-1])[-1]:
self.thirdpartyPluginsLocation = path.join(root, folder)
self.thirdpartyPluginsLocation = self.thirdpartyPluginsLocation.replace(' ', '%20')
available = listdir(self.thirdpartyPluginsLocation)
# print 'TRUE',self.thirdpartyPluginsLocation
break
if available:
for file in available:
if file:
fileparts = file.strip().split('_')
# print 'FILE:',fileparts
# print 'IPK:',ipk
if fileparts[0] == ipk:
self.thirdpartyPluginsLocation = self.thirdpartyPluginsLocation.replace(' ', '%20')
ipk = path.join(self.thirdpartyPluginsLocation, file)
if path.exists(ipk):
# print 'IPK', ipk
self.pluginslist2.append(ipk)
print '[BackupManager] Restoring Stage 3: Complete'
self.Stage3Completed = True
def Stage4(self):
if len(self.pluginslist) or len(self.pluginslist2):
if len(self.pluginslist):
self.pluginslist = " ".join(self.pluginslist)
else:
self.pluginslist = ""
if len(self.pluginslist2):
self.pluginslist2 = " ".join(self.pluginslist2)
else:
self.pluginslist2 = ""
print '[BackupManager] Restoring Stage 4: Plugins to restore (extra plugins)', self.pluginslist
print '[BackupManager] Restoring Stage 4: Plugins to restore (3rd party plugins)', self.pluginslist2
AddPopupWithCallback(self.Stage4Complete,
_("Do you want to restore your Enigma2 plugins ?"),
MessageBox.TYPE_YESNO,
15,
PLUGINRESTOREQUESTIONID
)
else:
print '[BackupManager] Restoring Stage 4: plugin restore not required'
self.Stage6()
def Stage4Complete(self, answer=None):
if answer is True:
print '[BackupManager] Restoring Stage 4: plugin restore chosen'
self.doPluginsRestore = True
self.Stage4Completed = True
elif answer is False:
print '[BackupManager] Restoring Stage 4: plugin restore skipped by user'
AddPopupWithCallback(self.Stage6,
_("Now skipping restore process"),
MessageBox.TYPE_INFO,
15,
NOPLUGINS
)
def Stage5(self):
if self.doPluginsRestore:
print '[BackupManager] Restoring Stage 5: starting plugin restore'
print '[BackupManager] Console command: ', 'opkg install ' + self.pluginslist + ' ' + self.pluginslist2
self.Console.ePopen('opkg install ' + self.pluginslist + ' ' + self.pluginslist2, self.Stage5Complete)
else:
print '[BackupManager] Restoring Stage 5: plugin restore not requested'
self.Stage6()
def Stage5Complete(self, result, retval, extra_args):
if result:
print "[BackupManager] opkg install result:\n", result
self.didPluginsRestore = True
self.Stage5Completed = True
print '[BackupManager] Restoring Stage 5: Completed'
def Stage6(self, result=None, retval=None, extra_args=None):
self.Stage1Completed = True
self.Stage2Completed = True
self.Stage3Completed = True
self.Stage4Completed = True
self.Stage5Completed = True
if self.didPluginsRestore or self.didSettingsRestore:
print '[BackupManager] Restoring Completed rebooting'
quitMainloop(2)
else:
print '[BackupManager] Restoring failed or canceled'
self.close()
class BackupSelection(Screen):
skin = """
<screen name="BackupSelection" position="center,center" size="560,400">
<ePixmap pixmap="skin_default/buttons/red.png" position="0,0" size="140,40" alphatest="on"/>
<ePixmap pixmap="skin_default/buttons/green.png" position="140,0" size="140,40" alphatest="on"/>
<ePixmap pixmap="skin_default/buttons/yellow.png" position="280,0" size="140,40" alphatest="on"/>
<widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1"/>
<widget source="key_green" render="Label" position="140,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1"/>
<widget source="key_yellow" render="Label" position="280,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#a08500" transparent="1"/>
<widget name="checkList" position="5,50" size="550,250" transparent="1" scrollbarMode="showOnDemand"/>
</screen>"""
def __init__(self, session, menu_path):
Screen.__init__(self, session)
screentitle = _("Select files/folders to backup")
if config.usage.show_menupath.value == 'large':
menu_path += screentitle
print 'menu_pathoo',menu_path
title = menu_path
self["menu_path_compressed"] = StaticText("")
elif config.usage.show_menupath.value == 'small':
title = screentitle
self["menu_path_compressed"] = StaticText(menu_path + " >" if not menu_path.endswith(' / ') else menu_path[:-3] + " >" or "")
else:
title = screentitle
self["menu_path_compressed"] = StaticText("")
Screen.setTitle(self, title)
self["key_red"] = StaticText(_("Cancel"))
self["key_green"] = StaticText(_("Save"))
self["key_yellow"] = StaticText()
self.selectedFiles = config.backupmanager.backupdirs.value
defaultDir = '/'
self.filelist = MultiFileSelectList(self.selectedFiles, defaultDir)
self["checkList"] = self.filelist
self["actions"] = ActionMap(["DirectionActions", "OkCancelActions", "ShortcutActions", "MenuActions"],
{
"cancel": self.exit,
"red": self.exit,
"yellow": self.changeSelectionState,
"green": self.saveSelection,
"ok": self.okClicked,
"left": self.left,
"right": self.right,
"down": self.down,
"up": self.up,
"menu": self.exit,
}, -1)
if not self.selectionChanged in self["checkList"].onSelectionChanged:
self["checkList"].onSelectionChanged.append(self.selectionChanged)
self.onLayoutFinish.append(self.layoutFinished)
def layoutFinished(self):
idx = 0
self["checkList"].moveToIndex(idx)
self.selectionChanged()
def selectionChanged(self):
current = self["checkList"].getCurrent()[0]
if current[2] is True:
self["key_yellow"].setText(_("Deselect"))
else:
self["key_yellow"].setText(_("Select"))
def up(self):
self["checkList"].up()
def down(self):
self["checkList"].down()
def left(self):
self["checkList"].pageUp()
def right(self):
self["checkList"].pageDown()
def changeSelectionState(self):
self["checkList"].changeSelectionState()
self.selectedFiles = self["checkList"].getSelectedList()
def saveSelection(self):
self.selectedFiles = self["checkList"].getSelectedList()
config.backupmanager.backupdirs.value = self.selectedFiles
config.backupmanager.backupdirs.save()
config.backupmanager.save()
config.save()
self.close(None)
def exit(self):
self.close(None)
def okClicked(self):
if self.filelist.canDescent():
self.filelist.descent()
def closeRecursive(self):
self.close(True)
class XtraPluginsSelection(Screen):
skin = """
<screen name="BackupSelection" position="center,center" size="560,400">
<ePixmap pixmap="skin_default/buttons/red.png" position="0,0" size="140,40" alphatest="on"/>
<ePixmap pixmap="skin_default/buttons/green.png" position="140,0" size="140,40" alphatest="on"/>
<ePixmap pixmap="skin_default/buttons/yellow.png" position="280,0" size="140,40" alphatest="on"/>
<widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1"/>
<widget source="key_green" render="Label" position="140,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1"/>
<widget source="key_yellow" render="Label" position="280,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#a08500" transparent="1"/>
<widget name="checkList" position="5,50" size="550,250" transparent="1" scrollbarMode="showOnDemand"/>
</screen>"""
def __init__(self, session, menu_path):
Screen.__init__(self, session)
screentitle = _("Select extra packages folder")
if config.usage.show_menupath.value == 'large':
menu_path += screentitle
title = menu_path
self["menu_path_compressed"] = StaticText("")
elif config.usage.show_menupath.value == 'small':
title = screentitle
self["menu_path_compressed"] = StaticText(menu_path + " >" if not menu_path.endswith(' / ') else menu_path[:-3] + " >" or "")
else:
title = screentitle
self["menu_path_compressed"] = StaticText("")
Screen.setTitle(self, title)
self["key_red"] = StaticText(_("Cancel"))
self["key_green"] = StaticText(_("Save"))
defaultDir = config.backupmanager.backuplocation.value
self.filelist = FileList(defaultDir, showFiles=True, matchingPattern='^.*.(ipk)')
self["checkList"] = self.filelist
self["actions"] = ActionMap(["DirectionActions", "OkCancelActions", "ShortcutActions", "MenuActions"],
{
"cancel": self.exit,
"red": self.exit,
"green": self.saveSelection,
"ok": self.okClicked,
"left": self.left,
"right": self.right,
"down": self.down,
"up": self.up,
"menu": self.exit,
}, -1)
if not self.selectionChanged in self["checkList"].onSelectionChanged:
self["checkList"].onSelectionChanged.append(self.selectionChanged)
self.onLayoutFinish.append(self.layoutFinished)
def layoutFinished(self):
idx = 0
self["checkList"].moveToIndex(idx)
self.setWindowTitle()
self.selectionChanged()
def setWindowTitle(self):
self.setTitle(_("Select folder that contains plugins"))
def selectionChanged(self):
current = self["checkList"].getCurrent()[0]
def up(self):
self["checkList"].up()
def down(self):
self["checkList"].down()
def left(self):
self["checkList"].pageUp()
def right(self):
self["checkList"].pageDown()
def saveSelection(self):
filelist = str(self.filelist.getFileList())
if filelist.find('.ipk') != -1:
config.backupmanager.xtraplugindir.setValue(self.filelist.getCurrentDirectory())
config.backupmanager.xtraplugindir.save()
config.backupmanager.save()
config.save()
self.close(None)
else:
self.session.open(MessageBox, _("Please enter a folder that contains some packages."), MessageBox.TYPE_INFO, timeout=10)
def exit(self):
self.close(None)
def okClicked(self):
if self.filelist.canDescent():
self.filelist.descent()
def closeRecursive(self):
self.close(True)
class VIXBackupManagerMenu(Setup):
skin = """
<screen name="VIXBackupManagerMenu" position="center,center" size="560,550" title="VIX backup manager menu">
<ePixmap pixmap="skin_default/buttons/red.png" position="0,0" size="140,40" alphatest="on"/>
<ePixmap pixmap="skin_default/buttons/green.png" position="140,0" size="140,40" alphatest="on"/>
<ePixmap pixmap="skin_default/buttons/yellow.png" position="280,0" size="140,40" alphatest="on"/>
<ePixmap pixmap="skin_default/buttons/blue.png" position="420,0" size="140,40" alphatest="on"/>
<widget name="key_red" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1"/>
<widget name="key_green" position="140,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1"/>
<widget name="key_yellow" position="280,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#a08500" transparent="1"/>
<widget name="key_blue" position="420,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#18188b" transparent="1"/>
<widget name="HelpWindow" pixmap="buttons/vkey_icon.png" position="450,510" zPosition="1" size="1,1" transparent="1" alphatest="on"/>
<widget source="VKeyIcon" render="Pixmap" pixmap="buttons/key_text.png" position="0,500" zPosition="1" size="35,25" transparent="1" alphatest="on">
<convert type="ConditionalShowHide"/>
</widget>
<widget name="footnote" position="0,50" size="300,20" zPosition="1" font="Regular;20" halign="left" transparent="1" valign="top"/>
<widget name="config" position="0,90" size="560,375" transparent="0" enableWrapAround="1" scrollbarMode="showOnDemand"/>
<widget name="description" position="0,e-75" size="560,75" font="Regular;18" halign="center" valign="top" transparent="0" zPosition="1"/>
</screen>"""
def __init__(self, session, setup, plugin=None, menu_path=None, PluginLanguageDomain=None):
Setup.__init__(self, session, setup, plugin, menu_path, PluginLanguageDomain)
self.menu_path = menu_path
self.skinName = "VIXBackupManagerMenu"
self["actions2"] = ActionMap(["SetupActions", 'ColorActions', 'VirtualKeyboardActions', "MenuActions"],
{
"yellow": self.chooseFiles,
"blue": self.chooseXtraPluginDir,
}, -2)
self["key_red"] = Button(_("Cancel"))
self["key_green"] = Button(_("OK"))
self["key_yellow"] = Button(_("Choose files"))
self["key_blue"] = Button(_("Choose local ipk's folder"))
def chooseFiles(self):
self.session.openWithCallback(self.backupfiles_choosen, BackupSelection, self.menu_path)
def chooseXtraPluginDir(self):
self.session.open(XtraPluginsSelection, self.menu_path)
def backupfiles_choosen(self, ret):
self.backupdirs = ' '.join(config.backupmanager.backupdirs.value)
config.backupmanager.backupdirs.save()
config.backupmanager.save()
config.save()
class VIXBackupManagerLogView(Screen):
skin = """
<screen name="VIXBackupManagerLogView" position="center,center" size="560,400" title="Backup Log">
<widget name="list" position="0,0" size="560,400" font="Regular;16"/>
</screen>"""
def __init__(self, session, menu_path, filename):
self.session = session
Screen.__init__(self, session)
screentitle = _("Logs")
if config.usage.show_menupath.value == 'large':
menu_path += screentitle
title = menu_path
self["menu_path_compressed"] = StaticText("")
elif config.usage.show_menupath.value == 'small':
title = screentitle
self["menu_path_compressed"] = StaticText(menu_path + " >" if not menu_path.endswith(' / ') else menu_path[:-3] + " >" or "")
else:
title = screentitle
self["menu_path_compressed"] = StaticText("")
Screen.setTitle(self, title)
self.skinName = "VIXBackupManagerLogView"
filedate = str(date.fromtimestamp(stat(filename).st_mtime))
backuplog = _('Backup created') + ': ' + filedate + '\n\n'
tar = tarfile.open(filename, "r")
contents = ""
for tarinfo in tar:
file = tarinfo.name
contents += str(file) + '\n'
tar.close()
backuplog = backuplog + contents
self["list"] = ScrollLabel(str(backuplog))
self["setupActions"] = ActionMap(["SetupActions", "ColorActions", "DirectionActions", "MenuActions"],
{
"cancel": self.cancel,
"ok": self.cancel,
"up": self["list"].pageUp,
"down": self["list"].pageDown,
"menu": self.closeRecursive,
}, -2)
def cancel(self):
self.close()
def closeRecursive(self):
self.close(True)
class AutoBackupManagerTimer:
def __init__(self, session):
self.session = session
self.backuptimer = eTimer()
self.backuptimer.callback.append(self.BackuponTimer)
self.backupactivityTimer = eTimer()