epgrefresh: use ready-function of eDVBLocalTimeHandler instead of custom check agains...
[enigma2-plugins.git] / epgrefresh / src / plugin.py
1 from __future__ import print_function
2
3 # for localized messages
4 from . import _
5
6 # Config
7 from Components.config import config, ConfigYesNo, ConfigNumber, \
8         ConfigSelection, ConfigSubsection, ConfigClock, ConfigYesNo
9
10 # Calculate default begin/end
11 from time import time, localtime, mktime
12 now = localtime()
13 begin = mktime((
14         now.tm_year, now.tm_mon, now.tm_mday, 20, 15, \
15         0, now.tm_wday, now.tm_yday, now.tm_isdst)
16 )
17 end = mktime((
18         now.tm_year, now.tm_mon, now.tm_mday, 06, 30, \
19         0, now.tm_wday, now.tm_yday, now.tm_isdst)
20 )
21
22 #Configuration
23 config.plugins.epgrefresh = ConfigSubsection()
24 config.plugins.epgrefresh.enabled = ConfigYesNo(default = False)
25 config.plugins.epgrefresh.begin = ConfigClock(default = int(begin))
26 config.plugins.epgrefresh.end = ConfigClock(default = int(end))
27 config.plugins.epgrefresh.interval = ConfigNumber(default = 2)
28 config.plugins.epgrefresh.delay_standby = ConfigNumber(default = 10)
29 config.plugins.epgrefresh.inherit_autotimer = ConfigYesNo(default = False)
30 config.plugins.epgrefresh.afterevent = ConfigYesNo(default = False)
31 config.plugins.epgrefresh.force = ConfigYesNo(default = False)
32 config.plugins.epgrefresh.enablemessage = ConfigYesNo(default = True)
33 config.plugins.epgrefresh.wakeup = ConfigYesNo(default = False)
34 config.plugins.epgrefresh.lastscan = ConfigNumber(default = 0)
35 config.plugins.epgrefresh.parse_autotimer = ConfigYesNo(default = False)
36 config.plugins.epgrefresh.adapter = ConfigSelection(choices = [
37                 ("main", _("Main Picture")),
38                 ("pip", _("Picture in Picture")),
39                 ("pip_hidden", _("Picture in Picture (hidden)")),
40                 ("record", _("Fake recording")),
41         ], default = "main"
42 )
43 config.plugins.epgrefresh.show_in_extensionsmenu = ConfigYesNo(default = False)
44 config.plugins.epgrefresh.show_help = ConfigYesNo(default = True)
45
46 # convert previous parameter
47 config.plugins.epgrefresh.background = ConfigYesNo(default = False)
48 if config.plugins.epgrefresh.background.value:
49         config.plugins.epgrefresh.adapter.value = "pip_hidden"
50         config.plugins.epgrefresh.background.value = False
51         config.plugins.epgrefresh.save()
52
53 del now, begin, end
54
55 #pragma mark - Workaround for unset clock
56
57 from enigma import eDVBLocalTimeHandler
58
59 def timeCallback(isCallback=True):
60         """Time Callback/Autostart management."""
61         thInstance = eDVBLocalTimeHandler.getInstance()
62         if isCallback:
63                 # NOTE: this assumes the clock is actually ready when called back
64                 # this may not be true, but we prefer silently dying to waiting forever
65                 thInstance.m_timeUpdated.get().remove(timeCallback)
66         elif not thInstance.ready():
67                 thInstance.m_timeUpdated.get().append(timeCallback)
68                 return
69
70         if config.plugins.epgrefresh.wakeup.value:
71                 now = localtime()
72                 begin = int(mktime(
73                         (now.tm_year, now.tm_mon, now.tm_mday,
74                         config.plugins.epgrefresh.begin.value[0],
75                         config.plugins.epgrefresh.begin.value[1],
76                         0, now.tm_wday, now.tm_yday, now.tm_isdst)
77                 ))
78                 # booted +- 10min from begin of timespan
79                 if abs(time() - begin) < 600:
80                         from Screens.MessageBox import MessageBox
81                         from Tools.Notifications import AddNotificationWithCallback
82                         from Tools.BoundFunction import boundFunction
83                         # XXX: we use a notification because this will be suppressed otherwise
84                         AddNotificationWithCallback(
85                                 boundFunction(standbyQuestionCallback, session),
86                                 MessageBox,
87                                 _("This might have been an automated bootup to refresh the EPG. For this to happen it is recommended to put the receiver to Standby.\nDo you want to do this now?"),
88                                 timeout = 15
89                         )
90         epgrefresh.start()
91
92 #pragma mark - Help
93 try:
94         from Plugins.SystemPlugins.MPHelp import registerHelp, XMLHelpReader
95         from Tools.Directories import resolveFilename, SCOPE_PLUGINS
96         reader = XMLHelpReader(resolveFilename(SCOPE_PLUGINS, "Extensions/EPGRefresh/mphelp.xml"))
97         epgrefreshHelp = registerHelp(*reader)
98 except Exception as e:
99         print("[EPGRefresh] Unable to initialize MPHelp:", e,"- Help not available!")
100         epgrefreshHelp = None
101 #pragma mark -
102
103 # Plugin
104 from EPGRefresh import epgrefresh
105 from EPGRefreshConfiguration import EPGRefreshConfiguration
106 from EPGRefreshService import EPGRefreshService
107
108 # Plugins
109 from Components.PluginComponent import plugins
110 from Plugins.Plugin import PluginDescriptor
111
112 def standbyQuestionCallback(session, res = None):
113         if res:
114                 from Screens.Standby import Standby
115                 session.open(Standby)
116
117 # Autostart
118 def autostart(reason, **kwargs):
119         if reason == 0 and "session" in kwargs:
120                 session = kwargs["session"]
121                 epgrefresh.session = session
122
123                 if config.plugins.epgrefresh.enabled.value:
124                         timeCallback(isCallback=False)
125
126         elif reason == 1:
127                 epgrefresh.stop()
128
129 def getNextWakeup():
130         # Return invalid time if not automatically refreshing
131         if not config.plugins.epgrefresh.enabled.value or \
132                 not config.plugins.epgrefresh.wakeup.value:
133
134                 return -1
135
136         now = localtime()
137         begin = int(mktime(
138                 (now.tm_year, now.tm_mon, now.tm_mday,
139                 config.plugins.epgrefresh.begin.value[0],
140                 config.plugins.epgrefresh.begin.value[1],
141                 0, now.tm_wday, now.tm_yday, now.tm_isdst)
142         ))
143         # todays timespan has not yet begun
144         if begin > time():
145                 return begin
146         # otherwise add 1 day
147         return begin+86400
148
149 # Mainfunction
150 def main(session, **kwargs):
151         epgrefresh.stop()
152         session.openWithCallback(
153                 doneConfiguring,
154                 EPGRefreshConfiguration
155         )
156
157 def doneConfiguring(session, **kwargs):
158         if config.plugins.epgrefresh.enabled.value:
159                 epgrefresh.start(session)
160
161 # Eventinfo
162 def eventinfo(session, servicelist, **kwargs):
163         ref = session.nav.getCurrentlyPlayingServiceReference()
164         if not ref:
165                 return
166         sref = ref.toString()
167         # strip all after last :
168         pos = sref.rfind(':')
169         if pos != -1:
170                 sref = sref[:pos+1]
171
172         epgrefresh.services[0].add(EPGRefreshService(str(sref), None))
173
174 # XXX: we need this helper function to identify the descriptor
175 # Extensions menu
176 def extensionsmenu(session, **kwargs):
177         main(session, **kwargs)
178
179 def housekeepingExtensionsmenu(el):
180         if el.value:
181                 plugins.addPlugin(extDescriptor)
182         else:
183                 try:
184                         plugins.removePlugin(extDescriptor)
185                 except ValueError as ve:
186                         print("[EPGRefresh] housekeepingExtensionsmenu got confused, tried to remove non-existant plugin entry... ignoring.")
187
188 config.plugins.epgrefresh.show_in_extensionsmenu.addNotifier(housekeepingExtensionsmenu, initial_call = False, immediate_feedback = True)
189 extDescriptor = PluginDescriptor(name="EPGRefresh", description = _("Automatically refresh EPG"), where = PluginDescriptor.WHERE_EXTENSIONSMENU, fnc = extensionsmenu, needsRestart=False)
190
191 def Plugins(**kwargs):
192         # NOTE: this might be a little odd to check this, but a user might expect
193         # the plugin to resume normal operation if installed during runtime, but
194         # this is not given if the plugin is supposed to run in background (as we
195         # won't be handed the session which we need to zap). So in turn we require
196         # a restart if-and only if-we're installed during runtime AND running in
197         # background. To improve the user experience in this situation, we hide
198         # all references to this plugin.
199         needsRestart = config.plugins.epgrefresh.enabled.value and not plugins.firstRun
200         list = [
201                 PluginDescriptor(
202                         name = "EPGRefresh",
203                         where = [
204                                 PluginDescriptor.WHERE_AUTOSTART,
205                                 PluginDescriptor.WHERE_SESSIONSTART
206                         ],
207                         fnc = autostart,
208                         wakeupfnc = getNextWakeup,
209                         needsRestart = needsRestart,
210                 ),
211                 PluginDescriptor(
212                         name = _("add to EPGRefresh"),
213                         where = PluginDescriptor.WHERE_EVENTINFO,
214                         fnc = eventinfo,
215                         needsRestart = needsRestart,
216                 ),
217                 PluginDescriptor(
218                         name = "EPGRefresh",
219                         description = _("Automatically refresh EPG"),
220                         where = PluginDescriptor.WHERE_PLUGINMENU, 
221                         fnc = main,
222                         needsRestart = needsRestart,
223                 ),
224         ]
225         if config.plugins.epgrefresh.show_in_extensionsmenu.value:
226                 extDescriptor.needsRestart = needsRestart
227                 list.append(extDescriptor)
228
229         return list