150dba9debc1ffd419a716ff5ee11afb770bc7bf
[enigma2.git] / lib / python / Plugins / SystemPlugins / NetworkWizard / NetworkWizard.py
1 from Screens.Wizard import wizardManager, WizardSummary
2 from Screens.WizardLanguage import WizardLanguage
3 from Screens.Rc import Rc
4 from Screens.MessageBox import MessageBox
5 from Components.Pixmap import Pixmap, MovingPixmap, MultiPixmap
6 from Components.Sources.Boolean import Boolean
7 from Components.config import config, ConfigBoolean, configfile, ConfigYesNo, NoSave, ConfigSubsection, ConfigText, getConfigListEntry, ConfigSelection, ConfigPassword
8 from Components.Network import iNetwork
9 from Tools.Directories import resolveFilename, SCOPE_PLUGINS, SCOPE_SKIN_IMAGE
10 from enigma import eTimer
11
12 config.misc.firstrun = ConfigBoolean(default = True)
13 list = []
14 list.append("WEP")
15 list.append("WPA")
16 list.append("WPA2")
17 list.append("WPA/WPA2")
18
19 weplist = []
20 weplist.append("ASCII")
21 weplist.append("HEX")
22
23 config.plugins.wlan = ConfigSubsection()
24 config.plugins.wlan.essid = NoSave(ConfigText(default = "home", fixed_size = False))
25 config.plugins.wlan.hiddenessid = NoSave(ConfigText(default = "home", fixed_size = False))
26
27 config.plugins.wlan.encryption = ConfigSubsection()
28 config.plugins.wlan.encryption.enabled = NoSave(ConfigYesNo(default = False))
29 config.plugins.wlan.encryption.type = NoSave(ConfigSelection(list, default = "WPA/WPA2" ))
30 config.plugins.wlan.encryption.wepkeytype = NoSave(ConfigSelection(weplist, default = "ASCII"))
31 config.plugins.wlan.encryption.psk = NoSave(ConfigPassword(default = "mysecurewlan", fixed_size = False))
32
33 class NetworkWizard(WizardLanguage, Rc):
34         skin = """
35                 <screen position="0,0" size="720,576" title="Welcome..." flags="wfNoBorder" >
36                         <widget name="text" position="153,40" size="340,300" font="Regular;22" />
37                         <widget source="list" render="Listbox" position="53,340" size="440,180" scrollbarMode="showOnDemand" >
38                                 <convert type="StringList" />
39                         </widget>
40                         <widget name="config" position="53,340" zPosition="1" size="440,180" transparent="1" scrollbarMode="showOnDemand" />
41                         <ePixmap pixmap="skin_default/buttons/button_red.png" position="40,225" zPosition="0" size="15,16" transparent="1" alphatest="on" />
42                         <widget name="languagetext" position="55,225" size="95,30" font="Regular;18" />
43                         <widget name="wizard" pixmap="skin_default/wizard.png" position="40,50" zPosition="10" size="110,174" alphatest="on" />
44                         <widget name="rc" pixmaps="skin_default/rc.png,skin_default/rcold.png" position="500,50" zPosition="10" size="154,500" alphatest="on" />
45                         <widget name="arrowdown" pixmap="skin_default/arrowdown.png" position="-100,-100" zPosition="11" size="37,70" alphatest="on" />
46                         <widget name="arrowdown2" pixmap="skin_default/arrowdown.png" position="-100,-100" zPosition="11" size="37,70" alphatest="on" />
47                         <widget name="arrowup" pixmap="skin_default/arrowup.png" position="-100,-100" zPosition="11" size="37,70" alphatest="on" />
48                         <widget name="arrowup2" pixmap="skin_default/arrowup.png" position="-100,-100" zPosition="11" size="37,70" alphatest="on" />
49                         <widget source="VKeyIcon" render="Pixmap" pixmap="skin_default/buttons/key_text.png" position="40,260" zPosition="0" size="35,25" transparent="1" alphatest="on" >
50                                 <convert type="ConditionalShowHide" />
51                         </widget>
52                         <widget name="HelpWindow" pixmap="skin_default/buttons/key_text.png" position="125,170" zPosition="1" size="1,1" transparent="1" alphatest="on" />      
53                 </screen>"""
54         def __init__(self, session, interface = None):
55                 self.xmlfile = resolveFilename(SCOPE_PLUGINS, "SystemPlugins/NetworkWizard/networkwizard.xml")
56                 WizardLanguage.__init__(self, session, showSteps = False, showStepSlider = False)
57                 Rc.__init__(self)
58                 self.session = session
59                 self["wizard"] = Pixmap()
60                 self["HelpWindow"] = Pixmap()
61                 self["HelpWindow"].hide()
62                 self["VKeyIcon"] = Boolean(False)
63
64                 self.InstalledInterfaceCount = None
65                 self.Adapterlist = None
66                 self.InterfaceState = None
67                 self.isInterfaceUp = None
68                 self.WlanPluginInstalled = None
69                 self.ap = None
70                 if interface is not None:
71                         self.selectedInterface = interface
72                 else:
73                         self.selectedInterface = None
74                 self.NextStep = None
75                 self.resetRef = None
76                 self.checkRef = None
77                 self.AdapterRef = None
78                 self.APList = None
79                 self.newAPlist = None
80                 self.WlanList = None
81                 self.oldlist = None
82                 self.originalAth0State = None
83                 self.originalEth0State = None
84                 self.originalWlan0State = None
85                 self.originalInterfaceStateChanged = False
86                 self.Text = None
87                 self.rescanTimer = eTimer()
88                 self.rescanTimer.callback.append(self.rescanTimerFired)
89                 self.getInstalledInterfaceCount()
90                 self.isWlanPluginInstalled()
91                 
92         def exitWizardQuestion(self, ret = False):
93                 if (ret):
94                         self.markDone()
95                         self.close()
96                 
97         def markDone(self):
98                 self.rescanTimer.stop()
99                 del self.rescanTimer
100                 self.checkOldInterfaceState()
101                 pass
102
103         def getInstalledInterfaceCount(self):
104                 self.rescanTimer.stop()
105                 self.Adapterlist = iNetwork.getAdapterList()
106                 self.InstalledInterfaceCount = len(self.Adapterlist)
107                 self.originalAth0State = iNetwork.getAdapterAttribute('ath0', 'up')
108                 self.originalEth0State = iNetwork.getAdapterAttribute('eth0', 'up')
109                 self.originalWlan0State = iNetwork.getAdapterAttribute('wlan0', 'up')
110
111         def selectInterface(self):
112                 self.InterfaceState = None
113                 if self.selectedInterface is None and self.InstalledInterfaceCount <= 1:
114                         if self.selectedInterface == 'eth0':
115                                 self.NextStep = 'nwconfig'
116                         else:
117                                 self.NextStep = 'scanwlan'
118                         self.checkInterface(self.selectedInterface)
119                 elif self.selectedInterface is not None and self.InstalledInterfaceCount <= 1:
120                         if self.selectedInterface == 'eth0':
121                                 self.NextStep = 'nwconfig'
122                         else:
123                                 self.NextStep = 'scanwlan'
124                         self.checkInterface(self.selectedInterface)
125                 elif self.selectedInterface is None and self.InstalledInterfaceCount > 1:
126                         self.NextStep = 'selectinterface'
127                         self.currStep = self.getStepWithID(self.NextStep)
128                         self.afterAsyncCode()
129                 elif self.selectedInterface is not None and self.InstalledInterfaceCount > 1:
130                         if self.selectedInterface == 'eth0':
131                                 self.NextStep = 'nwconfig'
132                         else:
133                                 self.NextStep = 'scanwlan'
134                         self.checkInterface(self.selectedInterface)
135                 else:
136                         self.NextStep = 'selectinterface'
137                         self.currStep = self.getStepWithID(self.NextStep)
138                         self.afterAsyncCode()                   
139
140         def checkOldInterfaceState(self):
141                 # disable up interface if it was originally down and config is unchanged.
142                 if self.originalAth0State is False and self.originalInterfaceStateChanged is False:
143                         if iNetwork.checkforInterface('ath0') is True:
144                                 iNetwork.deactivateInterface('ath0')            
145                 if self.originalEth0State is False and self.originalInterfaceStateChanged is False:
146                         if iNetwork.checkforInterface('eth0') is True:
147                                 iNetwork.deactivateInterface('eth0')
148                 if self.originalWlan0State is False and self.originalInterfaceStateChanged is False:
149                         if iNetwork.checkforInterface('wlan0') is True:
150                                 iNetwork.deactivateInterface('wlan0')
151
152         def listInterfaces(self):
153                 self.rescanTimer.stop()
154                 self.checkOldInterfaceState()
155                 list = [(iNetwork.getFriendlyAdapterName(x),x) for x in iNetwork.getAdapterList()]
156                 list.append((_("Exit network wizard"), "end"))
157                 return list
158
159         def InterfaceSelectionMade(self, index):
160                 self.selectedInterface = index
161                 self.InterfaceSelect(index)
162
163         def InterfaceSelect(self, index):
164                 if index == 'end':
165                         self.NextStep = 'end'
166                 elif index == 'eth0':
167                         self.NextStep = 'nwconfig'
168                 else:
169                         self.NextStep = 'scanwlan'
170
171         def InterfaceSelectionMoved(self):
172                 self.InterfaceSelect(self.selection)
173                 
174         def checkInterface(self,iface):
175                 self.rescanTimer.stop()
176                 if self.Adapterlist is None:
177                         self.Adapterlist = iNetwork.getAdapterList()
178                 if self.NextStep is not 'end':
179                         if len(self.Adapterlist) == 0:
180                                 #Reset Network to defaults if network broken
181                                 iNetwork.resetNetworkConfig('lan', self.resetNetworkConfigCB)
182                                 self.resetRef = self.session.openWithCallback(self.resetNetworkConfigFinished, MessageBox, _("Please wait while we prepare your network interfaces..."), type = MessageBox.TYPE_INFO, enable_input = False)
183                         if iface in ('eth0', 'wlan0', 'ath0'):
184                                 if iface in iNetwork.configuredNetworkAdapters and len(iNetwork.configuredNetworkAdapters) == 1:
185                                         if iNetwork.getAdapterAttribute(iface, 'up') is True:
186                                                 self.isInterfaceUp = True
187                                         else:
188                                                 self.isInterfaceUp = False
189                                         self.currStep = self.getStepWithID(self.NextStep)
190                                         self.afterAsyncCode()
191                                 else:
192                                         self.isInterfaceUp = iNetwork.checkforInterface(iface)
193                                         self.currStep = self.getStepWithID(self.NextStep)
194                                         self.afterAsyncCode()
195                 else:
196                         self.resetNetworkConfigFinished(False)
197                         
198         def resetNetworkConfigFinished(self,data):
199                 if data is True:
200                         self.currStep = self.getStepWithID(self.NextStep)
201                         self.afterAsyncCode()
202                 else:
203                         self.currStep = self.getStepWithID(self.NextStep)
204                         self.afterAsyncCode()
205
206         def resetNetworkConfigCB(self,callback,iface):
207                 if callback is not None:
208                         if callback is True:
209                                 iNetwork.getInterfaces(self.getInterfacesFinished)
210                                 
211         def getInterfacesFinished(self, data):
212                 if data is True:
213                         if iNetwork.getAdapterAttribute(self.selectedInterface, 'up') is True:
214                                 self.isInterfaceUp = True
215                         else:
216                                 self.isInterfaceUp = False
217                         self.resetRef.close(True)
218                 else:
219                         print "we should never come here!"
220
221         def AdapterSetupEnd(self, iface):
222                 self.originalInterfaceStateChanged = True
223                 if iNetwork.getAdapterAttribute(iface, "dhcp") is True:
224                         iNetwork.checkNetworkState(self.AdapterSetupEndFinished)
225                         self.AdapterRef = self.session.openWithCallback(self.AdapterSetupEndCB, MessageBox, _("Please wait while we test your network..."), type = MessageBox.TYPE_INFO, enable_input = False)
226                 else:
227                         self.currStep = self.getStepWithID("confdns")
228                         self.afterAsyncCode()
229
230         def AdapterSetupEndCB(self,data):
231                 if data is True:
232                         if self.selectedInterface in ('wlan0', 'ath0'):
233                                 if self.WlanPluginInstalled == True:
234                                         from Plugins.SystemPlugins.WirelessLan.Wlan import iStatus
235                                         iStatus.getDataForInterface(self.selectedInterface,self.checkWlanStateCB)
236                                 else:
237                                         self.currStep = self.getStepWithID("checklanstatusend")
238                                         self.afterAsyncCode()                                   
239                         else:
240                                 self.currStep = self.getStepWithID("checklanstatusend")
241                                 self.afterAsyncCode()
242
243         def AdapterSetupEndFinished(self,data):
244                 if data <= 2:
245                         self.InterfaceState = True
246                 else:
247                         self.InterfaceState = False
248                 self.AdapterRef.close(True)
249                         
250         def checkWlanStateCB(self,data,status):
251                 if data is not None:
252                         if data is True:
253                                 if status is not None:
254                                         text1 = _("Your Dreambox is now ready to use.\n\nYour internet connection is working now.\n\n")
255                                         text2 = _('Accesspoint:') + "\t" + str(status[self.selectedInterface]["acesspoint"]) + "\n"
256                                         text3 = _('SSID:') + "\t" + str(status[self.selectedInterface]["essid"]) + "\n"
257                                         text4 = _('Link Quality:') + "\t" + str(status[self.selectedInterface]["quality"])+"%" + "\n"
258                                         text5 = _('Signal Strength:') + "\t" + str(status[self.selectedInterface]["signal"]) + "\n"
259                                         text6 = _('Bitrate:') + "\t" + str(status[self.selectedInterface]["bitrate"]) + "\n"
260                                         text7 = _('Encryption:') + " " + str(status[self.selectedInterface]["encryption"]) + "\n"
261                                         text8 = _("Please press OK to continue.")
262                                         infotext = text1 + text2 + text3 + text4 + text5 + text7 +"\n" + text8
263                                         self.currStep = self.getStepWithID("checkWlanstatusend")
264                                         self.Text = infotext
265                                         if str(status[self.selectedInterface]["acesspoint"]) == "Not-Associated":
266                                                 self.InterfaceState = False
267                                         self.afterAsyncCode()
268
269         def checkNetwork(self):
270                 iNetwork.checkNetworkState(self.checkNetworkStateCB)
271                 self.checkRef = self.session.openWithCallback(self.checkNetworkCB, MessageBox, _("Please wait while we test your network..."), type = MessageBox.TYPE_INFO, enable_input = False)
272
273         def checkNetworkCB(self,data):
274                 if data is True:
275                         if self.selectedInterface in ('wlan0', 'ath0'):
276                                 if self.WlanPluginInstalled == True:
277                                         from Plugins.SystemPlugins.WirelessLan.Wlan import iStatus
278                                         iStatus.getDataForInterface(self.selectedInterface,self.checkWlanStateCB)
279                                 else:
280                                         self.currStep = self.getStepWithID("checklanstatusend")
281                                         self.afterAsyncCode()                                   
282                         else:
283                                 self.currStep = self.getStepWithID("checklanstatusend")
284                                 self.afterAsyncCode()
285
286         def checkNetworkStateCB(self,data):
287                 if data <= 2:
288                         self.InterfaceState = True
289                 else:
290                         self.InterfaceState = False
291                 self.checkRef.close(True)
292         
293         def rescanTimerFired(self):
294                 self.rescanTimer.stop()
295                 self.updateAPList()
296
297         def updateAPList(self):
298                 self.oldlist = self.APList
299                 self.newAPlist = []
300                 newList = []
301                 newListIndex = None
302                 currentListEntry = None
303                 newList = self.listAccessPoints()
304
305                 for oldentry in self.oldlist:
306                         if oldentry not in newList:
307                                 newList.append(oldentry)
308                                 
309                 for newentry in newList:
310                         if newentry[1] == "hidden...":
311                                 continue
312                         self.newAPlist.append(newentry)
313                 
314                 if len(self.newAPlist):
315                         if "hidden..." not in self.newAPlist:
316                                 self.newAPlist.append(( _("enter hidden network SSID"), "hidden..." ))
317
318                         if (self.wizard[self.currStep].has_key("dynamiclist")):
319                                 currentListEntry = self["list"].getCurrent()
320                                 idx = 0
321                                 for entry in self.newAPlist:
322                                         if entry == currentListEntry:
323                                                 newListIndex = idx
324                                         idx +=1
325                                 self.wizard[self.currStep]["evaluatedlist"] = self.newAPlist
326                                 self['list'].setList(self.newAPlist)
327                                 self["list"].setIndex(newListIndex)
328                                 self["list"].updateList(self.newAPlist)
329
330         def listAccessPoints(self):
331                 self.APList = []
332                 try:
333                         from Plugins.SystemPlugins.WirelessLan.Wlan import Wlan
334                 except ImportError:
335                         self.APList.append( ( _("No networks found"),_("unavailable") ) )
336                         return self.APList
337                 else:
338                         try:
339                                 self.w = Wlan(self.selectedInterface)
340                                 aps = self.w.getNetworkList()
341                         except ValueError:
342                                 self.APList = []
343                                 self.APList.append( ( _("No networks found"),_("unavailable") ) )
344                                 return self.APList
345                         else:
346                                 if aps is not None:
347                                         print "[NetworkWizard.py] got Accespoints!"
348                                         tmplist = []
349                                         complist = []
350                                         for ap in aps:
351                                                 a = aps[ap]
352                                                 if a['active']:
353                                                         tmplist.append( (a['bssid'], a['essid']) )
354                                                         complist.append( (a['bssid'], a['essid']) )
355                                         
356                                         for entry in tmplist:
357                                                 if entry[1] == "":
358                                                         for compentry in complist:
359                                                                 if compentry[0] == entry[0]:
360                                                                         complist.remove(compentry)
361                                         for entry in complist:
362                                                 self.APList.append( (entry[1], entry[1]) )
363         
364                                 if "hidden..." not in self.APList:
365                                         self.APList.append(( _("enter hidden network SSID"), "hidden..." ))
366                         
367                                 self.rescanTimer.start(3000)
368                                 return self.APList
369
370         def AccessPointsSelectionMade(self, index):
371                 self.ap = index
372                 self.WlanList = []
373                 currList = []
374                 if (self.wizard[self.currStep].has_key("dynamiclist")):
375                         currList = self['list'].list
376                         for entry in currList:
377                                 self.WlanList.append( (entry[1], entry[0]) )
378                 self.AccessPointsSelect(index)
379
380         def AccessPointsSelect(self, index):
381                 self.NextStep = 'wlanconfig'
382
383         def AccessPointsSelectionMoved(self):
384                 self.AccessPointsSelect(self.selection)
385
386         def checkWlanSelection(self):
387                 self.rescanTimer.stop()
388                 self.currStep = self.getStepWithID(self.NextStep)
389
390         def isWlanPluginInstalled(self):
391                 try:
392                         from Plugins.SystemPlugins.WirelessLan.Wlan import Wlan
393                 except ImportError:
394                         self.WlanPluginInstalled = False
395                 else:
396                         self.WlanPluginInstalled = True
397
398         def listChoices(self):
399                 self.rescanTimer.stop()
400                 list = []
401                 if self.WlanPluginInstalled == True:
402                         list.append((_("Configure your wireless LAN again"), "scanwlan"))
403                 list.append((_("Configure your internal LAN"), "nwconfig"))
404                 list.append((_("Exit network wizard"), "end"))          
405                 return list
406
407         def ChoicesSelectionMade(self, index):
408                 self.ChoicesSelect(index)
409
410         def ChoicesSelect(self, index):
411                 if index == 'end':
412                         self.NextStep = 'end'
413                 elif index == 'nwconfig':
414                         self.selectedInterface = "eth0"
415                         self.NextStep = 'nwconfig'
416                 else:
417                         self.NextStep = 'scanwlan'
418
419         def ChoicesSelectionMoved(self):
420                 pass
421