Exemple #1
0
    def routes(self):
        'returns a list of routes'
        agency = self.agency

        url = '{0}/routes-for-agency/{1}.json' \
            .format(self.url, self._decode_id(agency.get_id()))
        resp = self.session.get(url, params=self.params)

        routes = []
        for route in resp.json()['data']['list']:
            short_name = route['shortName']
            long_name = route['longName']

            name = ''
            if short_name and long_name.find(short_name) == -1:
                name = short_name + " - "
            name += long_name if long_name else route['description']

            color = route['color'] if route['color'] else None
            id = self._encode_id(Route.create_id(agency.id, route['id']))
            routes.append(
                Route(id=id,
                      agency=agency,
                      sign=short_name,
                      name=name,
                      type=route_types[int(route['type'])],
                      color=color))

        routes.sort(key=route_key)
        for i, route in enumerate(routes):
            route.order = i

        return routes
Exemple #2
0
    def _stop_arrivals(self, stop):
        params = {'command': 'predictions', 'a': stop.agency.get_id(),
                  'stopId': stop.code}

        resp = requests.get(self.url, params=params)

        arrivals = []
        for predictions in parse(resp.content)['body']['predictions']:
            route_id = Route.create_id(stop.agency.id,
                                       predictions['@routeTag'])
            if 'direction' not in predictions:
                continue
            directions = predictions['direction']
            if isinstance(directions, OrderedDict):
                directions = [directions]
            for direction in directions:
                predictions = direction['prediction']
                if isinstance(predictions, OrderedDict):
                    predictions = [predictions]
                for prediction in predictions:
                    dir_id = Direction.create_id(route_id,
                                                 prediction['@dirTag'])
                    departure = prediction['@isDeparture'] == 'true'
                    arrivals.append(Arrival(stop=stop,
                                            away=int(prediction['@seconds']),
                                            direction_id=dir_id))

        arrivals.sort(key=attrgetter('away'))
        return arrivals
Exemple #3
0
    def routes(self):
        agency = self.agency

        # use external id
        params = {'command': 'routeList', 'a': agency.get_id()}

        resp = self.session.get(self.url, params=params)

        routes = []
        for i, route in enumerate(parse(resp.content)['body']['route']):
            tag = route['@tag']
            id = Route.create_id(agency.id, tag)
            # TODO: type, url, color (may require pre-walk etc.)
            routes.append(Route(id=id, agency=agency, name=route['@title'],
                                sign=tag, order=i))
        return routes
Exemple #4
0
    def routes(self):
        'returns a list of routes'
        agency = self.agency

        url = '{0}/routes-for-agency/{1}.json' \
            .format(self.url, self._decode_id(agency.get_id()))
        resp = self.session.get(url, params=self.params)

        routes = []
        for route in resp.json()['data']['list']:
            short_name = route['shortName']
            long_name = route['longName']

            name = ''
            if short_name and long_name.find(short_name) == -1:
                name = short_name + " - "
            name += long_name if long_name else route['description']

            color = route['color'] if route['color'] else None
            id = self._encode_id(Route.create_id(agency.id, route['id']))
            routes.append(Route(id=id, agency=agency, sign=short_name,
                                name=name,
                                type=route_types[int(route['type'])],
                                color=color))

        routes.sort(key=route_key)
        for i, route in enumerate(routes):
            route.order = i

        return routes
Exemple #5
0
    def _stop_arrivals(self, stop):
        url = 'http://bustime.mta.info/api/siri/stop-monitoring.json'

        # shares api keys with onebus
        params = dict(self.params)
        params['MonitoringRef'] = stop.get_id().split('_')[1]

        arrivals = []

        resp = requests.get(url, params=params)

        data = resp.json()['Siri']['ServiceDelivery']
        data = data['StopMonitoringDelivery'][0]

        for visit in data['MonitoredStopVisit']:
            visit = visit['MonitoredVehicleJourney']
            did = Direction.create_id(Route.create_id(stop.agency.id,
                                                      visit['LineRef']),
                                      visit['DirectionRef'])
            visit = visit['MonitoredCall']
            away = visit['Extensions']['Distances']['DistanceFromCall']
            arrivals.append(Arrival(stop=stop, away=int(away),
                                    unit=arrival_units[1], direction_id=did))

        return arrivals
Exemple #6
0
    def _stop_arrivals(self, stop):
        url = 'http://bustime.mta.info/api/siri/stop-monitoring.json'

        # shares api keys with onebus
        params = dict(self.params)
        params['MonitoringRef'] = stop.get_id().split('_')[1]

        arrivals = []

        resp = requests.get(url, params=params)

        data = resp.json()['Siri']['ServiceDelivery']
        data = data['StopMonitoringDelivery'][0]

        for visit in data['MonitoredStopVisit']:
            visit = visit['MonitoredVehicleJourney']
            did = Direction.create_id(
                Route.create_id(stop.agency.id, visit['LineRef']),
                visit['DirectionRef'])
            visit = visit['MonitoredCall']
            away = visit['Extensions']['Distances']['DistanceFromCall']
            arrivals.append(
                Arrival(stop=stop,
                        away=int(away),
                        unit=arrival_units[1],
                        direction_id=did))

        return arrivals
Exemple #7
0
    def routes(self):

        params = {'Action': 'RouteList'}
        resp = self.session.get(self.url, params=params)

        data = parse(resp.content)['ActionRouteList']['RouteList']['Route']
        routes = {}
        stops = {}
        for route in data:
            line = route['Line']
            id = Route.create_id(self.agency.id, line['@LineId'])
            if id not in routes:
                # TODO route_type from line['ModeType']['@ModeTypeIdx']
                routes[id] = (line['@SortOrder'],
                              Route(id=id,
                                    agency=self.agency,
                                    name=line['@LineName'],
                                    sign=line['@LineId']))

        return [r[1] for r in sorted(routes.values(), key=itemgetter(0))]
Exemple #8
0
    def retrieve(self, request, region, agency, pk):
        try:
            route = Route.objects.select_related('agency', 'agency__region') \
                .prefetch_related('directions', 'directions__stops') \
                .get(pk=Route.create_id(Agency.create_id(region, agency), pk))
        except Route.DoesNotExist:
            raise Http404('No Route matches the given query.')

        stops = []
        for direction in route.directions.all():
            stops.extend(direction.stops.all())

        self.object = Adapter(route, stops=stops)
        serializer = self.get_serializer(self.object)
        return Response(serializer.data)
Exemple #9
0
    def retrieve(self, request, region, agency, pk):
        try:
            route = Route.objects.select_related('agency', 'agency__region') \
                .prefetch_related('directions', 'directions__stops') \
                .get(pk=Route.create_id(Agency.create_id(region, agency), pk))
        except Route.DoesNotExist:
            raise Http404('No Route matches the given query.')

        stops = []
        for direction in route.directions.all():
            stops.extend(direction.stops.all())

        self.object = Adapter(route, stops=stops)
        serializer = self.get_serializer(self.object)
        return Response(serializer.data)
Exemple #10
0
    def routes(self):
        routes = []

        agency = self.agency

        aid = agency.get_id()
        for route in self._routes(join('data', agency.id)):
            # if there's no agency_id, we'll assume they're all a part of
            # the single agency we're processing, hopefully that's correct
            if 'agency_id' in route and route['agency_id'] != aid:
                continue
            id = Route.create_id(agency.id, route['route_id'])
            routes.append(
                Route(agency=agency,
                      id=id,
                      sign=route['route_short_name'],
                      name=route['route_long_name'],
                      type=route_types[int(route['route_type'])],
                      color=route.get('route_color', None)))

        routes.sort(key=route_key)
        for i, route in enumerate(routes):
            route.order = i
        return routes
Exemple #11
0
    def routes(self):
        agency = self.agency

        # use external id
        params = {"command": "routeList", "a": agency.get_id()}

        resp = self.session.get(self.url, params=params)

        routes = []
        for i, route in enumerate(parse(resp.content)["body"]["route"]):
            tag = route["@tag"]
            id = Route.create_id(agency.id, tag)
            # TODO: type, url, color (may require pre-walk etc.)
            routes.append(Route(id=id, agency=agency, name=route["@title"], sign=tag, order=i))
        return routes
Exemple #12
0
    def retrieve(self, request, region, agency, route, pk):
        try:
            stop = Stop.objects.select_related('agency', 'agency__region') \
                .get(pk=Stop.create_id(Agency.create_id(region, agency), pk))
        except Stop.DoesNotExist:
            raise Http404('No Route matches the given query.')
        agency = stop.agency

        route = get_object_or_404(Route, pk=Route.create_id(agency.id, route))
        arrivals = get_provider(stop.agency).arrivals(stop, route)

        self.object = StopAdapter(stop, arrivals=arrivals, route=route)

        serializer = self.get_serializer(self.object)
        return Response(serializer.data)
Exemple #13
0
    def routes(self):
        agency = self.agency

        url = '{0}{1}'.format(self.url, 'route.aspx')
        params = dict(self.params)
        params['cmd'] = 'routes'

        resp = self.session.get(url, params=params)

        # preserve BART's order
        routes = OrderedDict()
        for route in parse(resp.content)['root']['routes']['route']:
            color = route['color']
            if color not in routes:
                id = Route.create_id(agency.id, route['abbr'])
                routes[color] = Route(id=id,
                                      agency=agency,
                                      name=route['name'],
                                      sign=route['abbr'],
                                      type=route_types[1],
                                      color=route['color'],
                                      order=len(routes))

        return list(routes.values())
Exemple #14
0
    def routes(self):

        params = {'Action': 'RouteList'}
        resp = self.session.get(self.url, params=params)


        data = parse(resp.content)['ActionRouteList']['RouteList']['Route']
        routes = {}
        stops = {}
        for route in data:
            line = route['Line']
            id = Route.create_id(self.agency.id, line['@LineId'])
            if id not in routes:
                # TODO route_type from line['ModeType']['@ModeTypeIdx']
                routes[id] = (line['@SortOrder'],
                              Route(id=id, agency=self.agency,
                                    name=line['@LineName'],
                                    sign=line['@LineId']))

        return [r[1] for r in sorted(routes.values(), key=itemgetter(0))]
Exemple #15
0
    def routes(self):
        agency = self.agency

        url = '{0}{1}'.format(self.url, 'route.aspx')
        params = dict(self.params)
        params['cmd'] = 'routes'

        resp = self.session.get(url, params=params)

        # preserve BART's order
        routes = OrderedDict()
        for route in parse(resp.content)['root']['routes']['route']:
            color = route['color']
            if color not in routes:
                id = Route.create_id(agency.id, route['abbr'])
                routes[color] = Route(id=id, agency=agency, name=route['name'],
                                      sign=route['abbr'], type=route_types[1],
                                      color=route['color'],
                                      order=len(routes))

        return list(routes.values())
Exemple #16
0
    def routes(self):
        routes = []

        agency = self.agency

        aid = agency.get_id()
        for route in self._routes(join('data', agency.id)):
            # if there's no agency_id, we'll assume they're all a part of
            # the single agency we're processing, hopefully that's correct
            if 'agency_id' in route and route['agency_id'] != aid:
                continue
            id = Route.create_id(agency.id, route['route_id'])
            routes.append(Route(agency=agency, id=id,
                                sign=route['route_short_name'],
                                name=route['route_long_name'],
                                type=route_types[int(route['route_type'])],
                                color=route.get('route_color', None)))

        routes.sort(key=route_key)
        for i, route in enumerate(routes):
            route.order = i
        return routes
Exemple #17
0
    def _stop_arrivals(self, stop):
        params = {"command": "predictions", "a": stop.agency.get_id(), "stopId": stop.code}

        resp = requests.get(self.url, params=params)

        arrivals = []
        for predictions in parse(resp.content)["body"]["predictions"]:
            route_id = Route.create_id(stop.agency.id, predictions["@routeTag"])
            if "direction" not in predictions:
                continue
            directions = predictions["direction"]
            if isinstance(directions, OrderedDict):
                directions = [directions]
            for direction in directions:
                predictions = direction["prediction"]
                if isinstance(predictions, OrderedDict):
                    predictions = [predictions]
                for prediction in predictions:
                    dir_id = Direction.create_id(route_id, prediction["@dirTag"])
                    departure = prediction["@isDeparture"] == "true"
                    arrivals.append(Arrival(stop=stop, away=int(prediction["@seconds"]), direction_id=dir_id))

        arrivals.sort(key=attrgetter("away"))
        return arrivals