summaryrefslogtreecommitdiff
path: root/bvggrabber/api/actualdeparture.py
blob: 00b6d1dfd9824901cb87431b800955bd2e48f686 (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
# -*- coding: utf-8 -*-
import requests

from bs4 import BeautifulSoup

from bvggrabber.api import QueryApi, Departure, Response


ACTUAL_API_ENDPOINT = 'http://mobil.bvg.de/Fahrinfo/bin/stboard.bin/dox?ld=0.1&rt=0&'


class ActualDepartureQueryApi(QueryApi):

    def __init__(self, station, limit=5):
        super(ActualDepartureQueryApi, self).__init__()
        if isinstance(station, str):
            self.station_enc = station.encode('iso-8859-1')
        elif isinstance(station, bytes):
            self.station_enc = station
        else:
            raise ValueError("Invalid type for station")
        self.station = station
        self.limit = limit

    def call(self):
        params = {
            'input': self.station_enc,
            'maxJourneys': self.limit,
            'start': 'suchen',
        }
        response = requests.get(ACTUAL_API_ENDPOINT, params=params)
        if response.ok:
            soup = BeautifulSoup(response.text, "html.parser")
            if soup.find_all('form'):
                # The station we are looking for is ambiguous or does not exist
                stations = soup.find_all('option')
                if stations:
                    # The station is ambiguous
                    stationlist = [s.get('value') for s in stations]
                    return Response(False, stationlist)
                else:
                    # The station does not exist
                    return Response(False)
            else:
                # The station seems to exist
                result = soup.find('div', {'id': '',
                                           'class': 'ivu_result_box'})
                if result is None:
                    return Response(True, self.station, [])
                rows = result.find_all('tr')
                departures = []
                for row in rows:
                    if row.parent.name == 'tbody':
                        stro = row.find_all("strong")
                        td = row.find_all('td')
                        if td:
                            dep = Departure(start=self.station,
                                            end=td[2].text.strip(),
                                            when=td[0].text.strip(),
                                            line=stro[1].text.strip())
                            departures.append(dep)
                return Response(True, self.station, departures)
        else:
            try:
                response.raise_for_status()
            except requests.RequestException as e:
                return Response(False, error=e)
            else:
                return Response(False,
                                error=Exception("An unknown error occured"))