New Plugin EPGBackup http://www.i-have-a-dreambox.com/wbb2/thread.php?threadid=184114
[enigma2-plugins.git] / epgbackup / src / EPGBackupConfig.py
1 # Screens
2 from Screens.Screen import Screen
3 from Screens.ChoiceBox import ChoiceBox
4 from Screens.HelpMenu import HelpMenu, HelpableScreen
5 from Components.ActionMap import ActionMap, HelpableActionMap
6 from Components.Sources.StaticText import StaticText
7 from Screens.MessageBox import MessageBox
8 from Screens.LocationBox import LocationBox
9
10 # for localized messages
11 from . import _
12
13 # GUI (Summary)
14 from Screens.Setup import SetupSummary
15
16 # Configuration
17 from Components.config import config, getConfigListEntry, configfile, NoSave
18 from Components.ConfigList import ConfigListScreen
19 from Components.config import KEY_OK
20
21 # Error-print
22 from EPGBackupTools import debugOut, PLUGIN_VERSION
23 from traceback import format_exc
24
25 from plugin import gUserScriptExists
26 from plugin import epgbackup
27                         
28 class EPGBackupConfig(Screen, HelpableScreen, ConfigListScreen):
29         skin = """
30                 <screen name="EPGBackupSetup" position="center,center" size="700,520" >
31                         <ePixmap position="0,0" size="140,40" pixmap="skin_default/buttons/red.png" transparent="1" alphatest="on" />
32                         <widget  position="0,0" size="140,40" source="key_red" render="Label" transparent="1" halign="center" valign="center" zPosition="2" foregroundColor="white" font="Regular;18" />
33                         <ePixmap position="140,0" size="140,40" pixmap="skin_default/buttons/green.png" transparent="1" alphatest="on" />
34                         <widget  position="140,0" size="140,40" render="Label" source="key_green" transparent="1" halign="center" valign="center" zPosition="2" foregroundColor="white" font="Regular;18" />
35                         <ePixmap position="282,10" zPosition="1" size="35,25" pixmap="skin_default/buttons/key_menu.png" alphatest="on" />
36                         <widget  position="5,45" size="690,335" name="config" scrollbarMode="showOnDemand" enableWrapAround="1" />
37                         <ePixmap position="0,390" size="700,2" pixmap="skin_default/div-h.png" zPosition="1" />
38                         <widget  position="5,400" size="690,120" source="help" render="Label" font="Regular;21" />
39                 </screen>"""
40
41         def __init__(self, session):
42                 Screen.__init__(self, session)
43                 HelpableScreen.__init__(self)
44                 
45                 # Summary
46                 self.setup_title = _("EPGBackup Setup")
47                 self.onChangedEntry = []
48                 
49                 self.session = session
50                 self.list = []
51                 ConfigListScreen.__init__(self, self.list, session, on_change = self.changed)
52                 self["config"].onSelectionChanged.append(self._updateHelp)
53                 self._getConfig()
54                 
55                 self["key_red"] = StaticText(_("Cancel"))
56                 self["key_green"] = StaticText(_("Save"))
57                 self["help"] = StaticText()
58                 
59                 # Actions
60                 self["ColorActions"] = HelpableActionMap(self, "ColorActions",
61                         {
62                                 "red": (self.keyCancel, _("Close and forget changes")),
63                                 "green": (self.keySave, _("Close and save changes")),
64                         }
65                 )
66                 self["MenuActions"] = HelpableActionMap(self, "MenuActions",
67                         {
68                                 "menu": (self.menu, _("Open Context Menu"))
69                         }
70                 )
71                 self["OkCancelActions"] = HelpableActionMap(self, "OkCancelActions",
72                         {
73                                 "cancel": (self.keyCancel, _("Close and forget changes")),
74                         }
75                 )
76                 self["ChannelSelectBaseActions"] = HelpableActionMap(self, "ChannelSelectBaseActions",
77                         {
78                                 "nextBouquet": (self.pageup, _("Move page up")),
79                                 "prevBouquet": (self.pagedown, _("Move page down")),
80                         }
81                 )
82                 
83                 self["HelpActions"] = ActionMap(["HelpActions"],
84                         {
85                                 "displayHelp": self.showKeyHelp,
86                         }
87                 )
88
89                 # Trigger change
90                 self.changed()
91                 
92                 self.confShowSetupIn = config.plugins.epgbackup.show_setup_in.value
93                 
94                 config.plugins.epgbackup.backup_strategy.addNotifier(self.updateVariableHelpText, initial_call = False, immediate_feedback = True)
95                 self.onClose.append(self.removeNotifiers)
96                 
97                 self.needsEnigmaRestart = False
98                 self.onLayoutFinish.append(self._layoutFinished)
99                 self["config"].isChanged = self._ConfigisChanged
100         
101         def _layoutFinished(self):
102                 self.setTitle(_("EPGBackup Setup") + " V%s" %(PLUGIN_VERSION))
103         
104         def removeNotifiers(self):
105                 try:
106                         config.plugins.epgbackup.backup_strategy.removeNotifier(self.updateVariableHelpText)
107                 except:
108                         debugOut("removeNotifiers-Error:\n" + str(format_exc()), forced=True)
109         
110         def showMainHelp(self):
111                 from plugin import epgBackuphHelp
112                 if epgBackuphHelp:
113                         epgBackuphHelp.open(self.session)
114
115         def showKeyHelp(self):
116                 self.session.openWithCallback(self.callHelpAction, HelpMenu, self.helpList)
117
118         def menu(self):
119                 menuList = []
120                 if config.plugins.epgbackup.backup_enabled.value:
121                         menuList.extend( [
122                                 (_("Restore EPG-Backups (Date)"), "MENU_RETURN_RESTORE_DATE"),
123                                 (_("Restore EPG-Backups (Size)"), "MENU_RETURN_RESTORE_SIZE"),
124                                 (_("Make a EPG-Backup"), "MENU_RETURN_DO_BACKUP"),
125                                 (_("Set Restore-File for next boot"), "MENU_RETURN_SET_NEXT_BOOT_RESTORE"),
126                                 ("--", None),
127                         ])
128                 menuList.append((_("Show Help"), "MENU_RETURN_MAINHELP"))
129
130                 self.session.openWithCallback(
131                         self.menuCallback,
132                         ChoiceBox,
133                         list = menuList,
134                 )
135
136         def menuCallback(self, menuinfo):
137                 try:
138                         menuinfo = menuinfo and menuinfo[1]
139                         if menuinfo:
140                                 if menuinfo == "MENU_RETURN_RESTORE_DATE":
141                                         if epgbackup:
142                                                 epgbackup.forceRestore()
143                                 elif menuinfo == "MENU_RETURN_RESTORE_SIZE":
144                                         if epgbackup:
145                                                 epgbackup.forceRestoreBySize()
146                                 elif menuinfo == "MENU_RETURN_DO_BACKUP":
147                                         if epgbackup:
148                                                 epgbackup.makeBackup(interactive = True)
149                                 elif menuinfo == "MENU_RETURN_SET_NEXT_BOOT_RESTORE":
150                                         if epgbackup:
151                                                 epgbackup.setNextBootRestore()
152                                 elif menuinfo == "MENU_RETURN_MAINHELP":
153                                         self.showMainHelp()
154                 except:
155                         debugOut("menuCallback-Error:\n" + str(format_exc()), forced=True)
156         
157         def _getConfig(self):
158                 # Name, configElement, HelpTxt, reloadConfig
159                 try:
160                         self.list = [] 
161                         self.list.append(getConfigListEntry(_("Enable Backup"), config.plugins.epgbackup.backup_enabled, _("Should the Backup-Functionality be enabled?\nFor more Information have a look at the Help-Screen."), True))
162                         if config.plugins.epgbackup.backup_enabled.value:
163                                 self.list.append(getConfigListEntry(_("make Backup on start"), config.plugins.epgbackup.make_backup_after_unsuccess_restore, _("Make a backup before starting enigma. A backup-file will only be created, if no valid backup-file could be restored.\nNote: It's logically the same as making a backup at the ending of enigma, because the file didn't change in the meanwhile."), False))
164                                 if epgbackup and epgbackup.epgrefresh_instance:
165                                                 self.list.append(getConfigListEntry(_("make Backup after EPGRefresh"), config.plugins.epgbackup.callAfterEPGRefresh, _("Make a backup after EPGRefresh."), False))
166                                 self.list.append(getConfigListEntry(_("make Backup every"), config.plugins.epgbackup.backupSaveInterval, _("Make backups periodically?"), False))
167                                 self.list.append(getConfigListEntry(_("Restore-Strategy"), config.plugins.epgbackup.backup_strategy, None, False))
168                                 self.list.append(getConfigListEntry(_("Valid Filesize"), config.plugins.epgbackup.filesize_valid, _("EPG-Files with a less size of this value (MiB) won't be backuped."), False))
169                                 self.list.append(getConfigListEntry(_("Valid Age"), config.plugins.epgbackup.timespan_valid, _("Only keep EPG-Backup-Files younger than this days."), False))
170                                 self.list.append(getConfigListEntry(_("Show Advanced Options"), NoSave(config.plugins.epgbackup.showadvancedoptions), _("Display more Options"), True))
171                                 if config.plugins.epgbackup.showadvancedoptions.value:
172                                         self.list.append(getConfigListEntry(_("EPG-File-Write Wait"), config.plugins.epgbackup.epgwrite_wait, _("How many seconds should EPGBackup be wait to check if the EPG-File-Size didn't change before it starts the Backup."), False))
173                                         self.list.append(getConfigListEntry(_("Maximum Boot-Count"), config.plugins.epgbackup.max_boot_count, _("After that times of unsuccesfully boot enigma2, the EPG-File will be deleted."), False))
174                                         self.list.append(getConfigListEntry(_("Enable Debug"), config.plugins.epgbackup.enable_debug, _("Should debugmessages be printed?\nMessages from the shell-script will be append to a file. The filename will be added with the current date"), True))
175                                         if config.plugins.epgbackup.enable_debug.value:
176                                                 self.list.append(getConfigListEntry(_("append plugin-messages"), config.plugins.epgbackup.plugin_debug_in_file, _("Should the debug-messages from the enigma-plugin also be append to the logfile? If you choose no the messages will print only to standard-out."), False))
177                                                 self.list.append(getConfigListEntry(_("Log-directory"), config.plugins.epgbackup.backup_log_dir, _("Directory for the Logfiles."), False))
178                                         if gUserScriptExists:
179                                                 self.list.append(getConfigListEntry(_("Show in User-Scripts"), config.plugins.epgbackup.showin_usr_scripts, _("Should the Manage-Script be shown in User-Scripts?"), False))
180                                         
181                                         self.list.append(getConfigListEntry(_("Show messages in background"), config.plugins.epgbackup.show_messages_background, _("Pop a notification if called in background?"), False))
182                                         self.list.append(getConfigListEntry(_("Show setup in"), config.plugins.epgbackup.show_setup_in, _("Where should this setup be displayed?"), False))
183                                         self.list.append(getConfigListEntry(_("Show \"Make Backup\" in extension menu"), config.plugins.epgbackup.show_make_backup_in_extmenu, _("Enable this to be able to make a Backup-File from within the extension menu."), False))
184                                         self.list.append(getConfigListEntry(_("Show \"Restore Backup\" in extension menu"), config.plugins.epgbackup.show_backuprestore_in_extmenu, _("Enable this to be able to start a restore of a Backup-File from within the extension menu."), False))
185                                 
186                         self["config"].list = self.list
187                         self["config"].setList(self.list)
188                 except:
189                         debugOut("_getConfig-Error:\n" + str(format_exc()), forced=True)
190
191         def _checkNeedsRestart(self):
192                 if (self.confShowSetupIn == "system" and config.plugins.epgbackup.show_setup_in.value != "system") \
193                         or (self.confShowSetupIn != "system" and config.plugins.epgbackup.show_setup_in.value == "system"):
194                         self.needsEnigmaRestart = True
195         
196         # overwrites / extendends
197         def keyLeft(self):
198                 ConfigListScreen.keyLeft(self)
199                 self._onKeyChange()
200
201         def keyRight(self):
202                 ConfigListScreen.keyRight(self)
203                 self._onKeyChange()
204         
205         # overwrite configlist.isChanged
206         def _ConfigisChanged(self):
207                 is_changed = False
208                 for x in self["config"].list:
209                         if not x[1].save_disabled:
210                                 is_changed |= x[1].isChanged()
211                 return is_changed
212         
213         def keyOK(self):
214                 self["config"].handleKey(KEY_OK)
215                 cur = self["config"].getCurrent()
216                 if cur[1] == config.plugins.epgbackup.backup_log_dir:
217                         self.session.openWithCallback(self.directorySelected, LocationBox, \
218                                 _("Select Logfile-Location"), "", \
219                                 config.plugins.epgbackup.backup_log_dir.value)
220
221         def directorySelected(self, res):
222                 if res is not None:
223                         config.plugins.epgbackup.backup_log_dir.value = res
224
225         def _onKeyChange(self):
226                 cur = self["config"].getCurrent()
227                 if cur and cur[3]:
228                         self._getConfig()
229
230         def _updateHelp(self):
231                 cur = self["config"].getCurrent()
232                 if cur:
233                         if cur[2] == None:
234                                 self.updateVariableHelpText(cur[1])
235                         else:
236                                 self["help"].text = cur[2]
237
238         def updateVariableHelpText(self, configelement):
239                 try:
240                         if configelement == config.plugins.epgbackup.backup_strategy:
241                                 self["help"].text = configelement.getChoices()[configelement.getIndex()][2]
242                 except:
243                         debugOut("updateVariableHelpText-Error:\n" + str(format_exc()), forced=True)
244
245         def pageup(self):
246                 self["config"].instance.moveSelection(self["config"].instance.pageUp)
247
248         def pagedown(self):
249                 self["config"].instance.moveSelection(self["config"].instance.pageDown)
250
251         def cancelConfirm(self, doCancel):
252                 if not doCancel:
253                         return
254                 for x in self["config"].list:
255                         x[1].cancel()
256                 self.close(self.session, False)
257
258         def keyCancel(self):
259                 if self["config"].isChanged():
260                         self.session.openWithCallback(
261                                 self.cancelConfirm,
262                                 MessageBox,
263                                 _("Really close without saving settings?")
264                         )
265                 else:
266                         self.close(self.session, False)
267
268         def keySave(self):
269                 if self["config"].isChanged():
270                         for x in self["config"].list:
271                                 x[1].save()
272                         configfile.save()
273                 
274                 self._checkNeedsRestart()
275                 self.close(self.session, self.needsEnigmaRestart)
276         
277         # for Summary
278         def changed(self):
279                 for x in self.onChangedEntry:
280                         try:
281                                 x()
282                         except Exception:
283                                 pass
284         def getCurrentEntry(self):
285                 if self["config"].getCurrent():
286                         return self["config"].getCurrent()[0]
287         def getCurrentValue(self):
288                 if self["config"].getCurrent():
289                         return str(self["config"].getCurrent()[1].getText())
290         def createSummary(self):
291                 return SetupSummary
292
293