views.py 2.15 KB
Newer Older
1
from django.shortcuts import get_object_or_404, render
2
from django.contrib.auth.decorators import login_required
3
from django.http import Http404
Joost Rijneveld's avatar
Joost Rijneveld committed
4
from django.conf import settings
5
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
6

7
from .models import Album
Joost Rijneveld's avatar
Joost Rijneveld committed
8
from utils.snippets import sanitize_path
9
from utils.views import _private_thumbnails_unauthed
Joost Rijneveld's avatar
Joost Rijneveld committed
10
11
12

from sendfile import sendfile
import os
13
14
15
16
17
18

COVER_FILENAME = 'cover.jpg'


@login_required
def index(request):
Joost Rijneveld's avatar
Joost Rijneveld committed
19
    albums = Album.objects.all().order_by('-date')
20
21
22
23
24
25
26
27
28
29
30
31

    paginator = Paginator(albums, 12)
    page = request.GET.get('page')
    try:
        albums = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        albums = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        albums = paginator.page(paginator.num_pages)
    return render(request, 'photos/index.html', {'albums': albums})
32
33
34


@login_required
35
36
def album(request, slug):
    album = get_object_or_404(Album, slug=slug)
37
    return render(request, 'photos/album.html', {'album': album})
38
39


40
41
42
43
44
45
46
47
48
49
50
51
52
53
def _checked_shared_album(slug, token):
    album = get_object_or_404(Album, slug=slug)
    if token != album.access_token:
        raise Http404("Invalid token.")
    return album


def shared_album(request, slug, token):
    album = _checked_shared_album(slug, token)
    return render(request, 'photos/album.html', {'album': album})


def _download(request, path):
    """This function provides a layer of indirection for shared albums"""
Joost Rijneveld's avatar
Joost Rijneveld committed
54
55
56
57
58
    path = sanitize_path(path)
    path = os.path.join(settings.MEDIA_ROOT, 'photos', *path.split('/')[1:])
    if not os.path.isfile(path):
        raise Http404("Photo not found.")
    return sendfile(request, path, attachment=True)
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73


@login_required
def download(request, path):
    return _download(request, path)


def shared_download(request, slug, token, path):
    _checked_shared_album(slug, token)
    return _download(request, path)


def shared_thumbnail(request, slug, token, size_fit, path):
    _checked_shared_album(slug, token)
    return _private_thumbnails_unauthed(request, size_fit, path)