Beispiel #1
0
    def fetch(self, request, key=None):
        cross_origin = request.META.get('HTTP_ORIGIN')
        if cross_origin is not None:
            try:
                if request.META['HTTP_HOST'] == urlparse(cross_origin).hostname:
                    cross_origin = None
            except ValueError:
                pass

        increment_cache_key('api_updates_fetch_requests%s' % ('_cross_origin' if cross_origin is not None else ''))

        from c3nav.site.models import SiteUpdate

        result = {
            'last_site_update': SiteUpdate.last_update(),
            'last_map_update': MapUpdate.current_processed_cache_key(),
        }
        if cross_origin is None:
            result.update({
                'user': get_user_data(request),
            })

        response = Response(result)
        if cross_origin is not None:
            response['Access-Control-Allow-Origin'] = cross_origin
            response['Access-Control-Allow-Credentials'] = 'true'
        set_tile_access_cookie(request, response)

        return response
Beispiel #2
0
 def wrapped_func(self, request, *args, **kwargs):
     response = func(self, request, *args, **kwargs)
     if response.status_code < 400 and kwargs:
         name, value = next(iter(kwargs.items()))
         for value in api_stats_clean_location_value(value):
             increment_cache_key('apistats__%s__%s__%s' % (view_name, name, value))
     return response
Beispiel #3
0
    def fetch(self, request, key=None):
        cross_origin = request.META.get('HTTP_ORIGIN')
        if cross_origin is not None:
            try:
                if request.META['HTTP_HOST'] == urlparse(
                        cross_origin).hostname:
                    cross_origin = None
            except ValueError:
                pass

        increment_cache_key(
            'api_updates_fetch_requests%s' %
            ('_cross_origin' if cross_origin is not None else ''))

        from c3nav.site.models import SiteUpdate

        result = {
            'last_site_update': SiteUpdate.last_update(),
            'last_map_update': MapUpdate.current_processed_cache_key(),
        }
        if cross_origin is None:
            result.update({
                'user': get_user_data(request),
            })

        response = Response(result)
        if cross_origin is not None:
            response['Access-Control-Allow-Origin'] = cross_origin
            response['Access-Control-Allow-Credentials'] = 'true'
        set_tile_access_cookie(request, response)

        return response
Beispiel #4
0
 def wrapped_func(self, request, *args, **kwargs):
     response = func(self, request, *args, **kwargs)
     if response.status_code < 400 and kwargs:
         name, value = next(iter(kwargs.items()))
         for value in api_stats_clean_location_value(value):
             increment_cache_key('apistats__%s__%s__%s' %
                                 (view_name, name, value))
     return response
Beispiel #5
0
    def locate(self, request, *args, **kwargs):
        try:
            location = Locator.load().locate(request.data, permissions=AccessPermission.get_for_request(request))
            if location is not None:
                increment_cache_key('apistats__locate__%s' % location.pk)
        except ValidationError:
            return Response({
                'errors': (_('Invalid scan data.'),),
            }, status=400)

        return Response({'location': None if location is None else location.serialize(simple_geometry=True)})
Beispiel #6
0
    def route(self, request, *args, **kwargs):
        params = request.POST if request.method == 'POST' else request.GET
        form = RouteForm(params, request=request)

        if not form.is_valid():
            return Response({
                'errors': form.errors,
            }, status=400)

        options = RouteOptions.get_for_request(request)
        try:
            options.update(params, ignore_unknown=True)
        except ValidationError as e:
            return Response({
                'errors': (str(e), ),
            }, status=400)

        try:
            route = Router.load().get_route(
                origin=form.cleaned_data['origin'],
                destination=form.cleaned_data['destination'],
                permissions=AccessPermission.get_for_request(request),
                options=options)
        except NotYetRoutable:
            return Response({
                'error': _('Not yet routable, try again shortly.'),
            })
        except LocationUnreachable:
            return Response({
                'error': _('Unreachable location.'),
            })
        except NoRouteFound:
            return Response({
                'error': _('No route found.'),
            })

        origin_values = api_stats_clean_location_value(
            form.cleaned_data['origin'].pk)
        destination_values = api_stats_clean_location_value(
            form.cleaned_data['destination'].pk)
        increment_cache_key('apistats__route')
        for origin_value in origin_values:
            for destination_value in destination_values:
                increment_cache_key('apistats__route_tuple_%s_%s' %
                                    (origin_value, destination_value))
        for value in origin_values:
            increment_cache_key('apistats__route_origin_%s' % value)
        for value in destination_values:
            increment_cache_key('apistats__route_destination_%s' % value)

        return Response({
            'request': {
                'origin': form.cleaned_data['origin'].pk,
                'destination': form.cleaned_data['destination'].pk,
            },
            'options':
            options.serialize(),
            'result':
            route.serialize(locations=visible_locations_for_request(request)),
        })
Beispiel #7
0
    def locate(self, request, *args, **kwargs):
        try:
            location = Locator.load().locate(
                request.data,
                permissions=AccessPermission.get_for_request(request))
            if location is not None:
                increment_cache_key('apistats__locate__%s' % location.pk)
        except ValidationError:
            return Response({
                'errors': (_('Invalid scan data.'), ),
            },
                            status=400)

        return Response({
            'location':
            None if location is None else location.serialize(
                simple_geometry=True)
        })
Beispiel #8
0
    def route(self, request, *args, **kwargs):
        params = request.POST if request.method == 'POST' else request.GET
        form = RouteForm(params, request=request)

        if not form.is_valid():
            return Response({
                'errors': form.errors,
            }, status=400)

        options = RouteOptions.get_for_request(request)
        try:
            options.update(params, ignore_unknown=True)
        except ValidationError as e:
            return Response({
                'errors': (str(e), ),
            }, status=400)

        try:
            route = Router.load().get_route(origin=form.cleaned_data['origin'],
                                            destination=form.cleaned_data['destination'],
                                            permissions=AccessPermission.get_for_request(request),
                                            options=options)
        except NotYetRoutable:
            return Response({
                'error': _('Not yet routable, try again shortly.'),
            })
        except LocationUnreachable:
            return Response({
                'error': _('Unreachable location.'),
            })
        except NoRouteFound:
            return Response({
                'error': _('No route found.'),
            })

        origin_values = api_stats_clean_location_value(form.cleaned_data['origin'].pk)
        destination_values = api_stats_clean_location_value(form.cleaned_data['destination'].pk)
        increment_cache_key('apistats__route')
        for origin_value in origin_values:
            for destination_value in destination_values:
                increment_cache_key('apistats__route_tuple_%s_%s' % (origin_value, destination_value))
        for value in origin_values:
            increment_cache_key('apistats__route_origin_%s' % value)
        for value in destination_values:
            increment_cache_key('apistats__route_destination_%s' % value)

        return Response({
            'request': {
                'origin': form.cleaned_data['origin'].pk,
                'destination': form.cleaned_data['destination'].pk,
            },
            'options': options.serialize(),
            'result': route.serialize(locations=visible_locations_for_request(request)),
        })
Beispiel #9
0
    def locate(self, request, *args, **kwargs):
        if isinstance(request.data, list):
            stations_data = request.data
            data = {}
        else:
            data = request.data
            if 'stations' not in data:
                return Response({
                    'errors': (_('stations is missing.'), ),
                },
                                status=400)
            stations_data = data['stations']

        try:
            location = Locator.load().locate(
                stations_data,
                permissions=AccessPermission.get_for_request(request))
            if location is not None:
                increment_cache_key('apistats__locate__%s' % location.pk)
        except ValidationError:
            return Response({
                'errors': (_('Invalid scan data.'), ),
            },
                            status=400)

        if 'set_position' in data and location:
            set_position = data['set_position']
            if not set_position.startswith('p:'):
                return Response({
                    'errors': (_('Invalid set_position.'), ),
                },
                                status=400)

            try:
                position = Position.objects.get(secret=set_position[2:])
            except Position.DoesNotExist:
                return Response({
                    'errors': (_('Invalid set_position.'), ),
                },
                                status=400)

            form_data = {
                **data,
                'coordinates_id':
                None if location is None else location.pk,
            }

            form = PositionAPIUpdateForm(instance=position,
                                         data=form_data,
                                         request=request)

            if not form.is_valid():
                return Response({
                    'errors': form.errors,
                }, status=400)

            form.save()

        return Response({
            'location':
            None if location is None else location.serialize(
                simple_geometry=True)
        })