summaryrefslogtreecommitdiffstats
path: root/pytransportapi.py
blob: 71f3d2716e5e5893c922cbed07394327d09d90f3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
#!/usr/bin/python3
# vim: set fileencoding=utf-8 ts=4 sts=4 sw=4 tw=80 expandtab :

# Copyright (C) 2012 Florian Bruhin <me@the-compiler.org>

# This file is part of pytransportapi.
# 
# pytransportapi is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# pytransportapi is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with pytransportapi.  If not, see <http://www.gnu.org/licenses/>.

import datetime
import re
import dateutil.parser
import requests
import time

__version__ = '0.2'

class Location:
    """A Location-object as returned by the transport API, with some attributes
    converted to Python-objects
    """
    def __init__(self, j):
        """Convert a json-dict of a Location to a Python-object

        >>> loc = Location({
        ...     'id':  '008503000', 'name': 'Zuerich', 'score': '100',
        ...     'coordinate': { 'type': 'WGS84', 'x': '8540192',
        ...                     'y': '47378177' }})
        >>> print(loc)
        Zuerich
        >>> loc.loc_id
        '008503000'
        >>> loc.name
        'Zuerich'
        >>> loc.score
        '100'
        """
        # The id of the location
        try:
            self.loc_id = j['id']
        except KeyError:
            self.loc_id = None
        # Type of the location, can contain:
        #  * station: Location is a train station, bus station
        #  * poi: Location is a point of interest (Clock tower, China garden)
        #  * address: Location is an address
        #  * refine: Location is not defined, the user has to relocate
        self.type_ = j.get('type', None)
        # The location name
        self.name = j['name']
        # The accuracy of the result
        self.score = j.get('score', None)
        # The location coordinates (a Coordinates object)
        self.coordinates = Coordinates(j['coordinate'])
        # If search has been with coordinates, distance to original point in
        # meters
        self.distance = j.get('distance', None)
        # Raw data
        self.raw = j

    def __repr__(self):
        return "{}({})".format(self.__class__.__name__, self.raw)

    def __str__(self):
        return self.name


class Coordinates:
    """A Coordinates-object as returned by the transport API, with some
    attributes converted to Python-objects
    """
    def __init__(self, j):
        """ Converts a json-dict of a Coordinates-object to a Python-object

        >>> coord = Coordinates({'type': 'WGS84', 'x': 6629086,
        ...                                     'y': 46516785})
        >>> coord.coord_type
        'WGS84'
        >>> coord.lat
        6629086
        >>> coord.lon
        46516785
        >>> print(coord)
        6629086 / 46516785
        """
        # The type of the given coordinate
        self.coord_type = j['type']
        # Latitude
        self.lat = lat = j['y']
        # Longitude
        self.lon = lon = j['x']
        # Raw data
        self.raw = j

    def __repr__(self):
        return "{}({})".format(self.__class__.__name__, self.raw)

    def __str__(self):
        return "{} / {}".format(self.lat, self.lon)


class Connection:
    """A Connection-object as returned by the transport API

    A connection represents a possible journey between two locations.
    """
    def __init__(self, j):
        """ Converts a json-dict of a Connection-object to a Python-object """
        # The departure checkpoint of the connection (a Checkpoint object)
        self.from_ = Checkpoint(j['from'])
        # The arrival checkpoint of the connection (a Checkpoint object)
        self.to = Checkpoint(j['to'])
        # The duration of the journey (e.g. 00d00:43:00)
        self.duration = j.get('duration', None)
        if self.duration is not None:
            try:
                self.duration = self._durstr_to_tdelta(self.duration)
            except ValueError:
                self.duration = None
        # Service information about how regular the connection operates (A
        # Service object)
        self.service = Service(j['service'])
        # Number of transfers within the connection (e.g. 2)
        self.servicedays = j.get('serviceDays', None)
        # Array with transport products	 (e.g. IR, S9)
        self.products = j['products']
        # The maximum estimated occupation load of 1st class coaches (e.g. 1)
        self.capacity1st = j['capacity1st']
        # The maximum estimated occupation load of 2nd class coaches (e.g. 2)
        self.capacity2nd = j['capacity2nd']
        # The sections in a journey
        self.sections = []
        for section in j['sections']:
            self.sections.append(Section(section))
        # Raw data
        self.raw = j

    def __repr__(self):
        return "{}({})".format(self.__class__.__name__, self.raw)

    @classmethod
    def _durstr_to_tdelta(cls, durstr):
        """Converts a duration string like 1d:23:59:59 to a timedelta

        >>> Connection._durstr_to_tdelta('1d23:59:59')
        datetime.timedelta(1, 86399)
        >>> Connection._durstr_to_tdelta('1d23:59:59:')
        Traceback (most recent call last):
        ...
        ValueError: Invalid duration-string!
        """
        r = re.match(r'^(?P<days>\d+)d(?P<hours>\d+):(?P<minutes>\d+):'
                     r'(?P<seconds>\d+)$', durstr)
        if r is None:
            raise ValueError("Invalid duration-string!")
        d = r.groupdict()
        for k, v in d.items(): d[k] = int(v)
        return datetime.timedelta(**d)


class Checkpoint:
    """A Checkpoint-object as returned by the transport API

    A checkpoint represents an arrival or a departure point (in time and space)
    of a connection.
    """
    def __init__(self, j):
        """Converts a json-dict of a Checkpoint-object to a Python-object

        >>> cp = Checkpoint(
        ...     {'arrival': None, 'platform': '1', 'station': {'coordinate':
        ...     {'y': 47.366608, 'x': 8.548462, 'type': 'WGS84'}, 'distance':
        ...     None, 'score': None, 'id': '008503003', 'name':
        ...     'Z├╝rich Stadelhofen'},
        ...     'departure': '2012-07-09T20:17:00+0200', 'prognosis':
        ...     {'arrival': None, 'platform': None, 'capacity1st': None,
        ...     'capacity2nd': None, 'departure': None}})
        >>> type(cp.station)
        <class 'pytransportapi.Location'>
        >>> type(cp.prognosis)
        <class 'pytransportapi.Prognosis'>
        >>> cp.departure
        datetime.datetime(2012, 7, 9, 20, 17, tzinfo=tzoffset(None, 7200))
        """
        # The location of the checkpoint
        self.station = Location(j['station'])
        # The arrival time to the checkpoint (e.g. 14:58:00)
        if j['arrival'] is not None:
            self.arrival = dateutil.parser.parse(j['arrival'])
        else:
            self.arrival = None
        # The departure time from the checkpoint (e.g. 14:58:00)
        if j['departure'] is not None:
            self.departure = dateutil.parser.parse(j['departure'])
        else:
            self.departure = None
        # The arrival/departure platform (e.g. 8)
        self.platform = j['platform']
        # The checkpoint prognosis
        self.prognosis = Prognosis(j['prognosis'])
        # Raw data
        self.raw = j

    def __repr__(self):
        return "{}({})".format(self.__class__.__name__, self.raw)


class Service:
    """A Service-object as returned by the transport API

    Operation information for a connection.

    """
    def __init__(self, j): # FIXME can we parse these somehow?
        """Converts a json-dict of a Service-object to a Python-object

        >>> ser = Service({'regular': 'daily', 'irregular': 'not 15. Jul'})
        >>> ser.regular
        'daily'
        >>> ser.irregular
        'not 15. Jul'
        >>> str(ser)
        'daily, not 15. Jul'

        """
        # Information about how regular a connection operates. (e.g. daily)
        self.regular = j['regular']
        # Additional information about irregular operation dates.
        self.irregular = j['irregular']
        # Raw data
        self.raw = j

    def __repr__(self):
        return "{}({})".format(self.__class__.__name__, self.raw)

    def __str__(self):
        s = self.regular
        if self.irregular:
            s += ", "
            s += self.irregular
        return s


class Section:
    """A Section-object as returned by the transport API"""
    def __init__(self, j):
        """Converts a json-dict of a Section-object to a Python-object"""
        self.arrival = Checkpoint(j['arrival'])
        self.departure = Checkpoint(j['departure'])
        if j.get('journey') is not None:
            self.journey = Stop(j['journey'])
        else:
            self.journey = None
        # Raw data
        self.raw = j

    def __repr__(self):
        return "{}({})".format(self.__class__.__name__, self.raw)


class Prognosis:
    """A Prognosis-object as returned by the transport API

    A prognosis contains "realtime" informations on the status of a connection
    checkpoint.
    """
    def __init__(self, j):
        """Converts a json-dict of a Prognosis-object to a Python-object
        
        >>> pro = Prognosis(
        ...     {'arrival': '2012-03-31T09:35:00+02:00', 'platform': None,
        ...      'capacity1st': 1, 'capacity2nd': 1, 'departure': None})
        >>> pro.capacity1st
        1
        >>> pro.arrival
        datetime.datetime(2012, 3, 31, 9, 35, tzinfo=tzoffset(None, 7200))
        """
        # The estimated arrival/departure platform
        self.platform = j['platform']
        # The departure time prognosis to the checkpoint (e.g.
        # 2012-03-31T08:58:00+02:00)
        if j['departure'] is not None:
            self.departure = dateutil.parser.parse(j['departure'])
        else:
            self.departure = None
        # The arrival time prognosis to the checkpoint (e.g.
        # 2012-03-31T09:35:00+02:00)
        if j['arrival'] is not None:
            self.arrival = dateutil.parser.parse(j['arrival'])
        else:
            self.arrival = None
        # The estimated occupation load of 1st class coaches (e.g. 1)
        self.capacity1st = j['capacity1st']
        # The estimated occupation load of 2nd class coaches (e.g. 2)
        self.capacity2nd = j['capacity2nd']
        # Raw data
        self.raw = j

    def __repr__(self):
        return "{}({})".format(self.__class__.__name__, self.raw)


class Stop:
    """A Stop-object as returned by the transport API"""
    def __init__(self, j):
        """Converts a json-dict of a Stop-object to a Python-object"""
        # A location object showing this line's stop at the requested station.
        station = j.get('station')
        if station is not None:
            self.station = Location(j['station'])
        else:
            self.station = None
        # The name of the connection (e.g. Bus 2)
        self.name = j['name']
        # The type of connection (e.g. Bus)
        self.category = j['category']
        # The number of the connection's line, e.g. Bus line 2 (e.g. 2)
        self.number = j['number']
        # The operator of the connection's line	(e.g. BBA)
        self.operator = j['operator']
        # The final destination of this line (e.g. Aarau Rohr, Unterdorf)
        self.to = j['to']
        passlist = j.get('passList')
        if passlist is not None:
            self.passlist = []
            for e in passlist:
                self.passlist.append(Checkpoint(e))
        else:
            self.passlist = None
        # Raw data
        self.raw = j

    def __repr__(self):
        return "{}({})".format(self.__class__.__name__, self.raw)


class TransportClient:
    """A client for the transports API"""
    def __init__(self, useragent=None, baseurl=None):
        """Initializes the client, sets useragent and baseurl"""
        if useragent is None:
            self.useragent = (
                "pytransportapi v{} by The Compiler "
                "<opendata.ch@the-compiler.org>".format(__version__))
        else:
            self.useragent = useragent
        if baseurl is None:
            self.baseurl = "http://transport.opendata.ch/v1"
        else:
            self.baseurl = baseurl
            
    def location(self, query, lat=None, lon=None, loctype=None):
        """Returns the matching locations for the given parameters."""
        params = { 'query': query, 'x': lat, 'y': lon, 'type': loctype }
        data = self._query(params, self._location_cb, '/locations')
        return data

    def connections(self, from_, to,  via=None, datetime=None,
                    isArrivalTime=None, transportations=None, limit=None,
                    direct=None, sleeper=None, couchette=None, bike=None):
        """Returns the next connections from a location to another."""
        if datetime is None:
            date = None
            time = None
        else: # If we got a datetime
            date = datetime.strftime('%Y-%m-%d')
            time = datetime.strftime('%H:%M')
        params = { # Maps API parameters to function arguments
            'from': from_,
            'to': to,
            'via': via,
            'date': date,
            'time': time,
            'isArrivalTime': isArrivalTime,
            'transportations': transportations,
            'limit': limit,
            'direct': direct,
            'sleeper': sleeper,
            'couchette': couchette,
            'bike': bike,
        }
        data = self._query(params, self._connections_cb, '/connections')
        return data

    def stationboard(self, station=None, stationid=None, limit=None,
                     transportations=None):
        """Returns the next connections from a location to another."""
        if station is None and stationid is None:
            raise ValueError("You need to specify either a station or a "
                             "stationid")
        params = {
            'station': station,
            'stationid': stationid,
            'limit': limit,
            'transportations': transportations,
        }
        data = self._query(params, self._stationboard_cb, '/stationboard')
        return data

    def _location_cb(self, j):
        """Callback for the location method"""
        newlist = []
        try:
            for station in j['stations']:
                newlist.append(Location(station))
        except TypeError:
            print(j)

        return newlist

    def _connections_cb(self, j):
        """Callback for the connections method"""
        newlist = []
        for connection in j['connections']:
            newlist.append(Connection(connection))
        return newlist

    def _stationboard_cb(self, j):
        """Callback for the stationboard method"""
        newlist = []
        for stop in j['stationboard']:
            newlist.append(Stop(stop))
        return newlist

    def _query(self, params, callback, page):
        """Sends a query to the API"""
        headers = { 'User-Agent': self.useragent }
        params = self._convert_params(params)
        url = self.baseurl + page
        r = requests.get(url, params=params, headers=headers)
        data = callback(r.json)
        return data

    @classmethod
    def _convert_params(cls, params):
        """Convert parameters before sending them to the API

        >>> tmp = TransportClient._convert_params(
        ...     {'none': None, 'list': ['eggs', 'bacon'], 'true': True,
        ...      'false': False, 'normal': 'spam'})
        >>> tmp == {'false': 0, 'list[]': ['eggs', 'bacon'], 'true': 1,
        ...         'normal': 'spam'}
        True
        """
        newparams = {}
        for e in params:
            val = params[e]
            if val is not None: # If a parameter is None, don't send it
                # If we have multiple parameters (e.g. vias) the API requires
                # array notation
                if isinstance(val, list) and len(val) > 1:
                    newparams["{}[]".format(e)] = val
                # Send True as 1
                elif val is True:
                    newparams[e] = 1
                # Senf False as 0
                elif val is False:
                    newparams[e] = 0
                # Everything else gets sent without modification
                else:
                    newparams[e] = val
        return newparams