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