delete old stuff from mapdata

This commit is contained in:
Laura Klünder 2017-05-12 01:21:53 +02:00
parent 9d67cdcb75
commit 92003080ed
11 changed files with 14 additions and 199 deletions

View file

@ -1,12 +0,0 @@
from rest_framework.authentication import SessionAuthentication
class ForceCSRFCheckSessionAuthentication(SessionAuthentication):
def authenticate(self, request):
result = super().authenticate(request)
if result is None:
self.enforce_csrf(request)
return result

View file

@ -10,14 +10,11 @@ from rest_framework.mixins import RetrieveModelMixin
from rest_framework.response import Response from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet, ReadOnlyModelViewSet from rest_framework.viewsets import GenericViewSet, ReadOnlyModelViewSet
from c3nav.access.apply import filter_queryset_by_access
from c3nav.mapdata.models import Building, Door, Hole, LocationGroup, Source, Space from c3nav.mapdata.models import Building, Door, Hole, LocationGroup, Source, Space
from c3nav.mapdata.models.geometry.section import SECTION_MODELS from c3nav.mapdata.models.geometry.section import SECTION_MODELS
from c3nav.mapdata.models.geometry.space import SPACE_MODELS, Area, LineObstacle, Obstacle, Point, Stair from c3nav.mapdata.models.geometry.space import SPACE_MODELS, Area, LineObstacle, Obstacle, Point, Stair
from c3nav.mapdata.models.locations import LOCATION_MODELS, Location, LocationRedirect, LocationSlug from c3nav.mapdata.models.locations import LOCATION_MODELS, Location, LocationRedirect, LocationSlug
from c3nav.mapdata.models.section import Section from c3nav.mapdata.models.section import Section
from c3nav.mapdata.serializers.main import SourceSerializer
from c3nav.mapdata.utils.cache import CachedReadOnlyViewSetMixin
class MapdataViewSet(ReadOnlyModelViewSet): class MapdataViewSet(ReadOnlyModelViewSet):
@ -157,12 +154,8 @@ class LocationViewSet(RetrieveModelMixin, GenericViewSet):
return MapdataViewSet.list_types(LOCATION_MODELS, geomtype=False) return MapdataViewSet.list_types(LOCATION_MODELS, geomtype=False)
class SourceViewSet(CachedReadOnlyViewSetMixin, ReadOnlyModelViewSet): class SourceViewSet(MapdataViewSet):
queryset = Source.objects.all() queryset = Source.objects.all()
serializer_class = SourceSerializer
def get_queryset(self):
return filter_queryset_by_access(self.request, super().get_queryset().all())
@detail_route(methods=['get']) @detail_route(methods=['get'])
def image(self, request, pk=None): def image(self, request, pk=None):

View file

@ -28,7 +28,7 @@ class Migration(migrations.Migration):
'verbose_name_plural': 'Areas of Interest', 'verbose_name_plural': 'Areas of Interest',
'verbose_name': 'Area of Interest', 'verbose_name': 'Area of Interest',
}, },
bases=(models.Model, c3nav.mapdata.models.locations.LocationModelMixin), bases=(models.Model, ),
), ),
migrations.CreateModel( migrations.CreateModel(
name='GroupOfInterest', name='GroupOfInterest',
@ -43,7 +43,7 @@ class Migration(migrations.Migration):
'verbose_name_plural': 'Groups of Interest', 'verbose_name_plural': 'Groups of Interest',
'verbose_name': 'Group of Interest', 'verbose_name': 'Group of Interest',
}, },
bases=(models.Model, c3nav.mapdata.models.locations.LocationModelMixin), bases=(models.Model, ),
), ),
migrations.AddField( migrations.AddField(
model_name='areaofinterest', model_name='areaofinterest',

View file

@ -39,10 +39,6 @@ class LocationSlug(SerializableMixin, models.Model):
default_related_name = 'locationslugs' default_related_name = 'locationslugs'
class LocationModelMixin:
pass
class Location(LocationSlug, EditorFormMixin, models.Model): class Location(LocationSlug, EditorFormMixin, models.Model):
titles = JSONField(default={}) titles = JSONField(default={})
can_search = models.BooleanField(default=True, verbose_name=_('can be searched')) can_search = models.BooleanField(default=True, verbose_name=_('can be searched'))
@ -97,12 +93,10 @@ class Location(LocationSlug, EditorFormMixin, models.Model):
@property @property
def title(self): def title(self):
if not hasattr(self, 'titles'):
return self.name
lang = get_language() lang = get_language()
if lang in self.titles: if lang in self.titles:
return self.titles[lang] return self.titles[lang]
return next(iter(self.titles.values())) if self.titles else self.name return next(iter(self.titles.values())) if self.titles else (self._meta.verbose_name+' '+(self.slug or self.id))
@property @property
def subtitle(self): def subtitle(self):
@ -130,44 +124,6 @@ class LocationGroup(Location, EditorFormMixin, models.Model):
verbose_name_plural = _('Location Groups') verbose_name_plural = _('Location Groups')
default_related_name = 'locationgroups' default_related_name = 'locationgroups'
@cached_property
def location_id(self):
return 'g:'+self.slug
def get_in_levels(self):
last_update = get_last_mapdata_update()
if last_update is None:
return self._get_in_levels()
cache_key = 'c3nav__mapdata__locationgroup__in_levels__'+last_update.isoformat()+'__'+str(self.id),
in_levels = cache.get(cache_key)
if not in_levels:
in_levels = self._get_in_levels()
cache.set(cache_key, in_levels, 900)
return in_levels
def _get_in_levels(self):
level_ids = set()
in_levels = []
for arealocation in self.arealocations.all():
for area in arealocation.get_in_areas():
if area.location_type == 'level' and area.id not in level_ids:
level_ids.add(area.id)
in_levels.append(area)
in_levels = sorted(in_levels, key=lambda area: area.section.altitude)
return in_levels
@property
def subtitle(self):
if self.compiled_room:
return ', '.join(area.title for area in self.get_in_levels())
return ungettext_lazy('%d location', '%d locations') % self.arealocations.count()
def __str__(self):
return self.title
def _serialize(self, **kwargs): def _serialize(self, **kwargs):
result = super()._serialize(**kwargs) result = super()._serialize(**kwargs)
result['compiled_room'] = self.compiled_room result['compiled_room'] = self.compiled_room
@ -191,61 +147,3 @@ class LocationRedirect(LocationSlug):
class Meta: class Meta:
default_related_name = 'redirect' default_related_name = 'redirect'
class PointLocation:
def __init__(self, section: 'Section', x: int, y: int, request):
self.section = section
self.x = x
self.y = y
self.request = request
@cached_property
def location_id(self):
return 'c:%d:%d:%d' % (self.section.id, self.x * 100, self.y * 100)
@cached_property
def xy(self):
return np.array((self.x, self.y))
@cached_property
def description(self):
from c3nav.routing.graph import Graph
graph = Graph.load()
point = graph.get_nearest_point(self.section, self.x, self.y)
if point is None or (':nonpublic' in point.arealocations and not self.request.c3nav_full_access and
not len(set(self.request.c3nav_access_list) & set(point.arealocations))):
return _('Unreachable Coordinates'), ''
AreaLocation = None
locations = sorted(AreaLocation.objects.filter(name__in=point.arealocations, can_describe=True),
key=AreaLocation.get_sort_key, reverse=True)
if not locations:
return _('Coordinates'), ''
location = locations[0]
if location.contains(self.x, self.y):
return (_('Coordinates in %(location)s') % {'location': location.title}), location.subtitle_without_type
else:
return (_('Coordinates near %(location)s') % {'location': location.title}), location.subtitle_without_type
@property
def title(self) -> str:
return self.description[0]
@property
def subtitle(self) -> str:
add_subtitle = self.description[1]
subtitle = '%s:%d:%d' % (self.section.name, self.x * 100, self.y * 100)
if add_subtitle:
subtitle += ' - '+add_subtitle
return subtitle
def to_location_json(self):
result = super().to_location_json()
result['section'] = self.section.id
result['x'] = self.x
result['y'] = self.y
return result

View file

@ -27,6 +27,13 @@ class Source(EditorFormMixin, models.Model):
return ((float(result['bottom__min']), float(result['left__min'])), return ((float(result['bottom__min']), float(result['left__min'])),
(float(result['top__max']), float(result['right__max']))) (float(result['top__max']), float(result['right__max'])))
def _serialize(self, section=True, **kwargs):
result = super()._serialize(**kwargs)
result['name'] = self.name
result['bounds'] = self.bounds
return result
@property @property
def bounds(self): def bounds(self):
# noinspection PyTypeChecker
return (float(self.bottom), float(self.left)), (float(self.top), float(self.right)) return (float(self.bottom), float(self.left)), (float(self.top), float(self.right))

View file

@ -1,27 +1,7 @@
import re
from django.db.models import Q from django.db.models import Q
from c3nav.access.apply import filter_arealocations_by_access, filter_queryset_by_access from c3nav.access.apply import filter_arealocations_by_access, filter_queryset_by_access
from c3nav.mapdata.models import LocationGroup from c3nav.mapdata.models import LocationGroup
from c3nav.mapdata.models.locations import PointLocation
from c3nav.mapdata.utils.cache import get_sections_cached
def get_location(request, location_id):
match = re.match('^c:(?P<section>[0-9]+):(?P<x>[0-9]+):(?P<y>[0-9]+)$', location_id)
if match:
levels = get_sections_cached()
section = levels.get(int(match.group('section')))
if section is None:
return None
return PointLocation(section=section, x=int(match.group('x')) / 100, y=int(match.group('y')) / 100, request=request)
if location_id.startswith('g:'):
queryset = LocationGroup.objects.filter(Q(slug=location_id[2:], can_search=True))
return filter_queryset_by_access(request, queryset).first()
return filter_arealocations_by_access(request, AreaLocation.objects.filter(slug=location_id, can_search=True)).first()
def filter_words(queryset, words): def filter_words(queryset, words):

View file

@ -1,26 +0,0 @@
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from shapely.geometry import mapping, shape
from c3nav.mapdata.utils.json import format_geojson
class GeometryField(serializers.DictField):
"""
shapely geometry objects serialized using GeoJSON
"""
default_error_messages = {
'invalid': _('Invalid GeoJSON.')
}
def to_representation(self, obj):
geojson = format_geojson(mapping(obj), round=False)
return super().to_representation(geojson)
def to_internal_value(self, data):
geojson = super().to_internal_value(data)
try:
return shape(geojson)
except:
raise ValidationError(_('Invalid GeoJSON.'))

View file

@ -1,26 +0,0 @@
from rest_framework import serializers
from c3nav.mapdata.models.section import Section
from c3nav.mapdata.models.source import Source
class SectionSerializer(serializers.ModelSerializer):
titles = serializers.DictField()
class Meta:
model = Section
fields = ('id', 'name', 'altitude', 'slug', 'public', 'titles', 'can_search', 'can_search', 'color')
class LocationSerializer(serializers.ModelSerializer):
titles = serializers.DictField()
class Meta:
model = Section
fields = ('id', 'name', 'slug', 'public', 'titles', 'can_search', 'can_search', 'color')
class SourceSerializer(serializers.ModelSerializer):
class Meta:
model = Source
fields = ('id', 'name', 'bounds')

View file

@ -8,7 +8,7 @@ from django.conf import settings
from scipy.sparse.csgraph._shortest_path import shortest_path from scipy.sparse.csgraph._shortest_path import shortest_path
from scipy.sparse.csgraph._tools import csgraph_from_dense from scipy.sparse.csgraph._tools import csgraph_from_dense
from c3nav.mapdata.models.locations import Location, LocationGroup, PointLocation from c3nav.mapdata.models.locations import Location, LocationGroup
from c3nav.mapdata.models.section import Section from c3nav.mapdata.models.section import Section
from c3nav.routing.connection import GraphConnection from c3nav.routing.connection import GraphConnection
from c3nav.routing.exceptions import AlreadyThere, NoRouteFound, NotYetRoutable from c3nav.routing.exceptions import AlreadyThere, NoRouteFound, NotYetRoutable

View file

@ -11,7 +11,7 @@ from c3nav.access.apply import get_visible_areas
from c3nav.mapdata.inclusion import get_includables_avoidables, parse_include_avoid from c3nav.mapdata.inclusion import get_includables_avoidables, parse_include_avoid
from c3nav.mapdata.lastupdate import get_last_mapdata_update from c3nav.mapdata.lastupdate import get_last_mapdata_update
from c3nav.mapdata.models.section import Section from c3nav.mapdata.models.section import Section
from c3nav.mapdata.search import get_location, search_location from c3nav.mapdata.search import search_location
from c3nav.mapdata.utils.cache import get_sections_cached from c3nav.mapdata.utils.cache import get_sections_cached
from c3nav.mapdata.utils.misc import get_dimensions, get_render_path from c3nav.mapdata.utils.misc import get_dimensions, get_render_path
from c3nav.routing.exceptions import AlreadyThere, NoRouteFound, NotYetRoutable from c3nav.routing.exceptions import AlreadyThere, NoRouteFound, NotYetRoutable
@ -40,6 +40,7 @@ def get_location_or_404(request, location):
if location is None: if location is None:
return None return None
get_location = None
location = get_location(request, location) location = get_location(request, location)
if location is None: if location is None:
raise Http404 raise Http404