1 # -*- coding: utf-8 -*-
3 from gotovienna.BeautifulSoup import BeautifulSoup
4 from urllib2 import urlopen
5 from datetime import time
8 from errors import LineNotFoundError, StationNotFoundError
10 from cache import Stations
12 from gotovienna import defaults
15 def __init__(self, line, station, direction, time, lowfloor):
17 self.station = station
18 self.direction = direction
20 self.lowfloor = lowfloor
22 def get_departure_time(self):
23 """ return time object of departure time
25 if type(self.time) == time:
29 def get_departure_deltatime(self):
30 """ return int representing minutes until departure
32 if type(self.time) == int:
38 if type(self.time) == int:
40 elif type(self.time) == time:
41 return self.time.strftime('%H:%M')
45 self._lines = cache.lines
47 def get_stations(self, name):
48 """ Get station by direction
49 {'Directionname': [('Station name', 'url')]}
51 if not name in self.lines:
57 bs = BeautifulSoup(urlopen(self.lines[name]))
58 tables = bs.findAll('table', {'class': 'text_10pix'})
60 dir = tables[i].div.contents[-1].strip()[6:-6]
63 for tr in tables[i].findAll('tr', {'onmouseout': 'obj_unhighlight(this);'}):
65 sta.append((tr.a.text, defaults.line_overview + tr.a['href']))
67 sta.append((tr.text.strip(' '), None))
75 """ Dictionary of Line names with url as value
78 bs = BeautifulSoup(urlopen(defaults.line_overview))
80 lines = bs.findAll('td', {'class': 'linie'})
84 href = defaults.line_overview + line.a['href']
86 self._lines[line.text] = href
88 self._lines[line.img['alt']] = href
92 def get_url_from_direction(self, line, direction, station):
93 stations = self.get_stations(line)
95 for stationname, url in stations.get(direction, []):
96 if stationname == station:
101 def get_departures(self, url):
102 """ Get list of next departures as Departure object
105 #TODO parse line name and direction for station site parsing
108 # FIXME prevent from calling this method with None
109 print "ERROR empty url"
112 # open url for 90 min timeslot / get departure for next 90 min
116 bs = BeautifulSoup(urlopen(url + "&departureSizeTimeSlot=90"))
118 lines = bs.find('form', {'name': 'mainform'}).table.findAll('tr')[1]
119 except AttributeError:
121 msg = bs.findAll('span', {'class': 'rot fett'})
122 if len(msg) > 0 and str(msg[0].text).find(u'technischen St') > 0:
123 print 'Temporary problem'
124 print '\n'.join(map(lambda x: x.text.replace(' ', ''), msg))
125 # FIXME Change to error message after fixing qml gui
131 if len(lines.findAll('td', {'class': 'info'})) > 0:
132 station = lines.span.text.replace(' ', '')
133 line = lines.findAll('span')[-1].text.replace(' ', '')
135 station = lines.td.span.text.replace(' ', '')
136 line = lines.find('td', {'align': 'right'}).span.text.replace(' ', '')
138 result_lines = bs.findAll('table')[-1].findAll('tr')
141 for tr in result_lines[1:]:
142 d = {'station': station}
143 th = tr.findAll('th')
145 #TODO replace with logger
146 print "[DEBUG] Unable to find th in:\n%s" % str(tr)
148 # underground site looks different -.-
151 d['direction'] = th[0].text.replace(' ', '')
155 d['lowfloor'] = th[-1].has_key('img') and th[-1].img.has_key('alt')
156 d['line'] = th[0].text.replace(' ', '')
157 d['direction'] = th[1].text.replace(' ', '')
160 tim = t.text.split(' ')
162 # print '[WARNING] Invalid time: %s' % time
163 # TODO: Issue a warning OR convert "HH:MM" format to countdown
168 if tim.find('rze...') >= 0:
171 # if time to next departure in cell convert to int
174 # check if time of next departue in cell
175 t = tim.strip(' ').split(':')
176 if len(t) == 2 and all(map(lambda x: x.isdigit(), t)):
181 #TODO replace with logger
182 print "[DEBUG] Invalid data:\n%s" % time
185 dep.append(Departure(**d))
190 UBAHN, TRAM, BUS, NIGHTLINE, OTHER = range(5)
191 LINE_TYPE_NAMES = ['U-Bahn', 'Strassenbahn', 'Bus', 'Nightline', 'Andere']
193 def get_line_sort_key(name):
194 """Return a sort key for a line name
196 >>> get_line_sort_key('U6')
199 >>> get_line_sort_key('D')
202 >>> get_line_sort_key('59A')
205 txt = ''.join(x for x in name if not x.isdigit())
206 num = ''.join(x for x in name if x.isdigit()) or '0'
208 return (txt, int(num))
210 def get_line_type(name):
211 """Get the type of line for the given name
213 >>> get_line_type('U1')
215 >>> get_line_type('59A')
220 elif name.endswith('A') or name.endswith('B') and name[1].isdigit():
222 elif name.startswith('U'):
224 elif name.startswith('N'):
226 elif name in ('D', 'O', 'VRT', 'WLB'):
231 def categorize_lines(lines):
232 """Return a categorized version of a list of line names
234 >>> categorize_lines(['U4', 'U3', '59A'])
235 [('U-Bahn', ['U3', 'U4']), ('Bus', ['59A'])]
237 categorized_lines = collections.defaultdict(list)
239 for line in sorted(lines):
240 line_type = get_line_type(line)
241 categorized_lines[line_type].append(line)
243 for lines in categorized_lines.values():
244 lines.sort(key=get_line_sort_key)
246 return [(LINE_TYPE_NAMES[key], categorized_lines[key])
247 for key in sorted(categorized_lines)]