Restructuring; removing ui files
[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
8 from textwrap import wrap
9 import argparse
10 import sys
11 import os.path
12
13 from gotovienna import defaults
14
15 POSITION_TYPES = ('stop', 'address', 'poi')
16 TIMEFORMAT = '%H:%M'
17 DEBUGLOG = os.path.expanduser('~/gotoVienna.debug')
18
19 class ParserError(Exception):
20
21     def __init__(self, msg='Parser error'):
22         self.message = msg
23
24 class PageType:
25     UNKNOWN, CORRECTION, RESULT = range(3)
26
27
28 def search(origin_tuple, destination_tuple, dtime=None):
29     """ build route request
30     returns html result (as urllib response)
31     """
32     if not dtime:
33         dtime = datetime.now()
34
35     origin, origin_type = origin_tuple
36     destination, destination_type = destination_tuple
37     if not origin_type in POSITION_TYPES or\
38         not destination_type in POSITION_TYPES:
39         raise ParserError('Invalid position type')
40
41     post = defaults.search_post
42     post['name_origin'] = origin
43     post['type_origin'] = origin_type
44     post['name_destination'] = destination
45     post['type_destination'] = destination_type
46     post['itdDateDayMonthYear'] = dtime.strftime('%d.%m.%Y')
47     post['itdTime'] = dtime.strftime('%H:%M')
48     params = urlencode(post)
49     url = '%s?%s' % (defaults.action, params)
50
51     try:
52         f = open(DEBUGLOG, 'a')
53         f.write(url + '\n')
54         f.close()
55     except:
56         print 'Unable to write to DEBUGLOG: %s' % DEBUGLOG
57
58     return urlopen(url)
59
60
61 class sParser:
62     """ Parser for search response
63     """
64
65     def __init__(self, html):
66         self.soup = BeautifulSoup(html)
67
68     def check_page(self):
69         if self.soup.find('form', {'id': 'form_efaresults'}):
70             return PageType.RESULT
71
72         if self.soup.find('div', {'class':'form_error'}):
73             return PageType.CORRECTION
74
75         return PageType.UNKNOWN
76
77     def get_correction(self):
78         nlo = self.soup.find('select', {'id': 'nameList_origin'})
79         nld = self.soup.find('select', {'id': 'nameList_destination'})
80
81         if not nlo and not nld:
82             raise ParserError('Unable to parse html')
83
84         if nlo:
85             origin = map(lambda x: x.text, nlo.findAll('option'))
86         else:
87             origin = []
88         if nld:
89             destination = map(lambda x: x.text, nld.findAll('option'))
90         else:
91             destination = []
92
93         return (origin, destination)
94
95     def get_result(self):
96         return rParser(str(self.soup))
97
98
99
100 class rParser:
101     """ Parser for routing results
102     """
103
104     def __init__(self, html):
105         self.soup = BeautifulSoup(html)
106         self._overview = None
107         self._details = None
108
109     @classmethod
110     def get_tdtext(cls, x, cl):
111             return x.find('td', {'class': cl}).text
112
113     @classmethod
114     def get_change(cls, x):
115         y = rParser.get_tdtext(x, 'col_change')
116         if y:
117             return int(y)
118         else:
119             return 0
120
121     @classmethod
122     def get_price(cls, x):
123         y = rParser.get_tdtext(x, 'col_price')
124         if y == '*':
125             return 0.0
126         if y.find(','):
127             return float(y.replace(',', '.'))
128         else:
129             return 0.0
130
131     @classmethod
132     def get_date(cls, x):
133         y = rParser.get_tdtext(x, 'col_date')
134         if y:
135             return datetime.strptime(y, '%d.%m.%Y').date()
136         else:
137             return None
138
139     @classmethod
140     def get_time(cls, x):
141         y = rParser.get_tdtext(x, 'col_time')
142         if y:
143             if (y.find("-") > 0):
144                 return map(lambda z: time(*map(int, z.split(':'))), y.split('-'))
145             else:
146                 return map(lambda z: time(*map(int, z.split(':'))), wrap(y, 5))
147         else:
148             return []
149
150     @classmethod
151     def get_duration(cls, x):
152         y = rParser.get_tdtext(x, 'col_duration')
153         if y:
154             return time(*map(int, y.split(":")))
155         else:
156             return None
157
158     def __iter__(self):
159         for detail in self.details():
160             yield detail
161
162     def _parse_details(self):
163         tours = self.soup.findAll('div', {'class': 'data_table tourdetail'})
164
165         trips = map(lambda x: map(lambda y: {
166                         'time': rParser.get_time(y),
167                         'station': map(lambda z: z[2:].strip(),
168                                        filter(lambda x: type(x) == NavigableString, y.find('td', {'class': 'col_station'}).contents)), # filter non NaviStrings
169                         'info': map(lambda x: x.strip(),
170                                     filter(lambda z: type(z) == NavigableString, y.find('td', {'class': 'col_info'}).contents)),
171                     }, x.find('tbody').findAll('tr')),
172                     tours) # all routes
173         return trips
174
175     @property
176     def details(self):
177         """returns list of trip details
178         [ [ { 'time': [datetime.time, datetime.time] if time else [],
179               'station': [u'start', u'end'] if station else [],
180               'info': [u'start station' if station else u'details for walking', u'end station' if station else u'walking duration']
181             }, ... # next trip step
182           ], ... # next trip possibility
183         ]
184         """
185         if not self._details:
186             self._details = self._parse_details()
187
188         return self._details
189
190     def _parse_overview(self):
191
192         # get overview table
193         table = self.soup.find('table', {'id': 'tbl_fahrten'})
194
195         # check if there is an overview table
196         if table and table.findAll('tr'):
197             # get rows
198             rows = table.findAll('tr')[1:] # cut off headline
199
200             overview = map(lambda x: {
201                                'date': rParser.get_date(x),
202                                'time': rParser.get_time(x),
203                                'duration': rParser.get_duration(x), # grab duration
204                                'change': rParser.get_change(x),
205                                'price': rParser.get_price(x),
206                            },
207                            rows)
208         else:
209             raise ParserError('Unable to parse overview')
210
211         return overview
212
213     @property
214     def overview(self):
215         """dict containing
216         date: datetime
217         time: [time, time]
218         duration: time
219         change: int
220         price: float
221         """
222         if not self._overview:
223             try:
224                 self._overview = self._parse_overview()
225             except AttributeError:
226                 f = open(DEBUGLOG, 'w')
227                 f.write(str(self.soup))
228                 f.close()
229
230         return self._overview
231