initial version
[enigma2-plugins.git] / trafficinfo / src / plugin.py
1 # by 3c5x9@2007
2 from enigma import eTimer
3 from Screens.Screen import Screen
4 from Screens.InputBox import InputBox
5 from Screens.ChoiceBox import ChoiceBox
6 from Components.ActionMap import ActionMap
7 from Components.Label import Label
8 from Components.MenuList import MenuList
9 from Components.Input import Input
10
11 from Components.GUIComponent import GUIComponent
12 from Components.MultiContent import MultiContentEntryText
13 from enigma import eListboxPythonMultiContent, eListbox, gFont, RT_HALIGN_LEFT, RT_WRAP
14
15 from Plugins.Plugin import PluginDescriptor
16 import xml.dom.minidom
17
18 from twisted.web.client import getPage
19 from twisted.internet import reactor
20
21 ###############################################################################        
22 class TrafficInfoMain(Screen):
23     skin = """
24         <screen position="110,83" size="530,430" title="Verkehrsinfo" >
25                         
26             <widget name="sectionlist" position="0,0" size="530,130" scrollbarMode="showOnDemand" />            
27             <widget name="itemlist" position="0,130" size="530,130" scrollbarMode="showOnDemand" />            
28             <widget name="itemdetails" position="0,260" size="530,140" font="Regular;20" halign=\"center\" valign=\"center\"/>            
29             <widget name="statuslabel" position="0,400" size="530,30" halign=\"left\"/>           
30         </screen>
31         """
32     def __init__(self, session,args = 0):
33         self.loadinginprogress = False 
34         self.skin = TrafficInfoMain.skin
35         self.session = session
36         Screen.__init__(self, session)
37         self.menu = args
38         self["sectionlist"] = MenuList([])
39         self["itemlist"] = ItemList([])
40         self["statuslabel"] = Label("")
41         self["itemdetails"] = Label("")
42         self["actions"] = ActionMap(["ChannelSelectBaseActions","WizardActions", "DirectionActions","MenuActions","NumberActions"], 
43             {
44              "ok":                  self.go,
45              "back":            self.exit,
46              "nextBouquet":     self.selectSectionlist,
47              "prevBouquet":     self.selectItemlist,
48              "down":            self.down,
49              "up":                  self.up,
50              "left":            self.left,
51              "right":           self.right,
52              }, -1)
53         self.statuslabelcleartimer = eTimer()
54         self.statuslabelcleartimer.timeout.get().append(self.clearStatusLabel)
55         
56         self["itemlist"].onSelectionChanged.append(self.onItemSelected)
57         self.selectSectionlist()
58         
59         self.onShown.append(self.getSections)
60         
61     def exit(self):
62         if self.loadinginprogress:
63             reactor.callLater(1,self.exit)
64         else:
65             self.close()
66
67     def selectSectionlist(self):
68         self.currList = "sectionlist"
69         self["sectionlist"].selectionEnabled(1)
70         self["itemlist"].selectionEnabled(0)
71         
72     def selectItemlist(self):
73         self.currList = "itemlist"
74         self["sectionlist"].selectionEnabled(0)
75         self["itemlist"].selectionEnabled(1)
76         self["itemlist"].selectionChanged()
77         
78     def go(self):
79         if self.currList == "sectionlist":
80             self.onSectionSelected()
81
82     def up(self):
83         self[self.currList].up()
84     
85     def down(self):
86         self[self.currList].down()
87         
88     def left(self):
89         self[self.currList].pageUp()
90     
91     def right(self):
92         self[self.currList].pageDown()
93         
94     def onSectionSelected(self):
95         c = self["sectionlist"].getCurrent()
96         if c is not None:
97             self.setTitle("Verkehrsinfo: "+c[1].name)
98             self.getItemsOfSection(c[1])
99         
100     def onItemSelected(self):
101         if self["itemlist"].getCurrent() is not None:
102             c = self["itemlist"].getCurrent()[0]
103             if c is not None:
104                 self["itemdetails"].setText(c.text)
105             
106     ###########
107     def clearStatusLabel(self):
108         self["statuslabel"].setText("")
109         
110     def setStatusLabel(self,text):
111         self.statuslabelcleartimer.stop()         
112         self["statuslabel"].setText(text)
113         self.statuslabelcleartimer.start(3000)
114         
115     def getSections(self):
116         self.setStatusLabel("loading sections")
117         self.loadinginprogress = True    
118         getPage("http://wap.verkehrsinfo.de/wvindex.php3").addCallback(self.sectionsLoaded).addErrback(self.sectionsLoadingFaild)
119     
120     def sectionsLoadingFaild(self,raw):
121         self.loadinginprogress = False
122         self.setStatusLabel("loading sections failed"+raw)
123         
124     def sectionsLoaded(self,raw):
125         self.loadinginprogress = False
126         try:
127             xmldoc = xml.dom.minidom.parseString( raw)
128             self.sections = []
129             for i in xmldoc.getElementsByTagName("a"):
130                 link = "/"+i.getAttribute("href")
131                 name = i.toxml().split(">")[1].split("<")[0]
132                 self.sections.append(TrafficInfoSection(name,link))
133             self.onSectionsLoaded()
134         except xml.parsers.expat.ExpatError,e:
135             print e
136             print raw
137             self.setStatusLabel("loading sections failed")
138
139     def onSectionsLoaded(self):
140         self.setStatusLabel("sections loaded")
141         list = []
142         for i in self.sections:
143             if i.name.startswith("BRD") is not True:
144                 list.append((i.name,i))
145         list.sort()
146         self["sectionlist"].l.setList(list)
147         self["sectionlist"].instance.moveSelectionTo(0)
148
149     def onItemsLoaded(self):
150         list=[]
151         for item in self.trafficitems:
152             res = [ item ]
153             res.append(MultiContentEntryText(pos=(0, 0), size=(75, 20), font=0, flags = RT_HALIGN_LEFT|RT_WRAP, text = item.street))
154             res.append(MultiContentEntryText(pos=(75,0), size=(455, 20), font=1, flags = RT_HALIGN_LEFT, text = item.direction))
155             list.append(res)
156         self["itemlist"].l.setList(list)
157         self["itemlist"].instance.moveSelectionTo(0)
158         self.setStatusLabel("messages loaded")
159
160     ##########
161     def getItemsOfSection(self,section):
162         print "loading section",section.name  ,section.link
163         self.setStatusLabel("loading messages "+section.name)
164         self.loadinginprogress = True    
165         getPage("http://wap.verkehrsinfo.de"+section.link).addCallback(self.trafficitemsLoaded).addErrback(self.trafficitemsLoadingFaild)
166
167     def trafficitemsLoadingFaild(self,raw):
168         self.loadinginprogress = False
169         print "loading items faild",raw
170         self.setStatusLabel("loading messages faild"+raw)
171         
172     def trafficitemsLoaded(self,raw):
173         self.loadinginprogress = False
174         try:
175             raw = raw.replace("&amp","")
176             xmldoc = xml.dom.minidom.parseString( raw)
177             self.trafficitems = []
178             for item in  xmldoc.getElementsByTagName("p"):
179                 self.trafficitems.append(self.parseItem(item))
180             self.onItemsLoaded()
181         except xml.parsers.expat.ExpatError,e:
182             print e
183             print raw
184             self.setStatusLabel("loading messages faild! Parsing Error")
185         
186     def parseItem(self,item):
187         source=item.toxml()
188         i= item.getElementsByTagName("b")
189         source=source.replace(i[0].toxml(),"")
190         street = i[0].toxml().replace("<b>","").replace("</b>","").replace("\n","")
191         
192         source=source.replace(i[1].toxml(),"")
193         direction = i[1].toxml().replace("<b>","").replace("</b>","").replace("\n","")
194         details = source.replace("<p>","").replace("</p>","").replace("<small>","").replace("</small>","").replace("<br/>","").replace("\n","")
195         if street == "<b/>":
196             street = "Info"
197         return TrafficInfoItem(street,direction,details)
198
199 class ItemList(MenuList):
200     def __init__(self, items):
201         MenuList.__init__(self,items)
202         self.l = eListboxPythonMultiContent()
203         self.l.setFont(0, gFont("Regular", 20))
204         self.l.setFont(1, gFont("Regular", 18))
205     GUI_WIDGET = eListbox
206
207     def getCurrentEntry(self):
208         return self.l.getCurrentSelection()
209
210 ####################
211 class TrafficInfoSection:
212     def __init__(self, name,link):
213         self.name = name.encode("utf-8")
214         self.link = link.encode("utf-8")
215
216     def __str__(self):
217         return "name="+self.name+", link="+self.link
218
219 ####################
220 class TrafficInfoItem:
221     def __init__(self, street,direction,text):
222         self.street = street.encode("utf-8")
223         self.direction = direction.encode("utf-8")
224         self.text = text.encode("utf-8")
225
226     def __str__(self):
227         return "street="+self.street+", dir="+self.direction+", text="+self.text
228
229 #############################
230 def main(session, **kwargs):
231     session.open(TrafficInfoMain)
232
233 def Plugins(**kwargs):
234   return PluginDescriptor(name="Verkehrsinfo",description="view german traffic jam informations",where = PluginDescriptor.WHERE_PLUGINMENU,fnc = main)
235