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