<commit_before>from django.conf import settings
from django.http import HttpResponse, Http404
from django.utils.decorators import method_decorator
from django.utils.html import escape
from django.utils import translation
from django.views.generic import CreateView, ListView
from django.views.generic.detail import BaseDetailView
from django.contrib.auth.decorators import login_required

from djgeojson.views import GeoJSONLayerView
from mapentity.views import (MapEntityLayer, MapEntityList, MapEntityJsonList, MapEntityFormat,
                             MapEntityDetail, MapEntityMapImage, MapEntityDocument, MapEntityCreate, MapEntityUpdate, MapEntityDelete,
                             LastModifiedMixin, MapEntityViewSet)
from mapentity.helpers import alphabet_enumeration
from paperclip.models import Attachment
from rest_framework import permissions as rest_permissions

from geotrek.core.models import AltimetryMixin
from geotrek.core.views import CreateFromTopologyMixin

from geotrek.authent.decorators import same_structure_required
from geotrek.common.utils import plain_text_preserve_linebreaks
from geotrek.common.views import FormsetMixin, DocumentPublic
from geotrek.zoning.models import District, City, RestrictedArea
from geotrek.tourism.views import InformationDeskGeoJSON

from .models import Trek, POI, WebLink
from .filters import TrekFilterSet, POIFilterSet
from .forms import TrekForm, TrekRelationshipFormSet, POIForm, WebLinkCreateFormPopup
from .serializers import (TrekGPXSerializer, TrekSerializer, POISerializer,
                          CirkwiTrekSerializer, CirkwiPOISerializer)


class FlattenPicturesMixin(object):
    def get_template_names(self):
        """ Due to bug in Django, providing get_queryset() method hides
        template_names lookup.
        https://code.djangoproject.com/ticket/17484
        """
        opts = self.get_model()._meta
        extra = ["%s/%s%s.html" % (opts.app_label, opts.object_name.lower(), self.template_name_suffix)]
        return extra + super(FlattenPicturesMixin, self).get_template_names()

    def get_queryset(self):
        """ Override queryset to avoid attachment lookup while serializing.
        It will fetch attachments, and force ``pictures`` attribute of instances.
        """
        app_label = self.get_model()._meta.app_label
        model_name = self.get_model()._meta.object_name.lower()
        attachments = Attachment.objects.filter(content_type__app_label=app_label,
                                                content_type__model=model_name)
        pictures = {}
        for attachment in attachments:
            if attachment.is_image:
                obj_id = attachment.object_id
                pictures.setdefault(obj_id, []).append(attachment)

        for obj in super(FlattenPicturesMixin, self).get_queryset():
            obj.pictures = pictures.get(obj.id, [])
            yield obj


class TrekLayer(MapEntityLayer):
    properties = ['name', 'published']
    queryset = Trek.objects.existing()


class TrekList(FlattenPicturesMixin, MapEntityList):
    queryset = Trek.objects.existing()
    filterform = TrekFilterSet
    columns = ['id', 'name', 'duration', 'difficulty', 'departure', 'thumbnail']


class TrekJsonList(MapEntityJsonList, TrekList):
    pass


class TrekFormatList(MapEntityFormat, TrekList):
    columns = [
        'id', 'name', 'departure', 'arrival', 'duration',
        'duration_pretty', 'description', 'description_teaser',
        'networks', 'advice', 'ambiance', 'difficulty',
        'information_desks', 'themes', 'practice', 'accessibilities', 'access',
        'route', 'public_transport', 'advised_parking',
        'web_links', 'is_park_centered', 'disabled_infrastructure',
        'parking_location', 'points_reference', 'related', 'pois',
        'review', 'published', 'publication_date',
        'structure', 'date_insert', 'date_update',
        'cities', 'districts', 'areas', 'source',
    ] + AltimetryMixin.COLUMNS


class TrekGPXDetail(LastModifiedMixin, BaseDetailView):
    queryset = Trek.objects.existing()

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(TrekGPXDetail, self).dispatch(*args, **kwargs)

    def render_to_response(self, context):
        gpx_serializer = TrekGPXSerializer()
        response = HttpResponse(mimetype='application/gpx+xml')
        response['Content-Disposition'] = 'attachment; filename=trek-%s.gpx' % self.get_object().pk
        gpx_serializer.serialize([self.get_object()], stream=response, geom_field='geom')
        return response


class TrekKMLDetail(LastModifiedMixin, BaseDetailView):
    queryset = Trek.objects.existing()

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(TrekKMLDetail, self).dispatch(*args, **kwargs)

    def render_to_response(self, context):
        trek = self.get_object()
        response = HttpResponse(trek.kml(),
                                content_type='application/vnd.google-earth.kml+xml')
        return response

<commit_msg>Anonymous access to GPX/KML of published treks<commit_after>from django.conf import settings
from django.http import HttpResponse, Http404
from django.utils.decorators import method_decorator
from django.utils.html import escape
from django.utils import translation
from django.views.generic import CreateView, ListView
from django.views.generic.detail import BaseDetailView
from django.contrib.auth.decorators import login_required

from djgeojson.views import GeoJSONLayerView
from mapentity.views import (MapEntityLayer, MapEntityList, MapEntityJsonList, MapEntityFormat,
                             MapEntityDetail, MapEntityMapImage, MapEntityDocument, MapEntityCreate, MapEntityUpdate, MapEntityDelete,
                             LastModifiedMixin, MapEntityViewSet)
from mapentity.helpers import alphabet_enumeration
from paperclip.models import Attachment
from rest_framework import permissions as rest_permissions

from geotrek.core.models import AltimetryMixin
from geotrek.core.views import CreateFromTopologyMixin

from geotrek.authent.decorators import same_structure_required
from geotrek.common.utils import plain_text_preserve_linebreaks
from geotrek.common.views import FormsetMixin, PublicOrReadPermMixin, DocumentPublic
from geotrek.zoning.models import District, City, RestrictedArea
from geotrek.tourism.views import InformationDeskGeoJSON

from .models import Trek, POI, WebLink
from .filters import TrekFilterSet, POIFilterSet
from .forms import TrekForm, TrekRelationshipFormSet, POIForm, WebLinkCreateFormPopup
from .serializers import (TrekGPXSerializer, TrekSerializer, POISerializer,
                          CirkwiTrekSerializer, CirkwiPOISerializer)


class FlattenPicturesMixin(object):
    def get_template_names(self):
        """ Due to bug in Django, providing get_queryset() method hides
        template_names lookup.
        https://code.djangoproject.com/ticket/17484
        """
        opts = self.get_model()._meta
        extra = ["%s/%s%s.html" % (opts.app_label, opts.object_name.lower(), self.template_name_suffix)]
        return extra + super(FlattenPicturesMixin, self).get_template_names()

    def get_queryset(self):
        """ Override queryset to avoid attachment lookup while serializing.
        It will fetch attachments, and force ``pictures`` attribute of instances.
        """
        app_label = self.get_model()._meta.app_label
        model_name = self.get_model()._meta.object_name.lower()
        attachments = Attachment.objects.filter(content_type__app_label=app_label,
                                                content_type__model=model_name)
        pictures = {}
        for attachment in attachments:
            if attachment.is_image:
                obj_id = attachment.object_id
                pictures.setdefault(obj_id, []).append(attachment)

        for obj in super(FlattenPicturesMixin, self).get_queryset():
            obj.pictures = pictures.get(obj.id, [])
            yield obj


class TrekLayer(MapEntityLayer):
    properties = ['name', 'published']
    queryset = Trek.objects.existing()


class TrekList(FlattenPicturesMixin, MapEntityList):
    queryset = Trek.objects.existing()
    filterform = TrekFilterSet
    columns = ['id', 'name', 'duration', 'difficulty', 'departure', 'thumbnail']


class TrekJsonList(MapEntityJsonList, TrekList):
    pass


class TrekFormatList(MapEntityFormat, TrekList):
    columns = [
        'id', 'name', 'departure', 'arrival', 'duration',
        'duration_pretty', 'description', 'description_teaser',
        'networks', 'advice', 'ambiance', 'difficulty',
        'information_desks', 'themes', 'practice', 'accessibilities', 'access',
        'route', 'public_transport', 'advised_parking',
        'web_links', 'is_park_centered', 'disabled_infrastructure',
        'parking_location', 'points_reference', 'related', 'pois',
        'review', 'published', 'publication_date',
        'structure', 'date_insert', 'date_update',
        'cities', 'districts', 'areas', 'source',
    ] + AltimetryMixin.COLUMNS


class TrekGPXDetail(LastModifiedMixin, PublicOrReadPermMixin, BaseDetailView):
    queryset = Trek.objects.existing()

    def render_to_response(self, context):
        gpx_serializer = TrekGPXSerializer()
        response = HttpResponse(mimetype='application/gpx+xml')
        response['Content-Disposition'] = 'attachment; filename=trek-%s.gpx' % self.get_object().pk
        gpx_serializer.serialize([self.get_object()], stream=response, geom_field='geom')
        return response


class TrekKMLDetail(LastModifiedMixin, PublicOrReadPermMixin, BaseDetailView):
    queryset = Trek.objects.existing()

    def render_to_response(self, context):
        trek = self.get_object()
        response = HttpResponse(trek.kml(),
                                content_type='application/vnd.google-earth.kml+xml')
        return response


{'fraction_non_alphanumeric': 0.09599198396793587, 'fraction_numerical': 0.0016032064128256513, 'mean_word_length': 3.7778841550981332, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 4}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3362962', 'n_tokens_mistral': 2890, 'n_tokens_neox': 2757, 'n_words': 629}