its mandatory to call deleteDialog for the pip screen
[enigma2-plugins.git] / epgrefresh / src / EPGRefreshConfiguration.py
1 from __future__ import print_function
2
3 # for localized messages
4 from . import _
5
6 # GUI (Screens)
7 from Screens.Screen import Screen
8 from Screens.ChoiceBox import ChoiceBox
9 from Components.ConfigList import ConfigListScreen
10 from Components.config import KEY_OK
11 from Screens.LocationBox import LocationBox
12 from EPGRefreshChannelEditor import EPGRefreshServiceEditor
13
14 # GUI (Summary)
15 from Screens.Setup import SetupSummary
16
17 # GUI (Components)
18 from Components.ActionMap import ActionMap, HelpableActionMap
19 from Screens.HelpMenu import HelpMenu, HelpableScreen
20 from Components.Sources.StaticText import StaticText
21
22 # Configuration
23 from Components.config import config, getConfigListEntry, configfile, NoSave
24 from Screens.FixedMenu import FixedMenu
25 from Tools.BoundFunction import boundFunction
26
27 from EPGRefresh import epgrefresh
28 from Components.SystemInfo import SystemInfo
29 from Screens.MessageBox import MessageBox
30
31 # Error-print
32 from traceback import print_exc
33 from sys import stdout
34 import os
35
36 VERSION = "2.1.5"
37 class EPGHelpContextMenu(FixedMenu):
38         HELP_RETURN_MAINHELP = 0
39         HELP_RETURN_KEYHELP = 1
40
41         def __init__(self, session):
42                 menu = [(_("General Help"), boundFunction(self.close, self.HELP_RETURN_MAINHELP)),
43                         (_("Key Help"), boundFunction(self.close, self.HELP_RETURN_KEYHELP)),
44                         (_("Cancel"), self.close)]
45
46                 FixedMenu.__init__(self, session, _("EPGRefresh Configuration Help"), menu)
47                 self.skinName = ["EPGRefreshConfigurationHelpContextMenu", "Menu" ]
48
49 class EPGFunctionMenu(FixedMenu):
50         FUNCTION_RETURN_FORCEREFRESH = 0
51         FUNCTION_RETURN_STOPREFRESH = 1
52         FUNCTION_RETURN_SHOWPENDING = 2
53
54         def __init__(self, session):
55                 if epgrefresh.isRunning():
56                         menu = [(_("Stop running refresh"), boundFunction(self.close, self.FUNCTION_RETURN_STOPREFRESH)),
57                                 (_("Pending Services"), boundFunction(self.close, self.FUNCTION_RETURN_SHOWPENDING))]
58                 else:
59                         menu = [(_("Refresh now"), boundFunction(self.close, self.FUNCTION_RETURN_FORCEREFRESH))]
60                 menu.append((_("Cancel"), self.close))
61
62                 FixedMenu.__init__(self, session, _("EPGRefresh Functions"), menu)
63                 self.skinName = ["EPGRefreshConfigurationFunctionContextMenu", "Menu" ]
64
65 class EPGRefreshConfiguration(Screen, HelpableScreen, ConfigListScreen):
66         """Configuration of EPGRefresh"""
67         
68         skin = """<screen name="EPGRefreshConfiguration" position="center,center" size="700,450">
69                 <ePixmap position="0,5" size="140,40" pixmap="skin_default/buttons/red.png" transparent="1" alphatest="on" />
70                 <ePixmap position="140,5" size="140,40" pixmap="skin_default/buttons/green.png" transparent="1" alphatest="on" />
71                 <ePixmap position="280,5" size="140,40" pixmap="skin_default/buttons/yellow.png" transparent="1" alphatest="on" />
72                 <ePixmap position="420,5" size="140,40" pixmap="skin_default/buttons/blue.png" transparent="1" alphatest="on" />
73                 <ePixmap position="572,15" size="35,25" pixmap="skin_default/buttons/key_info.png" alphatest="on" />
74
75                 <widget source="key_red" render="Label" position="0,5" zPosition="1" size="140,40" valign="center" halign="center" font="Regular;21" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" />
76                 <widget source="key_green" render="Label" position="140,5" zPosition="1" size="140,40" valign="center" halign="center" font="Regular;21" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" />
77                 <widget source="key_yellow" render="Label" position="280,5" zPosition="1" size="140,40" valign="center" halign="center" font="Regular;21" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" />
78                 <widget source="key_blue" render="Label" position="420,5" zPosition="1" size="140,40" valign="center" halign="center" font="Regular;21" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" />
79
80                 <widget name="config" position="5,50" size="690,275" scrollbarMode="showOnDemand" />
81                 <ePixmap pixmap="skin_default/div-h.png" position="5,335" zPosition="1" size="690,2" />
82                 <widget source="help" render="Label" position="5,345" size="690,105" font="Regular;21" />
83         </screen>"""
84         
85         def __init__(self, session):
86                 Screen.__init__(self, session)
87                 HelpableScreen.__init__(self)
88                 self.list = []
89                 # Summary
90                 self.setup_title = _("EPGRefresh Configuration")
91                 self.onChangedEntry = []
92                 
93                 self.session = session
94                 
95                 # Although EPGRefresh keeps services in a Set we prefer a list
96                 self.services = (
97                         [x for x in epgrefresh.services[0]],
98                         [x for x in epgrefresh.services[1]]
99                 )
100
101                 ConfigListScreen.__init__(self, self.list, session = session, on_change = self.changed)
102                 self._getConfig()
103
104                 self["config"].onSelectionChanged.append(self.updateHelp)
105
106                 # Initialize Buttons
107                 self["key_red"] = StaticText(_("Cancel"))
108                 self["key_green"] = StaticText(_("OK"))
109                 self["key_yellow"] = StaticText(_("Functions"))
110                 self["key_blue"] = StaticText(_("Edit Services"))
111
112                 self["help"] = StaticText()
113
114                 # Define Actions
115                 self["ColorActions"] = HelpableActionMap(self, "ColorActions",
116                         {
117                                 "yellow": (self.showFunctionMenu, _("Show more Functions")),
118                                 "blue": (self.editServices, _("Edit Services")),
119                         }
120                 )
121                 self["actions"] = HelpableActionMap(self, "ChannelSelectEPGActions",
122                         {
123                                 "showEPGList": (self.keyInfo, _("Show last EPGRefresh - Time")),
124                         }
125                 )
126                 self["ChannelSelectBaseActions"] = HelpableActionMap(self, "ChannelSelectBaseActions",
127                         {
128                                 "nextBouquet": (self.pageup, _("Move page up")),
129                                 "prevBouquet": (self.pagedown, _("Move page down")),
130                         }
131                 )
132                 self["actionstmp"] = ActionMap(["HelpActions"],
133                         {
134                                 "displayHelp": self.showHelp,
135                         }
136                 )
137                 self["SetupActions"] = HelpableActionMap(self, "SetupActions",
138                         {
139                                 "cancel": (self.keyCancel, _("Close and forget changes")),
140                                 "save": (self.keySave, _("Close and save changes")),
141                         }
142                 )
143                 
144                 # Trigger change
145                 self.changed()
146                 self.needsEnigmaRestart = False
147                 self.ServicesChanged = False
148                 
149                 self.onLayoutFinish.append(self.setCustomTitle)
150                 self.onFirstExecBegin.append(self.firstExec)
151                 self["config"].isChanged = self._ConfigisChanged
152
153         def _getConfig(self):
154                 # Name, configElement, HelpTxt, reloadConfig
155                 self.list = [] 
156                 self.list.append(getConfigListEntry(_("Refresh EPG automatically"), config.plugins.epgrefresh.enabled, _("Unless this is enabled, EPGRefresh won't automatically run but needs to be explicitly started by the yellow button in this menu."), True))
157                 if config.plugins.epgrefresh.enabled.value:
158                         self.list.append(getConfigListEntry(_("Duration to stay on service (seconds)"), config.plugins.epgrefresh.interval_seconds, _("This is the duration each service/channel will stay active during a refresh."), False))
159                         self.list.append(getConfigListEntry(_("EPG refresh auto-start earliest (hh:mm)"), config.plugins.epgrefresh.begin, _("An automated refresh will start after this time of day, but before the time specified in next setting."), False))
160                         self.list.append(getConfigListEntry(_("EPG refresh auto-start latest (hh:mm)"), config.plugins.epgrefresh.end, _("An automated refresh will start before this time of day, but after the time specified in previous setting."), False))
161                         self.list.append(getConfigListEntry(_("Delay if not in standby (minutes)"), config.plugins.epgrefresh.delay_standby, _("If the receiver currently isn't in standby, this is the duration which EPGRefresh will wait before retry."), False))
162                         if SystemInfo.get("NumVideoDecoders", 1) > 1:
163                                 self.list.append(getConfigListEntry(_("Refresh EPG using"), config.plugins.epgrefresh.adapter, _("If you want to refresh the EPG in background, you can choose the method which best suits your needs here, e.g. hidden, fake reocrding or regular Picture in Picture."), False))
164                         self.list.append(getConfigListEntry(_("Show Advanced Options"), NoSave(config.plugins.epgrefresh.showadvancedoptions), _("Display more Options"), True))
165                         if config.plugins.epgrefresh.showadvancedoptions.value:
166                                 if config.ParentalControl.configured.value and  config.ParentalControl.servicepinactive.value:
167                                         self.list.append(getConfigListEntry(_("Skip protected Services"), config.plugins.epgrefresh.skipProtectedServices, _("Should protected services be skipped if refresh was started in interactive-mode?"), False))
168                                 self.list.append(getConfigListEntry(_("Show Setup in extension menu"), config.plugins.epgrefresh.show_in_extensionsmenu, _("Enable this to be able to access the EPGRefresh configuration from within the extension menu."), False))
169                                 self.list.append(getConfigListEntry(_("Show 'EPGRefresh Start now' in extension menu"), config.plugins.epgrefresh.show_run_in_extensionsmenu, _("Enable this to be able to start the EPGRefresh from within the extension menu."), False))
170                                 self.list.append(getConfigListEntry(_("Show popup when refresh starts and ends"), config.plugins.epgrefresh.enablemessage, _("This setting controls whether or not an informational message will be shown at start and completion of refresh."), False))
171                                 self.list.append(getConfigListEntry(_("Wake up from standby for EPG refresh"), config.plugins.epgrefresh.wakeup, _("If this is enabled, the plugin will wake up the receiver from standby if possible. Otherwise it needs to be switched on already."), False))
172                                 self.list.append(getConfigListEntry(_("Force scan even if receiver is in use"), config.plugins.epgrefresh.force, _("This setting controls whether or not the refresh will be initiated even though the receiver is active (either not in standby or currently recording)."), False))
173                                 self.list.append(getConfigListEntry(_("Shutdown after EPG refresh"), config.plugins.epgrefresh.afterevent, _("This setting controls whether the receiver should be set to standby after refresh is completed."), False))
174                                 try:
175                                         # try to import autotimer module to check for its existence
176                                         from Plugins.Extensions.AutoTimer.AutoTimer import AutoTimer
177                 
178                                         self.list.append(getConfigListEntry(_("Inherit Services from AutoTimer"), config.plugins.epgrefresh.inherit_autotimer, _("Extend the list of services to refresh by those your AutoTimers use?"), True))
179                                         self.list.append(getConfigListEntry(_("Run AutoTimer after refresh"), config.plugins.epgrefresh.parse_autotimer, _("After a successful refresh the AutoTimer will automatically search for new matches if this is enabled. The options 'Ask*' has only affect on a manually refresh. If EPG-Refresh was called in background the default-Answer will be executed!"), False))
180                                 except ImportError as ie:
181                                         print("[EPGRefresh] AutoTimer Plugin not installed:", ie)
182                         
183                 self["config"].list = self.list
184                 self["config"].setList(self.list)
185
186         def firstExec(self):
187                 from plugin import epgrefreshHelp
188                 if config.plugins.epgrefresh.show_help.value and epgrefreshHelp:
189                         config.plugins.epgrefresh.show_help.value = False
190                         config.plugins.epgrefresh.show_help.save()
191                         epgrefreshHelp.open(self.session)
192
193         def setCustomTitle(self):
194                 self.setTitle(' '.join((_("EPGRefresh Configuration"), _("Version"), VERSION)))
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 isConfigurationChanged(self):
214                 return self.ServicesChanged or self._ConfigisChanged()
215         
216         def _onKeyChange(self):
217                 cur = self["config"].getCurrent()
218                 if cur and cur[3]:
219                         self._getConfig()
220
221         def showHelp(self):
222                 self.session.openWithCallback(self._HelpMenuCallback, EPGHelpContextMenu)
223
224         def _HelpMenuCallback(self, *result):
225                 if not len(result):
226                         return
227                 result = result[0]
228
229                 if result == EPGHelpContextMenu.HELP_RETURN_MAINHELP:
230                         self._showMainHelp()
231                 else:
232                         self._showKeyhelp()
233         
234         def _showMainHelp(self):
235                 from plugin import epgrefreshHelp
236                 if epgrefreshHelp:
237                         epgrefreshHelp.open(self.session)
238         
239         def _showKeyhelp(self):
240                 self.session.openWithCallback(self.callHelpAction, HelpMenu, self.helpList)
241
242         def updateHelp(self):
243                 cur = self["config"].getCurrent()
244                 if cur:
245                         self["help"].text = cur[2]
246
247         def showFunctionMenu(self):
248                 self.session.openWithCallback(self._FunctionMenuCB, EPGFunctionMenu)
249
250         def _FunctionMenuCB(self, *result):
251                 if not len(result):
252                         return
253                 result = result[0]
254
255                 try:
256                         if result == EPGFunctionMenu.FUNCTION_RETURN_FORCEREFRESH:
257                                 self.forceRefresh()
258                         if result == EPGFunctionMenu.FUNCTION_RETURN_STOPREFRESH:
259                                 self.stopRunningRefresh()
260                         if result == EPGFunctionMenu.FUNCTION_RETURN_SHOWPENDING:
261                                 self.showPendingServices()
262                 except:
263                         print("[EPGRefresh] Error in Function - Call")
264                         print_exc(file=stdout)
265         
266         def forceRefresh(self):
267                 if not epgrefresh.isRefreshAllowed():
268                         return
269         
270                 self._saveConfiguration()
271                 epgrefresh.services = (set(self.services[0]), set(self.services[1]))
272                 epgrefresh.forceRefresh(self.session)
273                 self.keySave(False)
274
275         def showPendingServices(self):
276                 epgrefresh.showPendingServices(self.session)
277         
278         def stopRunningRefresh(self):
279                 epgrefresh.stopRunningRefresh(self.session)
280
281         def editServices(self):
282                 self.session.openWithCallback(
283                         self.editServicesCallback,
284                         EPGRefreshServiceEditor,
285                         self.services
286                 )
287
288         def editServicesCallback(self, ret):
289                 if ret:
290                         self.services = ret
291                         self.ServicesChanged = True
292
293         # for Summary
294         def changed(self):
295                 for x in self.onChangedEntry:
296                         try:
297                                 x()
298                         except Exception:
299                                 pass
300         
301         # for Summary
302         def getCurrentEntry(self):
303                 if self["config"].getCurrent():
304                         return self["config"].getCurrent()[0]
305
306         # for Summary
307         def getCurrentValue(self):
308                 if self["config"].getCurrent():
309                         return str(self["config"].getCurrent()[1].getText())
310
311         # for Summary
312         def createSummary(self):
313                 return SetupSummary
314
315         def pageup(self):
316                 self["config"].instance.moveSelection(self["config"].instance.pageUp)
317
318         def pagedown(self):
319                 self["config"].instance.moveSelection(self["config"].instance.pageDown)
320
321         def keyInfo(self):
322                 lastscan = config.plugins.epgrefresh.lastscan.value
323                 if lastscan:
324                         from Tools.FuzzyDate import FuzzyTime
325                         scanDate = ', '.join(FuzzyTime(lastscan))
326                 else:
327                         scanDate = _("never")
328
329                 self.session.open(
330                                 MessageBox,
331                                 _("Last refresh was %s") % (scanDate,),
332                                 type=MessageBox.TYPE_INFO
333                 )
334
335         def cancelConfirm(self, doCancel):
336                 if not doCancel:
337                         return
338                 for x in self["config"].list:
339                         x[1].cancel()
340                 self.close(self.session, False)
341
342         def keyCancel(self):
343                 if self.isConfigurationChanged():
344                         self.session.openWithCallback(
345                                 self.cancelConfirm,
346                                 MessageBox,
347                                 _("Really close without saving settings?")
348                         )
349                 else:
350                         self.close(self.session, False)
351         
352         def _saveConfiguration(self):
353                 epgrefresh.services = (set(self.services[0]), set(self.services[1]))
354                 epgrefresh.saveConfiguration()
355
356                 for x in self["config"].list:
357                         x[1].save()             
358                 configfile.save()
359                 
360         def keySave(self, doSaveConfiguration = True):
361                 if self.isConfigurationChanged():
362                         if not epgrefresh.isRefreshAllowed():
363                                 return
364                         else:
365                                 epgrefresh.stop()
366                                 if doSaveConfiguration:
367                                         self._saveConfiguration()
368                 
369                 self.close(self.session, self.needsEnigmaRestart)
370
371