0990fc1fc4dc78fa67f708fcaf4979f29c490b9c
[pywienerlinien] / gotovienna / realtime.py
1 # -*- coding: utf-8 -*-
2
3 from gotovienna.BeautifulSoup import BeautifulSoup
4 from urllib2 import urlopen
5 from datetime import time
6 import re
7 import collections
8 from errors import LineNotFoundError, StationNotFoundError
9
10 from gotovienna import defaults
11
12 class Departure:
13     def __init__(self, line, station, direction, time, lowfloor):
14         self.line = line
15         self.station = station
16         self.direction = direction
17         self.time = time
18         self.lowfloor = lowfloor
19
20     def get_departure_time(self):
21         """ return time object of departure time
22         """
23         if type(self.time) == time:
24             return self.time
25         else:
26             pass
27     def get_departure_deltatime(self):
28         """ return int representing minutes until departure
29         """
30         if type(self.time) == int:
31             return self.time
32         else:
33             pass
34
35     def get_ftime(self):
36         if type(self.time) == int:
37             return str(self.time)
38         elif type(self.time) == time:
39             return self.time.strftime('%H:%M')
40
41 class ITipParser:
42     def __init__(self):
43         self._stations = {}
44         self._lines = {}
45
46     def get_stations(self, name):
47         """ Get station by direction
48         {'Directionname': [('Station name', 'url')]}
49         """
50         if not self._stations.has_key(name):
51             st = {}
52
53             if not self.lines.has_key(name):
54                 return None
55
56             bs = BeautifulSoup(urlopen(self.lines[name]))
57             tables = bs.findAll('table', {'class': 'text_10pix'})
58             for i in range(2):
59                 dir = tables[i].div.contents[-1].strip()[6:-6]
60
61                 sta = []
62                 for tr in tables[i].findAll('tr', {'onmouseout': 'obj_unhighlight(this);'}):
63                     if tr.a:
64                         sta.append((tr.a.text, defaults.line_overview + tr.a['href']))
65                     else:
66                         sta.append((tr.text.strip(' '), None))
67
68                 st[dir] = sta
69             self._stations[name] = st
70
71         return self._stations[name]
72
73     @property
74     def lines(self):
75         """ Dictionary of Line names with url as value
76         """
77         if not self._lines:
78             bs = BeautifulSoup(urlopen(defaults.line_overview))
79             # get tables
80             lines = bs.findAll('td', {'class': 'linie'})
81
82             for line in lines:
83                 if line.a:
84                     href = defaults.line_overview + line.a['href']
85                     if line.text:
86                         self._lines[line.text] = href
87                     elif line.img:
88                         self._lines[line.img['alt']] = href
89
90         return self._lines
91
92     def get_url_from_direction(self, line, direction, station):
93         stations = self.get_stations(line)
94
95         for stationname, url in stations.get(direction, []):
96             if stationname == station:
97                 return url
98
99         return None
100
101     def get_departures(self, url):
102         """ Get list of next departures as Departure object
103         """
104
105         #TODO parse line name and direction for station site parsing
106
107         if not url:
108             # FIXME prevent from calling this method with None
109             print "ERROR empty url"
110             return []
111
112         # open url for 90 min timeslot / get departure for next 90 min
113         bs = BeautifulSoup(urlopen(url + "&departureSizeTimeSlot=90"))
114         print url
115         lines = bs.findAll('table')[-2].findAll('tr')
116         if len(lines) == 1:
117             station = lines[0].span.text.replace(' ', '')
118             line = lines[0].findAll('span')[-1].text.replace(' ', '')
119         else:
120             station = lines[1].td.span.text.replace(' ', '')
121             line = '??'
122
123         result_lines = bs.findAll('table')[-1].findAll('tr')
124
125         dep = []
126         for tr in result_lines[1:]:
127             d = {'station': station}
128             th = tr.findAll('th')
129             if len(th) < 2:
130                 #TODO replace with logger
131                 print "[DEBUG] Unable to find th in:\n%s" % str(tr)
132             elif len(th) == 2:
133                 # underground site looks different -.-
134                 d['lowfloor'] = True
135                 d['line'] = line
136                 d['direction'] = th[0].text.replace('&nbsp;', '')
137                 t = th[-1]
138             else:
139                 # all other lines
140                 d['lowfloor'] = th[-1].has_key('img') and th[-1].img.has_key('alt')
141                 d['line'] = th[0].text.replace('&nbsp;', '')
142                 d['direction'] = th[1].text.replace('&nbsp;', '')
143                 t = th[-2]
144             # parse time
145             tim = t.text.split(' ')
146             if len(tim) < 2:
147                 # print '[WARNING] Invalid time: %s' % time
148                 # TODO: Issue a warning OR convert "HH:MM" format to countdown
149                 tim = tim[0]
150             else:
151                 tim = tim[1]
152
153             if tim.find('rze...') >= 0:
154                     d['time'] = 0
155             elif tim.isdigit():
156                 # if time to next departure in cell convert to int
157                 d['time'] = int(tim)
158             else:
159                 # check if time of next departue in cell
160                 t = tim.strip('&nbsp;').split(':')
161                 if len(t) == 2 and all(map(lambda x: x.isdigit(), t)):
162                     t = map(int, t)
163                     d['time'] = time(*t)
164                 else:
165                     # Unexpected content
166                     #TODO replace with logger
167                     print "[DEBUG] Invalid data:\n%s" % time
168
169             print d
170             dep.append(Departure(**d))
171
172         return dep
173
174
175 UBAHN, TRAM, BUS, NIGHTLINE, OTHER = range(5)
176 LINE_TYPE_NAMES = ['U-Bahn', 'Strassenbahn', 'Bus', 'Nightline', 'Andere']
177
178 def get_line_sort_key(name):
179     """Return a sort key for a line name
180
181     >>> get_line_sort_key('U6')
182     ('U', 6)
183
184     >>> get_line_sort_key('D')
185     ('D', 0)
186
187     >>> get_line_sort_key('59A')
188     ('A', 59)
189     """
190     txt = ''.join(x for x in name if not x.isdigit())
191     num = ''.join(x for x in name if x.isdigit()) or '0'
192
193     return (txt, int(num))
194
195 def get_line_type(name):
196     """Get the type of line for the given name
197
198     >>> get_line_type('U1')
199     UBAHN
200     >>> get_line_type('59A')
201     BUS
202     """
203     if name.isdigit():
204         return TRAM
205     elif name.endswith('A') or name.endswith('B') and name[1].isdigit():
206         return BUS
207     elif name.startswith('U'):
208         return UBAHN
209     elif name.startswith('N'):
210         return NIGHTLINE
211     elif name in ('D', 'O', 'VRT', 'WLB'):
212         return TRAM
213
214     return OTHER
215
216 def categorize_lines(lines):
217     """Return a categorized version of a list of line names
218
219     >>> categorize_lines(['U4', 'U3', '59A'])
220     [('U-Bahn', ['U3', 'U4']), ('Bus', ['59A'])]
221     """
222     categorized_lines = collections.defaultdict(list)
223
224     for line in sorted(lines):
225         line_type = get_line_type(line)
226         categorized_lines[line_type].append(line)
227
228     for lines in categorized_lines.values():
229         lines.sort(key=get_line_sort_key)
230
231     return [(LINE_TYPE_NAMES[key], categorized_lines[key])
232             for key in sorted(categorized_lines)]
233
234
235 class Line:
236     def __init__(self, name):
237         self._stations = None
238         self.parser = ITipParser()
239         if name.strip() in self.parser.lines():
240             self.name = name.strip()
241         else:
242             raise LineNotFoundError('There is no line "%s"' % name.strip())
243
244     @property
245     def stations(self):
246         if not self._stations:
247             self._stations = parser.get_stations(self.name)
248         return self._stations
249
250     def get_departures(self, stationname):
251         stationname = stationname.strip().lower()
252         stations = self.stations
253
254         found = false
255
256         for direction in stations.keys():
257             # filter stations starting with stationname
258             stations[direction] = filter(lambda station: station[0].lower().starts_with(stationname), stations)
259             found = found or bool(stations[direction])
260
261         if found:
262             # TODO return departures
263             raise NotImplementedError()
264         else:
265             raise StationNotFoundError('There is no stationname called "%s" at route of line "%s"' % (stationname, self.name))