cleanup
[enigma2-plugins.git] / unwetterzentrale / src / plugin.py
1 # -*- coding: utf-8 -*-
2 #
3 # Wetter Infos von
4 # www.unwetterzentrale.de und www.uwz.at
5 #
6 # Author: barabas
7 #
8
9 import xml.sax.saxutils as util
10
11 from Plugins.Plugin import PluginDescriptor
12 from twisted.web.client import getPage
13 from twisted.internet import reactor
14 from Screens.Screen import Screen
15 from Screens.Console import Console
16 from Components.ActionMap import ActionMap
17 from Components.Label import Label
18 from Components.MenuList import MenuList
19 from Components.AVSwitch import AVSwitch
20 from Components.Pixmap import Pixmap
21 from enigma import eTimer, ePicLoad
22 from re import sub, search, findall
23 from os import unlink
24
25 ###############################################################################
26
27 class PictureView(Screen):
28         skin = """
29                 <screen position="0,0" size="720,576" flags="wfNoBorder" title="UWZ" >
30                         <eLabel position="0,0" zPosition="1" size="720,576" backgroundColor="black" />
31                         <ePixmap position="635,540" zPosition="2" size="36,20" pixmap="skin_default/buttons/key_info.png" alphatest="on" />
32                         <widget name="picture" position="80,10" zPosition="2" size="550,550" />
33                 </screen>"""
34
35         def __init__(self, session):
36                 self.skin = PictureView.skin
37                 Screen.__init__(self, session)
38
39                 self.picfile = "/tmp/uwz.png"
40
41                 self["picture"] = Pixmap()
42
43                 self["actions"] = ActionMap(["OkCancelActions","MovieSelectionActions"],
44                 {
45                         "cancel": self.exit,
46                         "ok": self.exit,
47                         "showEventInfo": self.HelpView,
48                 }, -1)
49
50                 self.picload = ePicLoad()
51                 sc = AVSwitch().getFramebufferScale()
52                 self.picload.setPara((550, 550, sc[0], sc[1], 0, 0, '#ff000000'))
53                 self.picload.PictureData.get().append(self.gotPic)
54                 self.onLayoutFinish.append(self.getPic)
55
56         def getPic(self):
57                 self.picload.startDecode(self.picfile)
58
59         def gotPic(self, picInfo = None):
60                 ptr = self.picload.getData()
61                 if ptr:
62                         self["picture"].instance.setPixmap(ptr.__deref__())
63
64         def HelpView(self):
65                 self.session.openWithCallback(self.getPic, HelpPictureView)
66
67         def exit(self):
68                 self.close()
69
70 class HelpPictureView(Screen):
71         skin = """
72                 <screen position="25,200" size="670,290" title="Warnstufen" >
73                         <eLabel position="0,0" zPosition="1" size="670,290" backgroundColor="black" />
74                         <ePixmap position="320,260" zPosition="2" size="36,20" pixmap="skin_default/arrowdown.png" alphatest="on" />
75                         <widget name="picture" position="-10,20" zPosition="2" size="690,225" />
76                 </screen>"""
77
78         def __init__(self, session):
79                 self.skin = HelpPictureView.skin
80                 Screen.__init__(self, session)
81
82                 self["picture"] = Pixmap()
83
84                 self["actions"] = ActionMap(["OkCancelActions", "DirectionActions"],
85                 {
86                         "cancel": self.exit,
87                         "ok": self.exit,
88                         "left": self.prevPic,
89                         "right": self.nextPic
90                 }, -1)
91
92                 self.list = (
93                         pluginpath + "/W_gruen.gif",
94                         pluginpath + "/W_gelb.gif",
95                         pluginpath + "/W_orange.gif",
96                         pluginpath + "/W_rot.gif",
97                         pluginpath + "/W_violett.gif"
98                 )
99                 self.index = 0
100
101                 self.picload = ePicLoad()
102                 sc = AVSwitch().getFramebufferScale()
103                 self.picload.setPara((690, 225, sc[0], sc[1], 0, 0, '#ff000000'))
104                 self.picload.PictureData.get().append(self.gotPic)
105
106                 self.onShown.append(self.getPic)
107
108         def getPic(self):
109                 self.picload.startDecode(self.list[self.index])
110
111         def gotPic(self, picInfo = None):
112                 ptr = self.picload.getData()
113                 if ptr:
114                         self["picture"].instance.setPixmap(ptr.__deref__())
115
116         def nextPic(self):
117                 self.index += 1
118                 if self.index > 4:
119                         self.index = 0
120                 self.getPic()
121
122         def prevPic(self):
123                 self.index -= 1
124                 if self.index < 0:
125                         self.index = 4
126                 self.getPic()
127
128         def exit(self):
129                 self.close()
130
131 class UnwetterMain(Screen):
132         skin = """
133                 <screen position="110,83" size="530,430" title="Unwetterzentrale" >
134                         <widget name="hmenu" position="5,0" zPosition="1" size="530,220" scrollbarMode="showOnDemand" />
135                         <widget name="thumbnail" position="185,250" zPosition="2" size="140,150" />
136                         <widget name="thumbland" position="435,390" zPosition="2" size="90,40" />
137                         <ePixmap position="20,380" zPosition="2" size="36,20" pixmap="skin_default/buttons/key_menu.png" alphatest="on" />
138                         <widget name="statuslabel" position="5,410" zPosition="2" size="530,20" font="Regular;16" halign="left"/>
139                 </screen>"""
140
141         def __init__(self, session):
142                 self.loadinginprogress = False
143                 self.skin = UnwetterMain.skin
144                 self.session = session
145                 Screen.__init__(self, session)
146
147                 self["statuslabel"] = Label()
148                 self["thumbland"] = Pixmap()
149                 self["thumbnail"] = Pixmap()
150                 self["hmenu"] = MenuList([])
151                 self["actions"] = ActionMap(["OkCancelActions", "DirectionActions", "MovieSelectionActions"],
152                 {
153                         "ok":   self.ok,
154                         "up": self.up,
155                         "right": self.rightDown,
156                         "left": self.leftUp,
157                         "down": self.down,
158                         "cancel": self.exit,
159                         "contextMenu": self.switchDeA,
160                 }, -1)
161
162                 self.menueintrag = []
163                 self.link = []
164                 self.picfile = "/tmp/uwz.png"
165                 self.picweatherfile = pluginpath + "/wetterreport.jpg"
166                 self.reportfile = "/tmp/uwz.report"
167
168                 try:
169                         f = open(pluginpath + "/last.cfg","r")
170                         self.land = f.read()
171                         f.close
172                 except:
173                         self.land = "de"
174
175                 if self.land == "de":
176                         self.baseurl = "http://www.unwetterzentrale.de/uwz/"
177                         self.menuurl = self.baseurl + "index.html"
178                         self.weatherreporturl = self.baseurl + "lagebericht.html"
179                 else:
180                         self.baseurl = "http://www.uwz.at/"
181                         self.menuurl = self.baseurl + "index.php"
182                         self.weatherreporturl = self.baseurl + "lagebericht.php"
183
184                 self.downloadMenu()
185
186                 self.picload = ePicLoad()
187
188 #               self.onLayoutFinish.append(self.go)
189
190                 self.ThumbTimer = eTimer()
191                 self.ThumbTimer.callback.append(self.showThumb)
192                 self.ThumbTimer.start(1000, True)
193
194         def hauptmenu(self,output):
195                 self.loadinginprogress = False
196                 trans = { '&szlig;' : '' , '&auml;' : '' , '&ouml;' : '' , '&uuml;' : '' , '&Auml;' : '', '&Ouml;' : '' , '&Uuml;' : ''}
197                 output= util.unescape(output,trans)
198
199                 if self.land == "de":
200                         startpos = output.find('<!-- Anfang Navigation -->')
201                         endpos = output.find('<!-- Ende Navigation -->')
202                         bereich = output[startpos:endpos]
203                         a = findall(r'href=(?P<text>.*?)</a>',bereich)
204                         for x in a[1:16]:
205                                 x = x.replace('">',"#").replace('"',"").split('#')
206                                 if not len(x) > 1:
207                                         break
208                                 name = x[1]
209                                 link = self.baseurl + x[0]
210                                 self.menueintrag.append(name)
211                                 self.link.append(link)
212                 else:
213                         startpos = output.find('<div id="mainWindow">')
214                         endpos = output.find('<a class="menua" href="http://www.austrowetter.at"')
215                         bereich = output[startpos:endpos]
216                         a = findall(r'<a class="menub" href=(?P<text>.*?)</a>',bereich)
217                         for x in a[1:13]:
218                                 x = x.replace('">',"#").replace('"',"").replace(' style=font-weight:;',"")
219                                 if x != '#&nbsp;':
220                                                 x = x.split('#')
221                                                 if not len(x) > 1:
222                                                         break
223                                                 name = x[1]
224                                                 link = self.baseurl + x[0]
225                                                 self.menueintrag.append(name)
226                                                 self.link.append(link)
227
228                 self["statuslabel"].setText("")
229                 self["hmenu"].l.setList(self.menueintrag)
230                 self["hmenu"].instance.moveSelectionTo(0)
231                 self.showThumbLand()
232
233         def ok(self):
234                 self.go()
235                 c = self["hmenu"].getCurrent()
236                 if c is not None:
237                         x = self.menueintrag.index(c)
238                         if x != 0:
239                                 self.session.open(PictureView)
240                         else:
241                                 self.downloadWeatherReport()
242
243         def go(self):
244                 c = self["hmenu"].getCurrent()
245                 if c is not None:
246                         x = self.menueintrag.index(c)
247                         # Wetterlagebericht ist Index 0
248                         if x != 0:
249                                 url = self.link[x]
250                                 self["statuslabel"].setText("Loading Data")
251                                 self.downloadPicUrl(url)
252                         self.ThumbTimer.start(1500, True)
253
254         def up(self):
255                 self["hmenu"].up()
256                 self.go()
257
258         def down(self):
259                 self["hmenu"].down()
260                 self.go()
261
262         def leftUp(self):
263                 self["hmenu"].pageUp()
264                 self.go()
265
266         def rightDown(self):
267                 self["hmenu"].pageDown()
268                 self.go()
269
270         def showThumbLand(self):
271                 picture = ""
272                 if self.land == "de":
273                         picture = pluginpath + "/uwz.png"
274                 else:
275                         picture = pluginpath + "/uwzat.png"
276                 picload = self.picload
277                 sc = AVSwitch().getFramebufferScale()
278                 picload.setPara((90, 40, sc[0], sc[1], 0, 0, '#ff000000'))
279                 l = picload.PictureData.get()
280                 del l[:]
281                 l.append(self.gotThumbLand)
282                 picload.startDecode(picture)
283
284         def gotThumbLand(self, picInfo = None):
285                 ptr = self.picload.getData()
286                 if ptr:
287                         self["thumbland"].instance.setPixmap(ptr.__deref__())
288
289         def showThumb(self):
290                 picture = ""
291                 if self.land == "de":
292                         width = 142
293                         height = 150
294                 else:
295                         width = 142
296                         height = 135
297                 c = self["hmenu"].getCurrent()
298                 if c is not None:
299                         x = self.menueintrag.index(c)
300                         if x != 0:
301                                 picture = self.picfile
302                         else:
303                                 picture = self.picweatherfile
304                                 height = 150
305
306                         picload = self.picload
307                         sc = AVSwitch().getFramebufferScale()
308                         picload.setPara((width, height, sc[0], sc[1], 0, 0, '#ff000000'))
309                         l = picload.PictureData.get()
310                         del l[:]
311                         l.append(self.gotThumb)
312                         picload.startDecode(picture)
313
314         def gotThumb(self, picInfo = None):
315                 ptr = self.picload.getData()
316                 if ptr:
317                         self["statuslabel"].setText("")
318                         self["thumbnail"].show()
319                         self["thumbnail"].instance.setPixmap(ptr.__deref__())
320                 else:
321                         self["thumbnail"].hide()
322
323         def getPicUrl(self,output):
324                 self.loadinginprogress = False
325                 if self.land == "de":
326                         startpos = output.find('<!-- Anfang msg_Box Content -->')
327                         endpos = output.find('<!-- Ende msg_Box Content -->')
328                         bereich = output[startpos:endpos]
329                         picurl = search(r'<img src="(?P<text>.*?)" width=',bereich)
330                         picurl = self.baseurl + picurl.group(1)
331                 else:
332                         picurl = search(r'<img src="showMap(?P<text>.*?)" alt=',output)
333                         picurl = self.baseurl + "showMap" + picurl.group(1).replace('&amp;','&')
334                 self.downloadPic(picurl)
335
336         def getPic(self,output):
337                 self.loadinginprogress = False
338                 f = open(self.picfile, "wb")
339                 f.write(output)
340                 f.close()
341
342         def getWeatherReport(self,output):
343                 self.loadinginprogress = False
344                 if self.land == "de":
345                         trans = { '&szlig;' : '' , '&auml;' : '' , '&ouml;' : '' , '&uuml;' : '' , '&Auml;' : '', '&Ouml;' : '' , '&Uuml;' : ''}
346                         output= util.unescape(output,trans)
347                         startpos = output.find('<!-- Anfang msg_Box Content -->')
348                         endpos = output.find('<!-- Ende msg_Box Content -->')
349                         bereich = output[startpos:endpos]
350                 else:
351                         startpos = output.find('<div class="content">')
352                         endpos = output.find('<div class="rs_title">Unwettermeldungen</div>')
353                         bereich = output[startpos:endpos]
354                         u_bereich = bereich.decode("iso-8859-1")
355                         bereich = u_bereich.encode("utf-8")
356                         bereich = sub('<br />',"\n",bereich)
357
358                 bereich = sub('<[^>]*>',"",bereich)
359                 bereich = sub('Fronten- und Isobarenkarte.*',"",bereich)
360                 bereich = bereich.strip()
361                 bereich = sub("\n\s*\n*", "\n\n", bereich)
362
363                 f = open(self.reportfile, "w")
364                 f.write("%s" % bereich)
365                 f.close
366                 self.session.open(Console,_("Warnlagebericht"),["cat %s" % self.reportfile])
367
368         def downloadError(self,output):
369                 self.loadinginprogress = False
370                 self["statuslabel"].setText("Fehler beim Download")
371
372         def downloadMenu(self):
373                 self.loadinginprogress = True
374                 getPage(self.menuurl).addCallback(self.hauptmenu).addErrback(self.downloadError)
375
376         def downloadPicUrl(self,url):
377                 self.loadinginprogress = True
378                 getPage(url).addCallback(self.getPicUrl).addErrback(self.downloadError)
379
380         def downloadPic(self,picurl):
381                 self.loadinginprogress = True
382 #               self["statuslabel"].setText("Lade Bild: %s" % picurl)
383                 getPage(picurl).addCallback(self.getPic).addErrback(self.downloadError)
384
385         def downloadWeatherReport(self):
386                 self.loadinginprogress = True
387 #               self["statuslabel"].setText("Lade Report: %s" % self.weatherreporturl)
388                 getPage(self.weatherreporturl).addCallback(self.getWeatherReport).addErrback(self.downloadError)
389
390         def switchDeA(self):
391                 self.menueintrag = []
392                 self.link = []
393                 if self.land == "de":
394                         self.land = "a"
395                         self.baseurl = "http://www.uwz.at/"
396                         self.menuurl = self.baseurl + "index.php"
397                         self.weatherreporturl = self.baseurl + "lagebericht.php"
398                 else:
399                         self.land = "de"
400                         self.baseurl = "http://www.unwetterzentrale.de/uwz/"
401                         self.menuurl = self.baseurl + "index.html"
402                         self.weatherreporturl = self.baseurl + "lagebericht.html"
403
404                 f = open(pluginpath + "/last.cfg","w")
405                 f.write(self.land)
406                 f.close
407                 self.downloadMenu()
408                 self.ThumbTimer.start(1500, True)
409
410         def exit(self):
411                 if self.loadinginprogress:
412                         reactor.callLater(1,self.exit)
413                 else:
414                         try:
415                                 unlink(self.picfile)
416                                 unlink(self.reportfile)
417                         except OSError:
418                                 pass
419                         self.close()
420
421 #############################
422
423 def main(session, **kwargs):
424         session.open(UnwetterMain)
425
426 def Plugins(path,**kwargs):
427         global pluginpath
428         pluginpath = path
429         return PluginDescriptor(
430                 name="Unwetterzentrale",
431                 description="www.unwetterzentrale.de und www.uwz.at",
432                 icon="uwz.png",
433                 where = PluginDescriptor.WHERE_PLUGINMENU,
434                 fnc=main)