views.py 3.38 KB
Newer Older
1
"""Views provided by the documents package"""
Sébastiaan Versteeg's avatar
Sébastiaan Versteeg committed
2
3
import os

Thom Wiggers's avatar
Thom Wiggers committed
4
from django.conf import settings
5
6
7
from django.core.exceptions import PermissionDenied
from django.http import Http404, HttpResponse
from django.shortcuts import redirect
8
from django.utils import timezone
9
from django.utils.text import slugify
10
from django.utils.translation import get_language
11
from django.views.generic import TemplateView, DetailView
12
from sendfile import sendfile
13

Tom van Bussel's avatar
Tom van Bussel committed
14
15
from documents.models import (AnnualDocument, AssociationDocument,
                              GeneralMeeting, Document)
Sébastiaan Versteeg's avatar
Sébastiaan Versteeg committed
16
from utils.snippets import datetime_to_lectureyear
17
18


19
class DocumentsIndexView(TemplateView):
20
21
22
    """
    View that renders the documents index page
    """
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
    template_name = 'documents/index.html'

    def get_context_data(self, **kwargs) -> dict:
        lecture_year = datetime_to_lectureyear(timezone.now())

        years = {x: {} for x in reversed(range(1990, lecture_year + 1))}
        for year in years:
            years[year] = {
                'documents': {
                    'policy': None,
                    'report': None,
                    'financial': None
                },
                'general_meetings': []
            }

        for document in AnnualDocument.objects.filter(subcategory='policy'):
            years[document.year]['documents']['policy'] = document
        for document in AnnualDocument.objects.filter(subcategory='report'):
            years[document.year]['documents']['report'] = document
        for document in AnnualDocument.objects.filter(subcategory='financial'):
            years[document.year]['documents']['financial'] = document

        for obj in GeneralMeeting.objects.all():
            meeting_year = datetime_to_lectureyear(obj.datetime)
            years[meeting_year]['general_meetings'].append(obj)

        context = super().get_context_data(**kwargs)
        context.update({
            'association_documents': AssociationDocument.objects.order_by(
                f'name_{get_language()}').all(),
            'years': list(years.items())
        })
        return context


class DocumentDownloadView(DetailView):
60
61
62
63
    """
    View that allows you to download a specific document based on it's and your
    permissions settings
    """
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
    model = Document

    def get(self, request, *args, **kwargs) -> HttpResponse:
        """
        :return: either a 302 redirect to the login page or
        a 200 with the document
        """
        response = super().get(request, *args, **kwargs)
        document = response.context_data['document']

        if (document.members_only and
                not request.user.is_authenticated):
            return redirect(
                '{}?next={}'.format(settings.LOGIN_URL, request.path))
        elif (document.members_only and
              not request.member.has_active_membership()):
            raise PermissionDenied

        lang = request.GET.get('language')
        try:
            if lang == 'nl':
                file = document.file_nl
            elif lang == 'en':
                file = document.file_en
            else:  # Fall back on language detection
                file = document.file
        except ValueError:
            raise Http404('This document does not exist.')

        ext = os.path.splitext(file.path)[1]

        return sendfile(request, file.path, attachment=True,
                        attachment_filename=slugify(document.name) + ext)