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