# This file is part of photo21 # Copyright (C) 2021-2022 Amicale des élèves de l'ENS Paris-Saclay # SPDX-License-Identifier: GPL-3.0-or-later import os from django.conf import settings from django.contrib.auth import get_user_model from django.contrib.auth.mixins import LoginRequiredMixin from django.http import FileResponse, Http404 from django.views.generic import ListView, View from photologue.models import Gallery, Photo, Video class MediaAccess(View): def get(self, request, path): if not request.user.is_authenticated: from django.contrib.auth.views import redirect_to_login try: # Direct match (original photo file) allowed = Photo.objects.filter( image=path, galleries__is_public=True, ).exists() # Cache files (thumbnails/display) are derived from original photos if not allowed and '/cache/' in path: original_dir = os.path.dirname(os.path.dirname(path)) allowed = Photo.objects.filter( image__startswith=original_dir + '/', galleries__is_public=True, ).exists() # Video files and their thumbnails if not allowed: allowed = ( Video.objects.filter(file=path, galleries__is_public=True).exists() or Video.objects.filter(thumbnail=path, galleries__is_public=True).exists() ) except Exception: return redirect_to_login(request.get_full_path()) if not allowed: return redirect_to_login(request.get_full_path()) media_root = os.path.realpath(settings.MEDIA_ROOT) file_path = os.path.realpath(os.path.join(media_root, path)) if not file_path.startswith(media_root + os.sep): raise Http404 if not os.path.isfile(file_path): raise Http404 f = open(file_path, 'rb') try: response = FileResponse(f) response['Cache-Control'] = 'max-age=2678400' return response except Exception: f.close() raise class IndexView(LoginRequiredMixin, ListView): queryset = Gallery.objects.all() paginate_by = 4 template_name = "index.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # Get superusers user_model = get_user_model() superusers = user_model.objects.filter(is_superuser=True) context["superusers"] = superusers return context def oauth_context(request): return { "OAUTH_BUTTON_TEXT": settings.OAUTH_BUTTON_TEXT, "OAUTH_BUTTON_IMAGE": settings.OAUTH_BUTTON_IMAGE, "SOCIALACCOUNT_ONLY": settings.OAUTH_ONLY, }