team-3/src/c3nav/mapdata/api.py

187 lines
7.3 KiB
Python
Raw Normal View History

import mimetypes
2017-05-11 19:36:49 +02:00
from itertools import chain
2017-05-05 16:37:03 +02:00
2017-05-12 12:55:23 +02:00
from django.db.models import Q
2017-05-11 19:36:49 +02:00
from django.http import HttpResponse
from django.shortcuts import redirect
2017-05-11 19:36:49 +02:00
from django.utils.translation import ugettext_lazy as _
2017-01-13 21:52:44 +01:00
from rest_framework.decorators import detail_route, list_route
2017-05-11 19:36:49 +02:00
from rest_framework.exceptions import NotFound, ValidationError
2017-05-11 21:30:29 +02:00
from rest_framework.mixins import RetrieveModelMixin
from rest_framework.response import Response
2017-05-11 21:30:29 +02:00
from rest_framework.viewsets import GenericViewSet, ReadOnlyModelViewSet
2017-05-11 19:36:49 +02:00
from c3nav.mapdata.models import Building, Door, Hole, LocationGroup, Source, Space
from c3nav.mapdata.models.geometry.section import SECTION_MODELS
2017-06-09 15:22:30 +02:00
from c3nav.mapdata.models.geometry.space import SPACE_MODELS, Area, Column, LineObstacle, Obstacle, Point, Stair
from c3nav.mapdata.models.locations import LOCATION_MODELS, Location, LocationRedirect, LocationSlug
2017-05-07 12:06:13 +02:00
from c3nav.mapdata.models.section import Section
2017-05-11 19:36:49 +02:00
class MapdataViewSet(ReadOnlyModelViewSet):
2017-05-11 21:30:29 +02:00
def list(self, request, *args, **kwargs):
2017-05-11 19:36:49 +02:00
qs = self.get_queryset()
geometry = ('geometry' in request.GET)
if qs.model in SECTION_MODELS and 'section' in request.GET:
if not request.GET['section'].isdigit():
raise ValidationError(detail={'detail': _('%s is not an integer.') % 'section'})
try:
section = Section.objects.get(pk=request.GET['section'])
except Section.DoesNotExist:
raise NotFound(detail=_('section not found.'))
qs = qs.filter(section=section)
if qs.model in SPACE_MODELS and 'space' in request.GET:
if not request.GET['space'].isdigit():
raise ValidationError(detail={'detail': _('%s is not an integer.') % 'space'})
try:
space = Space.objects.get(pk=request.GET['space'])
except Space.DoesNotExist:
raise NotFound(detail=_('space not found.'))
2017-05-11 19:36:49 +02:00
qs = qs.filter(space=space)
return Response([obj.serialize(geometry=geometry) for obj in qs.order_by('id')])
2017-05-11 21:30:29 +02:00
def retrieve(self, request, *args, **kwargs):
2017-05-11 19:36:49 +02:00
return Response(self.get_object().serialize())
2017-05-11 21:30:29 +02:00
@staticmethod
def list_types(models_list, **kwargs):
return Response([
2017-05-11 21:30:29 +02:00
model.serialize_type(**kwargs) for model in models_list
])
2017-05-11 19:36:49 +02:00
class SectionViewSet(MapdataViewSet):
queryset = Section.objects.all()
2016-12-07 16:11:33 +01:00
2017-05-11 19:36:49 +02:00
@list_route(methods=['get'])
def geometrytypes(self, request):
2017-05-11 21:30:29 +02:00
return self.list_types(SECTION_MODELS)
2016-12-07 16:11:33 +01:00
2017-05-12 23:37:03 +02:00
@detail_route(methods=['get'])
def svg(self, requests, pk=None):
section = self.get_object()
response = HttpResponse(section.render_svg(), 'image/svg+xml')
return response
2016-12-19 16:54:11 +01:00
2017-05-11 19:36:49 +02:00
class BuildingViewSet(MapdataViewSet):
""" Add ?geometry=1 to get geometries, add ?section=<id> to filter by section. """
queryset = Building.objects.all()
2016-12-06 23:43:57 +01:00
2016-12-19 16:54:11 +01:00
2017-05-11 19:36:49 +02:00
class SpaceViewSet(MapdataViewSet):
""" Add ?geometry=1 to get geometries, add ?section=<id> to filter by section. """
queryset = Space.objects.all()
2016-12-08 12:36:09 +01:00
2017-05-11 19:36:49 +02:00
@list_route(methods=['get'])
def geometrytypes(self, request):
2017-05-11 21:30:29 +02:00
return self.list_types(SPACE_MODELS)
2016-12-06 23:43:57 +01:00
2017-05-11 19:36:49 +02:00
class DoorViewSet(MapdataViewSet):
""" Add ?geometry=1 to get geometries, add ?section=<id> to filter by section. """
queryset = Door.objects.all()
class HoleViewSet(MapdataViewSet):
2017-06-08 15:19:12 +02:00
""" Add ?geometry=1 to get geometries, add ?space=<id> to filter by space. """
2017-05-11 19:36:49 +02:00
queryset = Hole.objects.all()
class AreaViewSet(MapdataViewSet):
""" Add ?geometry=1 to get geometries, add ?space=<id> to filter by space. """
queryset = Area.objects.all()
class StairViewSet(MapdataViewSet):
""" Add ?geometry=1 to get geometries, add ?space=<id> to filter by space. """
queryset = Stair.objects.all()
class ObstacleViewSet(MapdataViewSet):
""" Add ?geometry=1 to get geometries, add ?space=<id> to filter by space. """
queryset = Obstacle.objects.all()
class LineObstacleViewSet(MapdataViewSet):
""" Add ?geometry=1 to get geometries, add ?space=<id> to filter by space. """
queryset = LineObstacle.objects.all()
2017-06-09 15:22:30 +02:00
class ColumnViewSet(MapdataViewSet):
""" Add ?geometry=1 to get geometries, add ?space=<id> to filter by space. """
queryset = Column.objects.all()
2017-05-11 19:36:49 +02:00
class PointViewSet(MapdataViewSet):
""" Add ?geometry=1 to get geometries, add ?space=<id> to filter by space. """
queryset = Point.objects.all()
class LocationGroupViewSet(MapdataViewSet):
queryset = LocationGroup.objects.all()
2017-05-11 21:30:29 +02:00
class LocationViewSet(RetrieveModelMixin, GenericViewSet):
2017-05-12 12:55:23 +02:00
"""
only accesses locations that have can_search or can_describe set to true.
2017-05-12 13:21:41 +02:00
add ?detailed=1 to show all attributes.
2017-05-12 12:55:23 +02:00
/{id}/ add ?show_redirect=1 to suppress redirects and show them as JSON.
/search/ only accesses locations that have can_search set to true. Add GET Parameter s to search.
"""
2017-05-11 19:36:49 +02:00
queryset = LocationSlug.objects.all()
lookup_field = 'slug'
2017-05-12 12:55:23 +02:00
def list(self, request, *args, **kwargs):
queryset = sorted(chain(*(model.objects.filter(Q(can_search=True) | Q(can_describe=True))
for model in LOCATION_MODELS)), key=lambda obj: obj.id)
2017-05-12 13:21:41 +02:00
return Response([obj.serialize(include_type=True, detailed='detailed' in request.GET) for obj in queryset])
2017-05-12 12:55:23 +02:00
def retrieve(self, request, slug=None, *args, **kwargs):
result = Location.get_by_slug(slug, self.get_queryset())
if result is None:
raise NotFound
2017-05-27 18:33:16 +02:00
result = result.get_child()
if isinstance(result, LocationRedirect):
if 'show_redirects' in request.GET:
return Response(result.serialize(include_type=True))
return redirect('../'+result.target.slug) # todo: why does redirect/reverse not work here?
2017-05-27 18:33:16 +02:00
return Response(result.serialize(include_type=True, detailed='detailed' in request.GET))
2017-05-11 21:30:29 +02:00
@list_route(methods=['get'])
def types(self, request):
return MapdataViewSet.list_types(LOCATION_MODELS, geomtype=False)
2017-05-12 12:54:50 +02:00
@list_route(methods=['get'])
def redirects(self, request):
return Response([obj.serialize(include_type=False) for obj in LocationRedirect.objects.all().order_by('id')])
2017-05-12 13:49:42 +02:00
@list_route(methods=['get'])
def search(self, request):
# todo: implement caching here
results = sorted(chain(*(model.objects.filter(can_search=True)
2017-05-13 16:42:39 +02:00
for model in LOCATION_MODELS)), key=lambda obj: obj.id)
2017-05-12 13:49:42 +02:00
search = request.GET.get('s')
if not search:
return Response([obj.serialize(include_type=True, detailed='detailed' in request.GET) for obj in results])
words = search.lower().split(' ')[:10]
for word in words:
results = [r for r in results if (word in r.title.lower() or (r.slug and word in r.slug.lower()))]
# todo: rank results
return Response([obj.serialize(include_type=True, detailed='detailed' in request.GET) for obj in results])
2017-05-12 01:21:53 +02:00
class SourceViewSet(MapdataViewSet):
queryset = Source.objects.all()
@detail_route(methods=['get'])
2017-05-11 19:36:49 +02:00
def image(self, request, pk=None):
return self._image(request, pk=pk)
2016-12-07 16:11:33 +01:00
2017-05-11 19:36:49 +02:00
def _image(self, request, pk=None):
source = self.get_object()
response = HttpResponse(content_type=mimetypes.guess_type(source.name)[0])
response.write(source.image)
return response