autotimer,pluginsort: allow mphelp localization
[enigma2-plugins.git] / autotimer / src / plugin.py
1 from __future__ import print_function
2
3 from . import _, config
4
5 # GUI (Screens)
6 from Screens.MessageBox import MessageBox
7 from Tools.Notifications import AddPopup
8
9 # Plugin
10 from Components.PluginComponent import plugins
11 from Plugins.Plugin import PluginDescriptor
12
13 from AutoTimer import AutoTimer
14 autotimer = AutoTimer()
15 autopoller = None
16
17 #pragma mark - Help
18 try:
19         from Plugins.SystemPlugins.MPHelp import registerHelp, XMLHelpReader
20         from Tools.Directories import resolveFilename, SCOPE_PLUGINS
21         reader = XMLHelpReader(resolveFilename(SCOPE_PLUGINS, "Extensions/AutoTimer/mphelp.xml"), translate=_)
22         autotimerHelp = registerHelp(*reader)
23 except Exception as e:
24         print("[AutoTimer] Unable to initialize MPHelp:", e,"- Help not available!")
25         autotimerHelp = None
26 #pragma mark -
27
28 # Autostart
29 def autostart(reason, **kwargs):
30         global autopoller
31
32         # Startup
33         if reason == 0 and config.plugins.autotimer.autopoll.value:
34                 # Start Poller
35                 from AutoPoller import AutoPoller
36                 autopoller = AutoPoller()
37                 autopoller.start()
38
39                 # Install NPB, main is too late because the Browser is already running
40                 from Plugins.SystemPlugins.Toolkit import NotifiablePluginBrowser
41                 NotifiablePluginBrowser.install()
42         # Shutdown
43         elif reason == 1:
44                 # Stop Poller
45                 if autopoller is not None:
46                         autopoller.stop()
47                         autopoller = None
48
49                 # We re-read the config so we won't save wrong information
50                 try:
51                         autotimer.readXml()
52                 except Exception:
53                         # XXX: we should at least dump the error
54                         pass
55                 else:
56                         autotimer.writeXml()
57
58 # Webgui
59 def sessionstart(reason, **kwargs):
60         if reason == 0 and "session" in kwargs:
61                 try:
62                         from Plugins.Extensions.WebInterface.WebChilds.Toplevel import addExternalChild
63                         from Plugins.Extensions.WebInterface.WebChilds.Screenpage import ScreenPage
64                         from twisted.web import static
65                         from twisted.python import util
66                         from WebChilds.UploadResource import UploadResource
67
68                         from AutoTimerResource import AutoTimerDoParseResource, \
69                                 AutoTimerListAutoTimerResource, AutoTimerAddOrEditAutoTimerResource, \
70                                 AutoTimerRemoveAutoTimerResource, AutoTimerChangeSettingsResource, \
71                                 AutoTimerSettingsResource, AutoTimerSimulateResource, API_VERSION
72                 except ImportError as ie:
73                         pass
74                 else:
75                         if hasattr(static.File, 'render_GET'):
76                                 class File(static.File):
77                                         def render_POST(self, request):
78                                                 return self.render_GET(request)
79                         else:
80                                 File = static.File
81
82                         # webapi
83                         root = AutoTimerListAutoTimerResource()
84                         root.putChild('parse', AutoTimerDoParseResource())
85                         root.putChild('remove', AutoTimerRemoveAutoTimerResource())
86                         root.putChild('edit', AutoTimerAddOrEditAutoTimerResource())
87                         root.putChild('get', AutoTimerSettingsResource())
88                         root.putChild('set', AutoTimerChangeSettingsResource())
89                         root.putChild('simulate', AutoTimerSimulateResource())
90                         addExternalChild( ("autotimer", root , "AutoTimer-Plugin", API_VERSION, False) )
91
92                         # webgui
93                         session = kwargs["session"]
94                         root = File(util.sibpath(__file__, "web-data"))
95                         root.putChild("web", ScreenPage(session, util.sibpath(__file__, "web"), True) )
96                         root.putChild('tmp', File('/tmp'))
97                         root.putChild("uploadfile", UploadResource(session))
98                         addExternalChild( ("autotimereditor", root, "AutoTimer", "1", True) )
99
100 # Mainfunction
101 def main(session, **kwargs):
102         global autopoller
103
104         try:
105                 autotimer.readXml()
106         except SyntaxError as se:
107                 session.open(
108                         MessageBox,
109                         _("Your config file is not well-formed:\n%s") % (str(se)),
110                         type = MessageBox.TYPE_ERROR,
111                         timeout = 10
112                 )
113                 return
114
115         # Do not run in background while editing, this might screw things up
116         if autopoller is not None:
117                 autopoller.pause()
118
119         from AutoTimerOverview import AutoTimerOverview
120         session.openWithCallback(
121                 editCallback,
122                 AutoTimerOverview,
123                 autotimer
124         )
125
126 def handleAutoPoller():
127         global autopoller
128
129         # Start autopoller again if wanted
130         if config.plugins.autotimer.autopoll.value:
131                 if autopoller is None:
132                         from AutoPoller import AutoPoller
133                         autopoller = AutoPoller()
134                 autopoller.start(initial = False)
135         # Remove instance if not running in background
136         else:
137                 autopoller = None
138
139 def editCallback(session):
140         # Don't parse EPG if editing was canceled
141         if session is not None:
142                 autotimer.parseEPGAsync().addCallback(parseEPGCallback)#.addErrback(parseEPGErrback)
143         else:
144                 handleAutoPoller()
145
146 #def parseEPGErrback(failure):
147 #       AddPopup(
148 #               _("AutoTimer failed with error %s" (str(failure),)),
149 #       )
150 #
151 #       # Save xml
152 #       autotimer.writeXml()
153 #       handleAutoPoller()
154
155 def parseEPGCallback(ret):
156         AddPopup(
157                 _("Found a total of %d matching Events.\n%d Timer were added and\n%d modified,\n%d conflicts encountered,\n%d similars added.") % (ret[0], ret[1], ret[2], len(ret[4]), len(ret[5])),
158                 MessageBox.TYPE_INFO,
159                 10,
160                 'AT_PopUp_ID_ParseEPGCallback'
161         )
162
163         # Save xml
164         autotimer.writeXml()
165         handleAutoPoller()
166
167 # Movielist
168 def movielist(session, service, **kwargs):
169         from AutoTimerEditor import addAutotimerFromService
170         addAutotimerFromService(session, service)
171
172 # Event Info
173 def eventinfo(session, servicelist, **kwargs):
174         from AutoTimerEditor import AutoTimerEPGSelection
175         ref = session.nav.getCurrentlyPlayingServiceReference()
176         session.open(AutoTimerEPGSelection, ref)
177
178 # XXX: we need this helper function to identify the descriptor
179 # Extensions menu
180 def extensionsmenu(session, **kwargs):
181         main(session, **kwargs)
182
183 def housekeepingExtensionsmenu(el):
184         if el.value:
185                 plugins.addPlugin(extDescriptor)
186         else:
187                 try:
188                         plugins.removePlugin(extDescriptor)
189                 except ValueError as ve:
190                         print("[AutoTimer] housekeepingExtensionsmenu got confused, tried to remove non-existant plugin entry... ignoring.")
191
192 config.plugins.autotimer.show_in_extensionsmenu.addNotifier(housekeepingExtensionsmenu, initial_call = False, immediate_feedback = True)
193 extDescriptor = PluginDescriptor(name="AutoTimer", description = _("Edit Timers and scan for new Events"), where = PluginDescriptor.WHERE_EXTENSIONSMENU, fnc = extensionsmenu, needsRestart = False)
194
195 def Plugins(**kwargs):
196         l = [
197                 PluginDescriptor(where=PluginDescriptor.WHERE_AUTOSTART, fnc=autostart, needsRestart=False),
198                 PluginDescriptor(where=PluginDescriptor.WHERE_SESSIONSTART, fnc=sessionstart, needsRestart=False),
199                 # TRANSLATORS: description of AutoTimer in PluginBrowser
200                 PluginDescriptor(name="AutoTimer", description = _("Edit Timers and scan for new Events"), where = PluginDescriptor.WHERE_PLUGINMENU, icon = "plugin.png", fnc = main, needsRestart = False),
201                 # TRANSLATORS: AutoTimer title in MovieList (automatically opens importer, I consider this no further interaction)
202                 PluginDescriptor(name="AutoTimer", description= _("add AutoTimer"), where = PluginDescriptor.WHERE_MOVIELIST, fnc = movielist, needsRestart = False),
203                 # TRANSLATORS: AutoTimer title in EventInfo dialog (requires the user to select an event to base the AutoTimer on)
204                 PluginDescriptor(name=_("add AutoTimer..."), where = PluginDescriptor.WHERE_EVENTINFO, fnc = eventinfo, needsRestart = False),
205         ]
206         if config.plugins.autotimer.show_in_extensionsmenu.value:
207                 l.append(extDescriptor)
208         return l
209