muistox/gallery/views/main.py

64 lines
2.5 KiB
Python

import os
import re
from django.conf import settings
from django.core.cache import cache
from django.core.paginator import Paginator
from django.db.models import Count, F, Q, Sum
from django.http import JsonResponse
from django.shortcuts import get_object_or_404, redirect
from django.urls import reverse
from django.views import View
from django.views.generic import DetailView, ListView, TemplateView
from ..models import Album, Photo, Redir
class Main(TemplateView):
"""Main homepage."""
template_name = "gallery/main.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['canonical_url'] = self.request.build_absolute_uri(reverse('gallery:main_url'))
context['latest_albums'] = Album.objects.filter(is_public=True).order_by('-album_date')[:6]
return context
class About(TemplateView):
"""Static about page."""
template_name = "gallery/about.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['canonical_url'] = self.request.build_absolute_uri(reverse('gallery:about_url'))
return context
def redirect_to_album(request, redir_path):
"""Redirect old album or photo URLs to new structure, including pagination and photos."""
photo_extensions = ['.jpg', '.jpeg']
# 1. Tarkista vanha pagination-muoto: Album_Name/page/3/
page_match = re.match(r'^(?P<album_path>.+)/page/(?P<page_number>\d+)/?$', redir_path)
if page_match:
album_path = page_match.group('album_path')
page_number = page_match.group('page_number')
redir = get_object_or_404(Redir, path=album_path)
return redirect(f'/albums/{redir.album.slug}/?page={page_number}')
# 2. Tarkista, onko kyseessä kuvan URL (tiedoston pääte)
_, ext = os.path.splitext(redir_path.lower())
if ext in photo_extensions:
# Erotellaan albumin nimi ja kuvan tiedostonimi
album_path, photo_filename = redir_path.rsplit('/', 1)
redir = get_object_or_404(Redir, path=album_path)
album = redir.album
photo = Photo.objects.filter(album=album, slug=photo_filename).first()
if photo:
return redirect('gallery:photo_url', album_slug=album.slug, photo_slug=photo.slug)
return redirect('gallery:album_url', album_slug=album.slug)
# 3. Oletus: pelkkä albuminimi
redir = get_object_or_404(Redir, path=redir_path)
return redirect('gallery:album_url', album_slug=redir.album.slug)