edbc590991538710d7d83cb8c043cdf68313eaff
[enigma2.git] / lib / python / Plugins / Extensions / Modem / plugin.py
1 def getDefaultGateway():
2         f = open("/proc/net/route", "r")
3         if f:
4                 for line in f.readlines():
5                         tokens = line.split('\t')
6                         if tokens[1] == '00000000': #dest 0.0.0.0
7                                 return int(tokens[2], 16)
8         return None
9
10 def getTelephone():
11         f = open("/etc/ppp/options", "r")
12         if f:
13                 for line in f.readlines():
14                         if line.find('connect') == 0:
15                                 line = line[line.find(' ')+1:]
16                                 line = line[line.find(' ')+1:]
17                                 line = line[:line.find('"')]
18                                 return line
19         return ""
20
21 def setTelephone(tel):
22         f = open("/etc/ppp/options", "r+")
23         if f:
24                 lines = f.readlines()
25                 f.seek(0)
26                 for line in lines:
27                         if line.find('connect') == 0:
28                                 p = line.find(' ')
29                                 p = line.find(' ', p+1)
30                                 line = line[:p+1]
31                                 f.write(line+tel+'"\n')
32                         else:
33                                 f.write(line)
34
35 def getSecretString():
36         f = open("/etc/ppp/pap-secrets", "r")
37         if f:
38                 for line in f.readlines():
39                         if line[0] == '#' or line.find('*') == -1:
40                                 continue
41                         for ch in (' ', '\t', '\n', '"'):
42                                 line = line.replace(ch, '')
43                         return line
44         return None
45
46 def setSecretString(secret):
47         f = open("/etc/ppp/pap-secrets", 'r+')
48         if f:
49                 lines = f.readlines()
50                 f.seek(0)
51                 for line in lines:
52                         if line[0] == '#' or line.find('*') == -1:
53                                 f.write(line)
54                                 continue
55                         f.write(secret+'\n')
56
57 from Screens.Screen import Screen
58 from Plugins.Plugin import PluginDescriptor
59 from enigma import eConsoleAppContainer, eTimer
60 from Components.Label import Label
61 from Components.Button import Button
62 from Components.ConfigList import ConfigList
63 from Components.config import ConfigText, ConfigPassword, KEY_LEFT, KEY_RIGHT, KEY_0, KEY_DELETE, KEY_BACKSPACE
64 from Components.ActionMap import NumberActionMap, ActionMap
65 from os import system
66
67 NONE = 0
68 CONNECT = 1
69 ABORT = 2
70 DISCONNECT = 3
71
72 gateway = None
73
74 def pppdClosed(ret):
75         global gateway
76         print "modem disconnected", ret
77         if gateway:
78                 #FIXMEEE... hardcoded for little endian!!
79                 system("route add default gw %d.%d.%d.%d" %(gateway&0xFF, (gateway>>8)&0xFF, (gateway>>16)&0xFF, (gateway>>24)&0xFF))
80
81 connected = False
82 conn = eConsoleAppContainer()
83 conn.appClosed.append(pppdClosed)
84
85 class ModemSetup(Screen):
86         skin = """
87                 <screen position="180,100" size="320,300" title="Modem" >
88                 <ePixmap pixmap="skin_default/buttons/green.png" position="10,10" size="140,40" alphatest="on" />
89                 <ePixmap pixmap="skin_default/buttons/red.png" position="160,10" size="140,40" alphatest="on" />
90                 <widget name="key_green" position="10,10" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
91                 <widget name="key_red" position="160,10" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
92                 <widget name="list" position="10,60" size="300,120" />
93                 <widget name="state" position="10,210" size="300,80" font="Regular;20" />
94                 </screen>"""
95
96         def nothing(self):
97                 print "nothing!"
98
99         def __init__(self, session, args = None):
100                 global connected
101                 global conn
102                 self.skin = ModemSetup.skin
103                 secret = getSecretString()
104                 user = secret[:secret.find('*')]
105                 password = secret[secret.find('*')+1:]
106                 self.username = ConfigText(user, fixed_size=False)
107                 self.password = ConfigPassword(password, fixed_size=False)
108                 self.phone = ConfigText(getTelephone(), fixed_size=False)
109                 self.phone.setUseableChars(u"0123456789")
110                 lst = [ (_("Username"), self.username),
111                         (_("Password"), self.password),
112                         (_("Phone number"), self.phone) ]
113                 self["list"] = ConfigList(lst)
114                 self["key_green"] = Button("")
115                 self["key_red"] = Button("")
116                 self["state"] = Label("")
117                 self["actions"] = NumberActionMap(["ModemActions"],
118                 {
119                         "cancel": self.close,
120                         "left": self.keyLeft,
121                         "right": self.keyRight,
122                         "connect": self.connect,
123                         "disconnect": self.disconnect,
124                         "deleteForward": self.deleteForward,
125                         "deleteBackward": self.deleteBackward,
126                         "0": self.keyNumber,
127                         "1": self.keyNumber,
128                         "2": self.keyNumber,
129                         "3": self.keyNumber,
130                         "4": self.keyNumber,
131                         "5": self.keyNumber,
132                         "6": self.keyNumber,
133                         "7": self.keyNumber,
134                         "8": self.keyNumber,
135                         "9": self.keyNumber
136                 }, 0)
137
138                 self["ListActions"] = ActionMap(["ListboxDisableActions"],
139                 {
140                         "moveUp": self.nothing,
141                         "moveDown": self.nothing,
142                         "moveTop": self.nothing,
143                         "moveEnd": self.nothing,
144                         "pageUp": self.nothing,
145                         "pageDown": self.nothing
146                 }, -1)
147
148                 self.stateTimer = eTimer()
149                 self.stateTimer.callback.append(self.stateLoop)
150
151                 conn.appClosed.append(self.pppdClosed)
152                 conn.dataAvail.append(self.dataAvail)
153
154                 Screen.__init__(self, session)
155                 self.onClose.append(self.__closed)
156                 self.onLayoutFinish.append(self.__layoutFinished)
157
158         def __layoutFinished(self):
159                 global conn
160                 if conn.running():
161                         self["state"].setText(_("Connected!"));
162                         self.green_function = NONE
163                         self.red_function = DISCONNECT
164                 else:
165                         self.green_function = CONNECT
166                         self.red_function = NONE
167                 self.updateGui()
168
169         def __closed(self):
170                 global connected
171                 conn.appClosed.remove(self.pppdClosed)
172                 conn.dataAvail.remove(self.dataAvail)
173                 if not connected:
174                         conn.sendCtrlC()
175                 setTelephone(self.phone.getText())
176                 setSecretString(self.username.getText() + ' * ' + self.password.getText())
177
178         def stateLoop(self):
179                 txt = self["state"].getText()
180                 txt += '.'
181                 self["state"].setText(txt)
182
183         def connect(self):
184                 if self.green_function == CONNECT:
185                         global gateway
186                         gateway = getDefaultGateway()
187                         self["state"].setText(_("Dialing:"))
188                         system("route del default")
189                         system("modprobe ppp_async");
190                         self.stateTimer.start(1000,False)
191                         setTelephone(self.phone.getText())
192                         setSecretString(self.username.getText() + ' * ' + self.password.getText())
193                         ret = conn.execute("pppd", "pppd", "-d", "-detach")
194                         if ret:
195                                 print "execute pppd failed!"
196                                 self.pppdClosed(ret)
197                                 pppdClosed(ret)
198                         self.green_function = NONE
199                         self.red_function = ABORT
200                         self.updateGui()
201
202         def disconnect(self):
203                 conn.sendCtrlC()
204                 self.red_function = NONE
205                 self.updateGui()
206
207         def keyLeft(self):
208                 if self.green_function == CONNECT:
209                         self["list"].handleKey(KEY_LEFT)
210
211         def keyRight(self):
212                 if self.green_function == CONNECT:
213                         self["list"].handleKey(KEY_RIGHT)
214
215         def keyNumber(self, number):
216                 if self.green_function == CONNECT:
217                         self["list"].handleKey(KEY_0 + number)
218
219         def deleteForward(self):
220                 if self.green_function == CONNECT:
221                         self["list"].handleKey(KEY_DELETE)
222
223         def deleteBackward(self):
224                 if self.green_function == CONNECT:
225                         self["list"].handleKey(KEY_BACKSPACE)
226
227         def pppdClosed(self, retval):
228                 global connected
229                 self.stateTimer.stop()
230                 self.red_function = NONE
231                 self.green_function = CONNECT
232                 self["state"].setText("")
233                 self.updateGui()
234                 connected = False
235
236         def dataAvail(self, text):
237                 if text.find("Serial connection established") != -1:
238                         tmp = self["state"].getText()
239                         tmp += "OK\nLogin:"
240                         self["state"].setText(tmp)
241                 if text.find("PAP authentication succeeded") != -1:
242                         tmp = self["state"].getText()
243                         tmp += "OK\n";
244                         self["state"].setText(tmp)
245                         self.stateTimer.stop()
246                 if text.find("ip-up finished") != -1:
247                         global connected
248                         tmp = self["state"].getText()
249                         tmp += "Connected :)\n"
250                         self["state"].setText(tmp)
251                         self.red_function = DISCONNECT
252                         connected=True
253                 if text.find("Connect script failed") != -1:
254                         tmp = self["state"].getText()
255                         tmp += "FAILED\n"
256                         self["state"].setText(tmp)
257                         self.stateTimer.stop()
258                         self.red_function = NONE
259                         self.green_function = CONNECT
260                 self.updateGui()
261
262         def updateGui(self):
263                 if self.red_function == NONE:
264                         self["key_red"].setText("")
265                 elif self.red_function == DISCONNECT:
266                         self["key_red"].setText(_("Disconnect"))
267                 elif self.red_function == ABORT:
268                         self["key_red"].setText(_("Abort"))
269                 if self.green_function == NONE:
270                         self["key_green"].setText("")
271                 elif self.green_function == CONNECT:
272                         self["key_green"].setText(_("Connect"))
273                 focus_enabled = self.green_function == CONNECT
274                 self["list"].instance.setSelectionEnable(focus_enabled)
275                 self["ListActions"].setEnabled(not focus_enabled)
276
277 def main(session, **kwargs):
278         session.open(ModemSetup)
279
280 def Plugins(**kwargs):
281         return PluginDescriptor(name="Modem", description="plugin to connect to internet via builtin modem", where = PluginDescriptor.WHERE_PLUGINMENU, fnc=main)