2 # -*- coding: UTF-8 -*-
4 from BeautifulSoup import BeautifulSoup, NavigableString
5 from urllib2 import urlopen
6 from urllib import urlencode
7 from datetime import datetime, time, timedelta
8 from textwrap import wrap
14 from gotovienna import defaults
16 POSITION_TYPES = ('stop', 'address', 'poi')
18 DEBUGLOG = os.path.expanduser('~/gotoVienna.debug')
20 class ParserError(Exception):
22 def __init__(self, msg='Parser error'):
26 UNKNOWN, CORRECTION, RESULT = range(3)
29 def extract_city(station):
30 """ Extract city from string if present,
31 else return default city
33 >>> extract_city('Karlsplatz, Wien')
36 if len(station.split(',')) > 1:
37 return station.split(',')[-1].strip()
41 def extract_station(station):
42 """ Remove city from string
44 >>> extract_station('Karlsplatz, Wien')
47 if len(station.split(',')) > 1:
48 return station[:station.rindex(',')].strip()
52 def split_station(station):
53 """ >>> split_station('Karlsplatz, Wien')
54 ('Karlsplatz', 'Wien')
55 >>> split_station('Karlsplatz')
56 ('Karlsplatz', 'Wien')
58 if len(station.split(',')) > 1:
59 return (station[:station.rindex(',')].strip(), station.split(',')[-1].strip())
61 return (station, 'Wien')
63 def guess_location_type(location):
64 """Guess type (stop, address, poi) of a location
66 >>> guess_location_type('pilgramgasse')
69 >>> guess_location_type('karlsplatz 14')
72 >>> guess_location_type('reumannplatz 12/34')
75 parts = location.split()
79 # Assume all single-word locations are stops
83 # If the last part is numeric, assume address
84 if last_part.isdigit() and len(parts) > 1:
87 # Addresses with door number (e.g. "12/34")
88 if all(x.isdigit() or x == '/' for x in last_part):
91 # Sane default - assume it's a stop/station name
94 def search(origin_tuple, destination_tuple, dtime=None):
95 """ build route request
96 returns html result (as urllib response)
99 dtime = datetime.now()
101 origin, origin_type = origin_tuple
102 origin, origin_city = split_station(origin)
104 destination, destination_type = destination_tuple
105 destination, destination_city = split_station(destination)
108 if origin_type is None:
109 origin_type = guess_location_type(origin)
110 print 'Guessed origin type:', origin_type
112 if destination_type is None:
113 destination_type = guess_location_type(destination)
114 print 'Guessed destination type:', destination_type
116 if (origin_type not in POSITION_TYPES or
117 destination_type not in POSITION_TYPES):
118 raise ParserError('Invalid position type')
120 post = defaults.search_post
121 post['name_origin'] = origin
122 post['type_origin'] = origin_type
123 post['name_destination'] = destination
124 post['type_destination'] = destination_type
125 post['itdDateDayMonthYear'] = dtime.strftime('%d.%m.%Y')
126 post['itdTime'] = dtime.strftime('%H:%M')
127 post['place_origin'] = origin_city
128 post['place_destination'] = destination_city
129 params = urlencode(post)
130 url = '%s?%s' % (defaults.action, params)
133 f = open(DEBUGLOG, 'a')
137 print 'Unable to write to DEBUGLOG: %s' % DEBUGLOG
143 """ Parser for search response
146 def __init__(self, html):
147 self.soup = BeautifulSoup(html)
149 def check_page(self):
150 if self.soup.find('form', {'id': 'form_efaresults'}):
151 return PageType.RESULT
153 if self.soup.find('div', {'class':'form_error'}):
154 return PageType.CORRECTION
156 return PageType.UNKNOWN
158 state = property(check_page)
160 def get_correction(self):
161 names_origin = self.soup.find('select', {'id': 'nameList_origin'})
162 names_destination = self.soup.find('select', {'id': 'nameList_destination'})
163 places_origin = self.soup.find('select', {'id': 'placeList_origin'})
164 places_destination = self.soup.find('select', {'id': 'placeList_destination'})
167 if names_origin or names_destination or places_origin or places_destination:
171 dict['origin'] = map(lambda x: x.text, names_origin.findAll('option'))
172 if names_destination:
173 dict['destination'] = map(lambda x: x.text, names_destination.findAll('option'))
176 dict['place_origin'] = map(lambda x: x.text, names_origin.findAll('option'))
177 if names_destination:
178 dict['place_destination'] = map(lambda x: x.text, names_destination.findAll('option'))
183 raise ParserError('Unable to parse html')
185 def get_result(self):
186 return rParser(str(self.soup))
191 """ Parser for routing results
194 def __init__(self, html):
195 self.soup = BeautifulSoup(html)
196 self._overview = None
200 def get_tdtext(cls, x, cl):
201 return x.find('td', {'class': cl}).text
204 def get_change(cls, x):
205 y = rParser.get_tdtext(x, 'col_change')
212 def get_price(cls, x):
213 y = rParser.get_tdtext(x, 'col_price')
217 return float(y.replace(',', '.'))
222 def get_date(cls, x):
223 y = rParser.get_tdtext(x, 'col_date')
225 return datetime.strptime(y, '%d.%m.%Y').date()
230 def get_datetime(cls, x):
231 y = rParser.get_tdtext(x, 'col_time')
233 if (y.find("-") > 0):
235 times = map(lambda z: time(*map(int, z.split(':'))), y.split('-'))
236 d = rParser.get_date(x)
237 from_dtime = datetime.combine(d, times[0])
238 if times[0] > times[1]:
240 to_dtime = datetime.combine(d + timedelta(1), times[1])
242 to_dtime = datetime.combine(d, times[1])
244 return [from_dtime, to_dtime]
247 dtregex = {'date' : '\d\d\.\d\d',
250 regex = "\s*(?P<date1>{date})?\s*(?P<time1>{time})\s*(?P<date2>{date})?\s*(?P<time2>{time})\s*".format(**dtregex)
251 ma = re.match(regex, y)
258 def extract_datetime(gr, n):
259 if 'date%d' % n in gr and gr['date%d' % n]:
260 from_dtime = datetime.strptime(str(datetime.today().year) + gr['date%d' % n] + gr['time%d' % n], '%Y%d.%m.%H:%M')
262 t = datetime.strptime(gr['time%d' % n], '%H:%M').time()
263 d = datetime.today().date()
264 return datetime.combine(d, t)
267 from_dtime = extract_datetime(gr, 1)
268 to_dtime = extract_datetime(gr, 2)
270 return [from_dtime, to_dtime]
276 for detail in self.details():
279 def _parse_details(self):
280 tours = self.soup.findAll('div', {'class': 'data_table tourdetail'})
282 trips = map(lambda x: map(lambda y: {
283 'timespan': rParser.get_datetime(y),
284 'station': map(lambda z: z[2:].strip(),
285 filter(lambda x: type(x) == NavigableString, y.find('td', {'class': 'col_station'}).contents)), # filter non NaviStrings
286 'info': map(lambda x: x.strip(),
287 filter(lambda z: type(z) == NavigableString, y.find('td', {'class': 'col_info'}).contents)),
288 }, x.find('tbody').findAll('tr')),
294 """returns list of trip details
295 [ [ { 'time': [datetime.time, datetime.time] if time else [],
296 'station': [u'start', u'end'] if station else [],
297 'info': [u'start station' if station else u'details for walking', u'end station' if station else u'walking duration']
298 }, ... # next trip step
299 ], ... # next trip possibility
302 if not self._details:
303 self._details = self._parse_details()
307 def _parse_overview(self):
310 table = self.soup.find('table', {'id': 'tbl_fahrten'})
312 # check if there is an overview table
313 if table and table.findAll('tr'):
315 rows = table.findAll('tr')[1:] # cut off headline
317 overview = map(lambda x: {
318 'timespan': rParser.get_datetime(x),
319 'change': rParser.get_change(x),
320 'price': rParser.get_price(x),
324 raise ParserError('Unable to parse overview')
337 if not self._overview:
339 self._overview = self._parse_overview()
340 except AttributeError:
341 f = open(DEBUGLOG, 'w')
342 f.write(str(self.soup))
345 return self._overview