- add meta informations for upcoming extension manager (not yet activated)9
[enigma2-plugins.git] / ftpbrowser / src / FTPServerManager.py
1 # for localized messages
2 from . import _
3
4 # GUI (Screens)
5 from Components.ConfigList import ConfigListScreen
6 from Screens.MessageBox import MessageBox
7 from Screens.Screen import Screen
8 from NTIVirtualKeyBoard import NTIVirtualKeyBoard
9
10 # GUI (Summary)
11 from Screens.Setup import SetupSummary
12
13 # GUI (Components)
14 from Components.ActionMap import ActionMap
15 from Components.Sources.List import List
16 from Components.Sources.StaticText import StaticText
17
18 # Config
19 from Components.config import config, ConfigInteger, ConfigSubsection, \
20                 ConfigText, ConfigPassword, ConfigYesNo, getConfigListEntry
21
22 # For new and improved _parse
23 from urlparse import urlparse, urlunparse
24
25 def _parse(url, defaultPort = None):
26         url = url.strip()
27         parsed = urlparse(url)
28         scheme = parsed[0]
29         path = urlunparse(('','')+parsed[2:])
30
31         if defaultPort is None:
32                 if scheme == 'https':
33                         defaultPort = 443
34                 elif scheme == 'ftp':
35                         defaultPort = 21
36                 else:
37                         defaultPort = 80
38
39         host, port = parsed[1], defaultPort
40
41         if '@' in host:
42                 username, host = host.split('@')
43                 if ':' in username:
44                         username, password = username.split(':')
45                 else:
46                         password = ""
47         else:
48                 username = ""
49                 password = ""
50
51         if ':' in host:
52                 host, port = host.split(':')
53                 port = int(port)
54
55         if path == "":
56                 path = "/"
57
58         return scheme, host, port, path, username, password
59
60 class FTPServer:
61         def __init__(self, cfg):
62                 self.cfg = cfg
63
64         def getCfg(self):
65                 return self.cfg
66
67         def getName(self):
68                 return self.cfg.name.value
69
70         def getAddress(self):
71                 return self.cfg.address.value
72
73         def getUsername(self):
74                 return self.cfg.username.value
75
76         def getPassword(self):
77                 return self.cfg.password.value
78
79         def getPort(self):
80                 return self.cfg.port.value
81
82         def getPassive(self):
83                 return self.cfg.passive.value
84
85         def getPath(self):
86                 # TODO: implement
87                 return '/'
88
89         def getURI(self):
90                 if self.getUsername() != "":
91                         uri = "ftp://%s:%s@%s:%d%s" % (self.getUsername(), self.getPassword(), self.getAddress(), self.getPort(), self.getPath())
92                 else:
93                         uri = "ftp://%s:%d%s" % (self.getAddress(), self.getPort(), self.getPath())
94                 return uri
95
96         def save(self):
97                 self.cfg.save()
98
99         def cancel(self):
100                 self.cfg.cancel()
101
102 def ftpserverFromURI(uri, name = "", save = True):
103         scheme, host, port, path, username, password = _parse(uri, defaultPort = 21)
104         
105         newServer = ConfigSubsection()
106         if save:
107                 config.plugins.ftpbrowser.server.append(newServer)
108         newServer.name = ConfigText(fixed_size = False)
109         newServer.name.value = name or host
110         newServer.address = ConfigText(fixed_size = False)
111         newServer.address.value = host
112         newServer.username = ConfigText(fixed_size = False)
113         newServer.username.value = username
114         newServer.password = ConfigPassword()
115         newServer.password.value = password
116         newServer.port = ConfigInteger(0, (0, 65535))
117         newServer.port.value = port
118         newServer.passive = ConfigYesNo(False)
119
120         if save:
121                 newServer.save()
122                 config.plugins.ftpbrowser.servercount.value += 1
123                 config.plugins.ftpbrowser.servercount.save()
124
125         return FTPServer(newServer)
126
127 class FTPServerEditor(ConfigListScreen, Screen):
128         skin = """
129                 <screen position="center,center" size="560,180" title="FTP Server Editor">
130                         <ePixmap pixmap="skin_default/buttons/red.png" position="0,0" size="140,40" transparent="1" alphatest="on" />
131                         <ePixmap pixmap="skin_default/buttons/green.png" position="140,0" size="140,40" transparent="1" alphatest="on" />
132                         <ePixmap pixmap="skin_default/buttons/yellow.png" position="280,0" size="140,40" transparent="1" alphatest="on" />
133                         <ePixmap pixmap="skin_default/buttons/blue.png" position="420,0" size="140,40" transparent="1" alphatest="on" />
134                         <widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" valign="center" halign="center" backgroundColor="#1f771f" transparent="1" />
135                         <widget source="key_green" render="Label" position="140,0" zPosition="1" size="140,40" font="Regular;20" valign="center" halign="center" backgroundColor="#1f771f" transparent="1" />
136                         <widget source="key_yellow" render="Label" position="280,0" zPosition="1" size="140,40" font="Regular;20" valign="center" halign="center" backgroundColor="#1f771f" transparent="1" />
137                         <widget source="key_blue" render="Label"  position="420,0" zPosition="1" size="140,40" font="Regular;20" valign="center" halign="center" backgroundColor="#1f771f" transparent="1" />
138                         <widget name="config" position="10,50" size="550,130" scrollbarMode="showOnDemand" />
139                 </screen>"""
140
141         def __init__(self, session, server):
142                 Screen.__init__(self, session)
143
144                 self.onChangedEntry = []
145                 self.setup_title = _("FTP Server Editor")
146                 self.server = server
147
148                 self["key_red"] = StaticText(_("Exit"))
149                 self["key_green"] = StaticText(_("OK"))
150                 self["key_yellow"] = StaticText("")
151                 self["key_blue"] = StaticText(_("Enter URI"))
152
153                 ConfigListScreen.__init__(self, [
154                         getConfigListEntry(_("Name:"), server.cfg.name),
155                         getConfigListEntry(_("Address:"), server.cfg.address),
156                         getConfigListEntry(_("Username:"), server.cfg.username),
157                         getConfigListEntry(_("Password:"), server.cfg.password),
158                         getConfigListEntry(_("Port:"), server.cfg.port),
159                         getConfigListEntry(_("Passive:"), server.cfg.passive),
160                 ])
161                 
162                 self["actions"] = ActionMap(["SetupActions", "ColorActions"],
163                         {
164                                 "save": self.keySave,
165                                 "cancel": self.keyCancel,
166                                 "blue": self.getURI,
167                         }, -2)
168
169                 self.onLayoutFinish.append(self.layoutFinished)
170
171         def layoutFinished(self):
172                 self.setTitle(_("FTP Server Editor"))
173
174         def changed(self):
175                 for x in self.onChangedEntry:
176                         try:
177                                 x()
178                         except Exception:
179                                 pass
180
181         def getCurrentEntry(self):
182                 return self["config"].getCurrent()[0]
183
184         def getCurrentValue(self):
185                 return str(self["config"].getCurrent()[1].getText())
186
187         def createSummary(self):
188                 return SetupSummary
189
190         def gotURI(self, res):
191                 if res:
192                         cfg = self.server.cfg
193
194                         # _parse gets confused without a scheme
195                         if not res.startswith("ftp://"):
196                                 res = "ftp://" + res
197                         scheme, host, port, path, username, password = _parse(res, defaultPort = 21)
198
199                         cfg.address.value = host
200                         cfg.username.value = username
201                         cfg.password.value = password
202                         cfg.port.value = port
203
204         def getURI(self):
205                 self.session.openWithCallback(
206                         self.gotURI,
207                         NTIVirtualKeyBoard,
208                         title = _("Enter URI of FTP Server:"),
209                         text = self.server.getURI(),
210                 )
211
212         def keySave(self):
213                 self.saveAll()
214                 self.close(True)
215
216 class FTPServerManagerSummary(Screen):
217         skin = """
218         <screen position="0,0" size="132,64">
219                 <widget source="parent.Title" render="Label" position="6,4" size="120,21" font="Regular;18" />
220                 <widget source="parent.list" render="Label" position="6,25" size="120,21" font="Regular;16">
221                         <convert type="StringListSelection" />
222                 </widget>
223                 <widget source="global.CurrentTime" render="Label" position="56,46" size="82,18" font="Regular;16" >
224                         <convert type="ClockToText">WithSeconds</convert>
225                 </widget>
226         </screen>"""
227
228 class FTPServerManager(Screen):
229         skin = """
230                 <screen position="center,center" size="560,420" title="FTP Server Manager" >
231                         <ePixmap pixmap="skin_default/buttons/red.png" position="0,0" size="140,40" transparent="1" alphatest="on" />
232                         <ePixmap pixmap="skin_default/buttons/green.png" position="140,0" size="140,40" transparent="1" alphatest="on" />
233                         <ePixmap pixmap="skin_default/buttons/yellow.png" position="280,0" size="140,40" transparent="1" alphatest="on" />
234                         <ePixmap pixmap="skin_default/buttons/blue.png" position="420,0" size="140,40" transparent="1" alphatest="on" />
235                         <widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" valign="center" halign="center" backgroundColor="#1f771f" transparent="1" />
236                         <widget source="key_green" render="Label" position="140,0" zPosition="1" size="140,40" font="Regular;20" valign="center" halign="center" backgroundColor="#1f771f" transparent="1" />
237                         <widget source="key_yellow" render="Label" position="280,0" zPosition="1" size="140,40" font="Regular;20" valign="center" halign="center" backgroundColor="#1f771f" transparent="1" />
238                         <widget source="key_blue" render="Label" position="420,0" zPosition="1" size="140,40" font="Regular;20" valign="center" halign="center" backgroundColor="#1f771f" transparent="1" />
239                         <widget source="list" render="Listbox" position="0,50" size="560,360" scrollbarMode="showAlways">
240                                 <convert type="TemplatedMultiContent">
241                                         {"template": [
242                                                         MultiContentEntryText(pos=(1,1), size=(540,22), text = 0, font = 0, flags = RT_HALIGN_LEFT|RT_VALIGN_CENTER),
243                                                 ],
244                                           "fonts": [gFont("Regular", 20)],
245                                           "itemHeight": 24
246                                          }
247                                 </convert>
248                         </widget>
249                 </screen>"""
250
251         def __init__(self, session):
252                 Screen.__init__(self, session)
253                 self.changed = False
254
255                 self["key_red"] = StaticText(_("Delete"))
256                 self["key_green"] = StaticText(_("Add"))
257                 self["key_yellow"] = StaticText(_("Edit"))
258                 self["key_blue"] = StaticText(_("Save"))
259                 self["list"] = List([])
260                 
261                 self["actions"] = ActionMap(["OkCancelActions", "ColorActions"],
262                         {
263                                 "cancel": self.exit,
264                                 "ok": self.okClicked,
265                                 "red": self.delete,
266                                 "green": self.add,
267                                 "yellow": self.edit,
268                                 "blue": self.save
269                         }, -1)
270                 
271                 self.onLayoutFinish.extend((
272                         self.updateServerList,
273                         self.layoutFinished,
274                 ))
275
276         def createSummary(self):
277                 return FTPServerManagerSummary
278
279         def layoutFinished(self):
280                 self.setTitle(_("FTP Server Manager"))
281
282         def updateServerList(self):
283                 list = [(server.name.value,) for server in config.plugins.ftpbrowser.server]
284                 self["list"].setList(list)
285
286         def exit(self, server=None):
287                 if self.changed:
288                         self.save(False)
289                 self.close(server)
290
291         def okClicked(self):
292                 idx = self["list"].index
293                 if idx is None:
294                         return
295
296                 ftpserverconfig = config.plugins.ftpbrowser
297                 Len = ftpserverconfig.servercount.value
298
299                 if Len and idx < Len:
300                         server = FTPServer(ftpserverconfig.server[idx])
301                         self.exit(server)
302
303         def delete(self):
304                 idx = self["list"].index
305                 if idx is None:
306                         return
307
308                 self.session.openWithCallback(
309                         self.deleteConfirm,
310                         MessageBox,
311                         _("Really delete this entry?\nIt cannot be recovered!")
312                 )
313
314         def deleteConfirm(self, ret):
315                 if not ret:
316                         return
317
318                 idx = self["list"].index
319                 ftpserverconfig = config.plugins.ftpbrowser
320                 Len = ftpserverconfig.servercount.value
321
322                 if Len and idx < Len:
323                         del ftpserverconfig.server[idx]
324                         ftpserverconfig.servercount.value -= 1
325                         self.updateServerList()
326                         self.changed = True
327
328         def add(self):
329                 newServer = ConfigSubsection()
330                 config.plugins.ftpbrowser.server.append(newServer)
331                 newServer.name = ConfigText("Name", fixed_size = False)
332                 newServer.address = ConfigText("192.168.2.12", fixed_size = False)
333                 newServer.username = ConfigText("root", fixed_size = False)
334                 newServer.password = ConfigPassword("dreambox")
335                 newServer.port = ConfigInteger(21, (1, 65535))
336                 newServer.passive = ConfigYesNo(False)
337                 config.plugins.ftpbrowser.servercount.value += 1
338                 config.plugins.ftpbrowser.servercount.save()
339
340                 self.updateServerList()
341                 self.changed = True
342
343         def edit(self):
344                 idx = self["list"].index
345                 ftpserverconfig = config.plugins.ftpbrowser
346                 Len = ftpserverconfig.servercount.value
347
348                 if idx is not None and Len and idx < Len:
349                         self.session.openWithCallback(
350                                 self.editCallback,
351                                 FTPServerEditor,
352                                 FTPServer(ftpserverconfig.server[idx])
353                         )
354
355         def editCallback(self, ret = False):
356                 if ret:
357                         self.updateServerList()
358                         self.changed = True
359
360         def save(self, showMessageBox=True):
361                 config.plugins.ftpbrowser.save()
362                 if showMessageBox:
363                         self.session.open(
364                                 MessageBox,
365                                 _("Configuration saved."),
366                                 type = MessageBox.TYPE_INFO
367                         )
368