first attempt to connect qml gui to pyside
[pywienerlinien] / gotovienna / routing.py
1 #!/usr/bin/env python
2 # -*- coding: UTF-8 -*-
3
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
9 import argparse
10 import sys
11 import os.path
12 import re
13
14 from gotovienna import defaults
15
16 POSITION_TYPES = ('stop', 'address', 'poi')
17 TIMEFORMAT = '%H:%M'
18 DEBUGLOG = os.path.expanduser('~/gotoVienna.debug')
19
20 class ParserError(Exception):
21
22     def __init__(self, msg='Parser error'):
23         self.message = msg
24
25 class PageType:
26     UNKNOWN, CORRECTION, RESULT = range(3)
27
28
29 def extract_city(station):
30     """ Extract city from string if present,
31     else return default city
32     
33     >>> extract_city('Karlsplatz, Wien')
34     'Wien'
35     """
36     if len(station.split(',')) > 1:
37         return station.split(',')[-1].strip()
38     else:
39         return 'Wien'
40         
41 def extract_station(station):
42     """ Remove city from string
43     
44     >>> extract_station('Karlsplatz, Wien')
45     'Karlsplatz'
46     """
47     if len(station.split(',')) > 1:
48         return station[:station.rindex(',')].strip()
49     else:
50         return station
51     
52 def split_station(station):
53     """ >>> split_station('Karlsplatz, Wien')
54     ('Karlsplatz', 'Wien')
55     >>> split_station('Karlsplatz')
56     ('Karlsplatz', 'Wien')
57     """
58     if len(station.split(',')) > 1:
59         return (station[:station.rindex(',')].strip(), station.split(',')[-1].strip())
60     else:
61         return (station, 'Wien')
62
63 def guess_location_type(location):
64     """Guess type (stop, address, poi) of a location
65
66     >>> guess_location_type('pilgramgasse')
67     'stop'
68
69     >>> guess_location_type('karlsplatz 14')
70     'address'
71
72     >>> guess_location_type('reumannplatz 12/34')
73     'address'
74     """
75     parts = location.split()
76     first_part = parts[0]
77     last_part = parts[-1]
78
79     # Assume all single-word locations are stops
80     if len(parts) == 1:
81         return 'stop'
82
83     # If the last part is numeric, assume address
84     if last_part.isdigit() and len(parts) > 1:
85         return 'address'
86
87     # Addresses with door number (e.g. "12/34")
88     if all(x.isdigit() or x == '/' for x in last_part):
89         return 'address'
90
91     # Sane default - assume it's a stop/station name
92     return 'stop'
93
94 def search(origin_tuple, destination_tuple, dtime=None):
95     """ build route request
96     returns html result (as urllib response)
97     """
98     if not dtime:
99         dtime = datetime.now()
100
101     origin, origin_type = origin_tuple
102     origin, origin_city = split_station(origin)
103     
104     destination, destination_type = destination_tuple
105     destination, destination_city = split_station(destination)
106
107
108     if origin_type is None:
109         origin_type = guess_location_type(origin)
110         print 'Guessed origin type:', origin_type
111
112     if destination_type is None:
113         destination_type = guess_location_type(destination)
114         print 'Guessed destination type:', destination_type
115
116     if (origin_type not in POSITION_TYPES or
117             destination_type not in POSITION_TYPES):
118         raise ParserError('Invalid position type')
119
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)
131
132     try:
133         f = open(DEBUGLOG, 'a')
134         f.write(url + '\n')
135         f.close()
136     except:
137         print 'Unable to write to DEBUGLOG: %s' % DEBUGLOG
138
139     return urlopen(url)
140
141
142 class sParser:
143     """ Parser for search response
144     """
145
146     def __init__(self, html):
147         self.soup = BeautifulSoup(html)
148
149     def check_page(self):
150         if self.soup.find('form', {'id': 'form_efaresults'}):
151             return PageType.RESULT
152
153         if self.soup.find('div', {'class':'form_error'}):
154             return PageType.CORRECTION
155
156         return PageType.UNKNOWN
157
158     state = property(check_page)
159
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'})
165         
166
167         if names_origin or names_destination or places_origin or places_destination:
168             dict = {}
169             
170             if names_origin:
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'))
174                 
175             if places_origin:
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'))
179     
180             return dict
181         
182         else:
183             raise ParserError('Unable to parse html')
184
185     def get_result(self):
186         return rParser(str(self.soup))
187
188
189
190 class rParser:
191     """ Parser for routing results
192     """
193
194     def __init__(self, html):
195         self.soup = BeautifulSoup(html)
196         self._overview = None
197         self._details = None
198
199     @classmethod
200     def get_tdtext(cls, x, cl):
201             return x.find('td', {'class': cl}).text
202
203     @classmethod
204     def get_change(cls, x):
205         y = rParser.get_tdtext(x, 'col_change')
206         if y:
207             return int(y)
208         else:
209             return 0
210
211     @classmethod
212     def get_price(cls, x):
213         y = rParser.get_tdtext(x, 'col_price')
214         if y == '*':
215             return 0.0
216         if y.find(','):
217             return float(y.replace(',', '.'))
218         else:
219             return 0.0
220
221     @classmethod
222     def get_date(cls, x):
223         y = rParser.get_tdtext(x, 'col_date')
224         if y:
225             return datetime.strptime(y, '%d.%m.%Y').date()
226         else:
227             return None
228
229     @classmethod
230     def get_datetime(cls, x):
231         y = rParser.get_tdtext(x, 'col_time')
232         if y:
233             if (y.find("-") > 0):
234                 # overview mode
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]:
239                     # dateline crossing
240                     to_dtime = datetime.combine(d + timedelta(1), times[1])
241                 else:
242                     to_dtime = datetime.combine(d, times[1])
243                     
244                 return [from_dtime, to_dtime]
245             
246             else:
247                 dtregex = {'date' : '\d\d\.\d\d',
248                            'time': '\d\d:\d\d'}
249                 
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)
252                 
253                 if not ma:
254                     return []
255                 
256                 gr = ma.groupdict()
257                 
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')
261                     else:
262                         t = datetime.strptime(gr['time%d' % n], '%H:%M').time()
263                         d = datetime.today().date()
264                         return datetime.combine(d, t)
265                 
266                 # detail mode
267                 from_dtime = extract_datetime(gr, 1)
268                 to_dtime = extract_datetime(gr, 2)
269                 
270                 return [from_dtime, to_dtime]
271                 
272         else:
273             return []
274
275     def __iter__(self):
276         for detail in self.details():
277             yield detail
278
279     def _parse_details(self):
280         tours = self.soup.findAll('div', {'class': 'data_table tourdetail'})
281
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')),
289                     tours) # all routes
290         return trips
291
292     @property
293     def details(self):
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
300         ]
301         """
302         if not self._details:
303             self._details = self._parse_details()
304
305         return self._details
306
307     def _parse_overview(self):
308
309         # get overview table
310         table = self.soup.find('table', {'id': 'tbl_fahrten'})
311
312         # check if there is an overview table
313         if table and table.findAll('tr'):
314             # get rows
315             rows = table.findAll('tr')[1:] # cut off headline
316
317             overview = map(lambda x: {
318                                'timespan': rParser.get_datetime(x),
319                                'change': rParser.get_change(x),
320                                'price': rParser.get_price(x),
321                            },
322                            rows)
323         else:
324             raise ParserError('Unable to parse overview')
325
326         return overview
327
328     @property
329     def overview(self):
330         """dict containing
331         date: datetime
332         time: [time, time]
333         duration: time
334         change: int
335         price: float
336         """
337         if not self._overview:
338             try:
339                 self._overview = self._parse_overview()
340             except AttributeError:
341                 f = open(DEBUGLOG, 'w')
342                 f.write(str(self.soup))
343                 f.close()
344
345         return self._overview
346