PushService: Initial release
[enigma2-plugins.git] / pushservice / src / PushServiceConfigScreen.py
1 '''
2 Created on 06.11.2011
3
4 @author: Frank Glaser
5 '''
6
7 # Config
8 from Components.config import *
9 from Components.ConfigList import ConfigListScreen
10 from Components.Sources.StaticText import StaticText
11
12 # Screen
13 from Components.ActionMap import ActionMap
14 from Components.ActionMap import HelpableActionMap
15 from Components.ScrollLabel import ScrollLabel
16 from enigma import eSize, ePoint, getDesktop
17 from Screens.Screen import Screen
18 from Screens.Setup import SetupSummary
19 from Screens.ChoiceBox import ChoiceBox
20 from Screens.MessageBox import MessageBox
21 from Screens.HelpMenu import HelpableScreen
22
23 # Plugin internal
24 from . import _
25 from PushService import PushService
26
27
28 # Constants
29 separator = "".ljust(250,"-")
30
31
32 # TODO Everytime the user will enter the ConfigurationScreen:
33 #  Modules will be reloaded
34 # TODO Everytime the user will leave the ConfigurationScreen:
35 #  Plugins will be reloaded
36
37 #######################################################
38 # Configuration screen
39 class PushServiceConfigScreen(Screen, ConfigListScreen, HelpableScreen):
40
41         skin = """
42                 <screen name="PushServiceConfigScreen" title="" position="center,center" size="565,350">
43                         <ePixmap position="0,5" size="140,40" pixmap="skin_default/buttons/red.png" transparent="1" alphatest="on" />
44                         <ePixmap position="140,5" size="140,40" pixmap="skin_default/buttons/green.png" transparent="1" alphatest="on" />
45                         <ePixmap position="280,5" size="140,40" pixmap="skin_default/buttons/yellow.png" transparent="1" alphatest="on" />
46                         <ePixmap position="420,5" size="140,40" pixmap="skin_default/buttons/blue.png" transparent="1" alphatest="on" />
47                         <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" />
48                         <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" />
49                         <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" />
50                         <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" />
51                         <widget name="config" position="5,50" size="555,225" enableWrapAround="1" scrollbarMode="showOnDemand" />
52                         <ePixmap pixmap="skin_default/div-h.png" position="0,275" zPosition="1" size="565,2" />
53                 </screen>
54         """
55 #                       <widget source="help" render="Label" position="5,280" size="555,63" font="Regular;21" />
56
57         def __init__(self, session):
58                 #TODO
59                 try:
60                         Screen.__init__(self, session)
61                         HelpableScreen.__init__(self)
62                         self.skinName = ["PushServiceConfigScreen", "ConfigListScreen"]
63                         
64                         # Summary
65                         from plugin import NAME, VERSION, gPushService
66                         self.setup_title = NAME + " " + _("Configuration") + " " + VERSION
67                         
68                         if gPushService:
69                                 # Save PushService instance
70                                 self.pushservice = gPushService
71                                 # Stop PushService
72                                 self.pushservice.stop()
73                         else:
74                                 # PushService not running - Instantiate a new one
75                                 global gPushService
76                                 self.pushservice = PushService()
77                         
78                         # Load local plugins to work on
79                         self.plugins = self.pushservice.load()
80                         
81                         # Buttons
82                         self["key_red"]   = StaticText(_("Cancel"))
83                         self["key_green"] = StaticText(_("OK"))
84                         self["key_blue"]  = StaticText(_("Add plugin"))
85                         self["key_yellow"]  = StaticText(_("Remove plugin"))
86                         #TODO
87                         #self["key_info"] test mail
88                         #self["key_play"] test run
89                         
90                         #TODO Maybe LATER
91                         #self["help"] = StaticText()
92                         #self["HelpWindow"].hide()
93                         #self["VirtualKB"].setEnabled(False)
94                         #self["VKeyIcon"].boolean = False
95                         self.help_window = None
96                         
97                         # Define Actions
98                         #Bug self["custom_actions"] = HelpableActionMap(self, ["SetupActions", "ColorActions", "PushServiceConfigActions"],
99                         self["custom_actions"] = HelpableActionMap(self, "PushServiceConfigActions",
100                         {
101                                 "cancel":                               (self.keyCancel,    _("Exit without saving")),
102                                 "save":                                 (self.keySave,      _("Save and exit.")),
103                                 "blue":                                 (self.addPlugin,    _("Add plugin")),
104                                 "yellow":                               (self.removePlugin, _("Remove plugin")),
105                                 "pageUp":                               (self.pageUp,       _("Page up")),
106                                 "pageDown":                     (self.pageDown,     _("Page down")),
107                                 "testMail":                     (self.testMail,     _("Send a test mail")),
108                                 "runNow":                               (self.runNow,       _("Test run")),
109                         }, -2) # higher priority
110                         
111                         # Initialize Configuration part
112                         self.list = []
113                         ConfigListScreen.__init__(self, self.list, session = session, on_change = self.buildConfig)
114                         self.buildConfig()
115                         
116                         # Override selectionChanged because our config tuples are bigger
117                         self.onChangedEntry = [ ]
118                         def selectionChanged():
119                                 current = self["config"].getCurrent()
120                                 if self["config"].current != current:
121                                         if self["config"].current:
122                                                 self["config"].current[1].onDeselect(self.session)
123                                         if current:
124                                                 current[1].onSelect(self.session)
125                                         self["config"].current = current
126                                 for x in self["config"].onSelectionChanged:
127                                         x()
128                         self["config"].selectionChanged = selectionChanged
129                         
130                         self.setTitle(self.setup_title)
131                 except Exception, e:
132                         print "PushServiceConfigScreen init exception " + str(e)
133
134         def buildConfig(self, selectuniqueid=None):
135                 #TODO
136                 try:
137                         self.list = []
138                         select = None
139                         lappend = self.list.append
140                         
141                         lappend( getConfigListEntry( _("Enable PushService"), config.pushservice.enable, 0 ) )
142                         
143                         if config.pushservice.enable.value:
144                                 lappend( getConfigListEntry( _("Dreambox name"), config.pushservice.boxname, 0 ) )
145                                 lappend( getConfigListEntry( _("Config file"), config.pushservice.xmlpath, 0 ) )
146
147                                 lappend( getConfigListEntry( _("Start time (HH:MM)"), config.pushservice.time, 0 ) )
148                                 lappend( getConfigListEntry( _("Period in hours (0=disabled)"), config.pushservice.period, 0 ) )
149                                 lappend( getConfigListEntry( _("Run on boot"), config.pushservice.runonboot, 0 ) )
150                                 
151                                 lappend( getConfigListEntry( _("SMTP Server"), config.pushservice.smtpserver, 0 ) )
152                                 lappend( getConfigListEntry( _("SMTP Port"), config.pushservice.smtpport, 0 ) )
153                                 lappend( getConfigListEntry( _("SMTP SSL"), config.pushservice.smtptyp, 0 ) )
154                                 lappend( getConfigListEntry( _("User name"), config.pushservice.username, 0 ) )
155                                 lappend( getConfigListEntry( _("Password"), config.pushservice.password, 0 ) )
156                                 lappend( getConfigListEntry( _("Mail from"), config.pushservice.mailfrom, 0 ) )
157                                 lappend( getConfigListEntry( _("Mail to or leave empty"), config.pushservice.mailto, 0 ) )
158                                 
159                                 if self.plugins:
160                                         lappend( getConfigListEntry( separator, config.pushservice.about, 0 ) )
161                                         
162                                         for idx, plugin in enumerate(self.plugins):
163                                                 lappend( getConfigListEntry( plugin.getNameId(), plugin.getConfigEnable(), idx ) )
164                                                 if plugin.getUniqueID() == selectuniqueid:
165                                                         # Select the added plugin
166                                                         select = len(self.list)-1
167                                                 if plugin.getEnable():
168                                                         for key, element, description in plugin.getConfigOptions():
169                                                                 lappend( getConfigListEntry( "  " + str(description), element, idx ) )
170                         
171                         self["config"].setList( self.list )
172                         del lappend
173                         
174                         if select is not None:
175                                 self["config"].instance.moveSelectionTo(select)
176                         
177                 except Exception, e:
178                         print _("PushServiceConfigScreen build exception ") + str(e)
179
180         def addPlugin(self):
181                 self.hideHelpWindow()
182                 addlist = []
183                 pluginclasslist = []
184                 if self.plugins:
185                         pluginclasslist = [ plg.getPluginClass() for plg in self.plugins]
186                 for name, module in self.pushservice.modules.iteritems():
187                         if module.forceSingle():
188                                 # We have to check if there is already a plugin instance
189                                 if module in pluginclasslist:
190                                         # A plugin instance already exists
191                                         continue
192                         addlist.append( (name, name) )
193                         addlist.sort()
194                 self.session.openWithCallback(self.addPluginCB, ChoiceBox,_("Add plugin"), addlist)
195
196         def addPluginCB(self, result):
197                 name = result and result[1]
198                 if name:
199                         plugin = self.pushservice.instantiatePlugin( name )
200                         if plugin:
201                                 plugin.setEnable(True)
202                                 
203                                 self.plugins.append( plugin )
204                                 self.plugins.sort( key=lambda x: ( x.getUniqueID() ) )
205                                 
206                                 self.buildConfig( plugin.getUniqueID() )
207
208         def removePlugin(self):
209                 self.hideHelpWindow()
210                 if self.plugins:
211                         select = 0
212                         current = self["config"].getCurrent()
213                         if current:
214                                 select = current[2]
215                         plist = []
216                         if self.plugins:
217                                 plist = [( plugin.getNameId(), plugin ) for plugin in self.plugins ]
218                         self.session.openWithCallback(self.removePluginCB, ChoiceBox,_("Remove plugin"), list=plist, selection=select)
219
220         def removePluginCB(self, result):
221                 plugin = result and result[1]
222                 if plugin:
223                         self.plugins.remove( plugin )
224                         self.buildConfig()
225
226         # Overwrite ConfigListScreen keySave function
227         def keySave(self):
228                 self.hideHelpWindow()
229                 
230                 # Save E2 PushService config
231                 self.saveAll()
232                 
233                 # Build xml config and write it
234                 self.pushservice.save(self.plugins)
235                 
236                 from plugin import gPushService
237                 global gPushService
238                 if config.pushservice.enable.value:
239                         gPushService = self.pushservice
240                         #TODO gPushService.load()
241                         gPushService.start() #with load
242                 else:
243                         gPushService = None
244                 
245                 self.close()
246
247         # Overwrite ConfigListScreen keyCancel function
248         def keyCancel(self):
249                 self.hideHelpWindow()
250                 # Call baseclass function
251                 ConfigListScreen.keyCancel(self)
252
253         # Overwrite ConfigListScreen cancelConfirm function
254         def cancelConfirm(self, result):
255                 from plugin import gPushService
256                 if gPushService:
257                         # Start PushService
258                         self.pushservice.start()
259                 
260                 # Call baseclass function
261                 ConfigListScreen.cancelConfirm(self, result)
262
263         # Overwrite Screen close function
264         def close(self):
265                 self.hideHelpWindow()
266                 from plugin import ABOUT
267                 self.session.openWithCallback(self.closeConfirm, MessageBox, ABOUT, MessageBox.TYPE_INFO)
268
269         def closeConfirm(self, dummy=None):
270                 # Call baseclass function
271                 Screen.close(self)
272
273         def getCurrentEntry(self):
274                 return self["config"].getCurrent()[0]
275
276         def getCurrentValue(self):
277                 return str(self["config"].getCurrent()[1].getText())
278
279         def createSummary(self):
280                 return SetupSummary
281
282         def pageUp(self):
283                 self["config"].instance.moveSelection(self["config"].instance.pageUp)
284
285         def pageDown(self):
286                 self["config"].instance.moveSelection(self["config"].instance.pageDown)
287
288         def testMail(self):
289                 self.hideHelpWindow()
290                 self.testMailBox = None
291                 timeout = 30
292                 # Send test mail
293                 connector = self.pushservice.push(_("Test mail"), _("If You can see this, Your SMTP configuration is correct."), [], self.success, self.error, timeout=timeout)
294                 def testMailCB(result):
295                         connector.disconnect()
296                 self.testMailBox = self.session.openWithCallback(testMailCB, TestMailBox, _("Testing SMTP"), _("Sending test mail...\n\nCancel?"), MessageBox.TYPE_INFO, timeout=timeout)
297         def success(self):
298                 if self.testMailBox:
299                         self.testMailBox.setText(_("The mail has been sent successfully"))
300         def error(self, e):
301                 if self.testMailBox:
302                         self.testMailBox.setText(_("Mail sent failed:\n\n%s") % e.getErrorMessage())
303                         self.testMailBox.setText(_("Mail sent failed:\n\n%s\n\n%s") % (e.type, e.value))
304
305         def runNow(self):
306                 self.hideHelpWindow()
307                 # Test actually not saved configuration
308                 response = self.pushservice.run(self.plugins, False)
309                 self.session.open(TestRunConsole, _("Test run"), response)
310
311         def hideHelpWindow(self):
312                 current = self["config"].getCurrent()
313                 if current and hasattr(current[1], "help_window"):
314                         help_window = current[1].help_window
315                         if help_window:
316                                 help_window.hide()
317
318
319 class TestMailBox(MessageBox):
320         def __init__(self, session, title, text, type = MessageBox.TYPE_YESNO, timeout = -1, close_on_any_key = False, default = True, enable_input = True, msgBoxID = None):
321                 MessageBox.__init__(self, session, text, type, timeout, close_on_any_key, default, enable_input, msgBoxID)
322                 self.skinName = ["TestMailBox", "MessageBox"]
323                 self.setTitle(title)
324
325         def setText(self, text):
326                 self.stopTimer()
327                 self["text"].setText(text)
328                 #self.resize()
329                 self.createGUIScreen(self.instance, self.desktop, updateonly = True)
330
331
332 class TestRunConsole(Screen):
333         def __init__(self, session, title = "Console", text = ""):
334                 Screen.__init__(self, session)
335                 self.skinName = ["TestMailBox", "Console"]
336                         
337                 self["text"] = ScrollLabel("")
338                 self["actions"] = ActionMap(["WizardActions", "DirectionActions"], 
339                 {
340                         "ok": self.cancel,
341                         "back": self.cancel,
342                         "up": self["text"].pageUp,
343                         "down": self["text"].pageDown
344                 }, -1)
345                 self.setTitle(title)
346                 self.setText(text)
347
348         def setText(self, text):
349                 self["text"].setText(text)
350
351         def cancel(self):
352                 self.close()