stdeb-based packaging for Harmattan
[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
9 from gotovienna import defaults
10
11 class ITipParser:
12     def __init__(self):
13         self._stations = {}
14         self._lines = {}
15
16     def get_stations(self, name):
17         """ Get station by direction
18         {'Directionname': [('Station name', 'url')]}
19         """
20         if not self._stations.has_key(name):
21             st = {}
22
23             if not self.lines.has_key(name):
24                 return None
25
26             bs = BeautifulSoup(urlopen(self.lines[name]))
27             tables = bs.findAll('table', {'class': 'text_10pix'})
28             for i in range(2):
29                 dir = tables[i].div.contents[-1].strip(' ')
30
31                 sta = []
32                 for tr in tables[i].findAll('tr', {'onmouseout': 'obj_unhighlight(this);'}):
33                     if tr.a:
34                         sta.append((tr.a.text, defaults.line_overview + tr.a['href']))
35                     else:
36                         sta.append((tr.text.strip(' '), None))
37
38                 st[dir] = sta
39             self._stations[name] = st
40
41         return self._stations[name]
42
43     @property
44     def lines(self):
45         """ Dictionary of Line names with url as value
46         """
47         if not self._lines:
48             bs = BeautifulSoup(urlopen(defaults.line_overview))
49             # get tables
50             lines = bs.findAll('td', {'class': 'linie'})
51
52             for line in lines:
53                 if line.a:
54                     href = defaults.line_overview + line.a['href']
55                     if line.text:
56                         self._lines[line.text] = href
57                     elif line.img:
58                         self._lines[line.img['alt']] = href
59
60         return self._lines
61
62     def get_departures(self, url):
63         """ Get list of next departures
64         integer if time until next departure
65         time if time of next departure
66         """
67
68         #TODO parse line name and direction for station site parsing
69
70         if not url:
71             # FIXME prevent from calling this method with None
72             return []
73
74         bs = BeautifulSoup(urlopen(url))
75         result_lines = bs.findAll('table')[-1].findAll('tr')
76
77         dep = []
78         for tr in result_lines[1:]:
79             th = tr.findAll('th')
80             if len(th) < 2:
81                 #TODO replace with logger
82                 print "[DEBUG] Unable to find th in:\n%s" % str(tr)
83                 continue
84
85             # parse time
86             time = th[-2].text.split(' ')
87             if len(time) < 2:
88                 #print 'Invalid time: %s' % time
89                 # TODO: Issue a warning OR convert "HH:MM" format to countdown
90                 continue
91
92             time = time[1]
93
94             if time.find('rze...') >= 0:
95                     dep.append(0)
96             elif time.isdigit():
97                 # if time to next departure in cell convert to int
98                 dep.append(int(time))
99             else:
100                 # check if time of next departue in cell
101                 t = time.strip('&nbsp;').split(':')
102                 if len(t) == 2 and all(map(lambda x: x.isdigit(), t)):
103                     t = map(int, t)
104                     dep.append(time(*t))
105                 else:
106                     # Unexpected content
107                     #TODO replace with logger
108                     print "[DEBUG] Invalid data:\n%s" % time
109
110         return dep
111
112
113 UBAHN, TRAM, BUS, NIGHTLINE, OTHER = range(5)
114 LINE_TYPE_NAMES = ['U-Bahn', 'Strassenbahn', 'Bus', 'Nightline', 'Andere']
115
116 def get_line_sort_key(name):
117     """Return a sort key for a line name
118
119     >>> get_line_sort_key('U6')
120     ('U', 6)
121
122     >>> get_line_sort_key('D')
123     ('D', 0)
124
125     >>> get_line_sort_key('59A')
126     ('A', 59)
127     """
128     txt = ''.join(x for x in name if not x.isdigit())
129     num = ''.join(x for x in name if x.isdigit()) or '0'
130
131     return (txt, int(num))
132
133 def get_line_type(name):
134     """Get the type of line for the given name
135
136     >>> get_line_type('U1')
137     UBAHN
138     >>> get_line_type('59A')
139     BUS
140     """
141     if name.isdigit():
142         return TRAM
143     elif name.endswith('A') or name.endswith('B') and name[1].isdigit():
144         return BUS
145     elif name.startswith('U'):
146         return UBAHN
147     elif name.startswith('N'):
148         return NIGHTLINE
149     elif name in ('D', 'O', 'VRT', 'WLB'):
150         return TRAM
151
152     return OTHER
153
154 def categorize_lines(lines):
155     """Return a categorized version of a list of line names
156
157     >>> categorize_lines(['U4', 'U3', '59A'])
158     [('U-Bahn', ['U3', 'U4']), ('Bus', ['59A'])]
159     """
160     categorized_lines = collections.defaultdict(list)
161
162     for line in sorted(lines):
163         line_type = get_line_type(line)
164         categorized_lines[line_type].append(line)
165
166     for lines in categorized_lines.values():
167         lines.sort(key=get_line_sort_key)
168
169     return [(LINE_TYPE_NAMES[key], categorized_lines[key])
170             for key in sorted(categorized_lines)]
171