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