Download cover with label.
[redakcja.git] / src / catalogue / views.py
1 # This file is part of FNP-Redakcja, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
3 #
4 from django.apps import apps
5 from django.db.models import Prefetch
6 from django.http import Http404
7 from django.urls import reverse
8 from django.utils.formats import localize_input
9 from django.contrib.auth.decorators import login_required
10 from django.contrib.auth.models import User
11 from django.shortcuts import get_object_or_404, redirect
12 from django.views.decorators.http import require_POST
13 from django.views.generic import DetailView, TemplateView
14 import apiclient
15 from . import models
16 import documents.models
17 from rest_framework.generics import ListAPIView, RetrieveAPIView
18 from rest_framework.filters import SearchFilter
19 from rest_framework.permissions import IsAdminUser
20 from rest_framework.response import Response
21 from rest_framework.views import APIView
22 from rest_framework import serializers
23
24
25 class CatalogueView(TemplateView):
26     template_name = "catalogue/catalogue.html"
27
28     def get_context_data(self):
29         ctx = super().get_context_data()
30         ctx["authors"] = models.Author.objects.all().prefetch_related('book_set__book_set', 'translated_book_set__book_set')
31
32         return ctx
33
34
35 class AuthorView(TemplateView):
36     model = models.Author
37     template_name = "catalogue/author_detail.html"
38
39     def get_context_data(self, slug):
40         ctx = super().get_context_data()
41         authors = models.Author.objects.filter(slug=slug).prefetch_related(
42             Prefetch("book_set"),
43             Prefetch("translated_book_set"),
44         )
45         ctx["author"] = authors.first()
46         return ctx
47
48
49 class BookView(DetailView):
50     model = models.Book
51
52 class BookAPIView(RetrieveAPIView):
53     queryset = models.Book.objects.all()
54     lookup_field = 'slug'
55
56     class serializer_class(serializers.ModelSerializer):
57         class AuthorSerializer(serializers.ModelSerializer):
58             literal = serializers.CharField(source='name')
59
60             class Meta:
61                 model = models.Author
62                 fields = ['literal']
63
64         def category_serializer(m):
65             class CategorySerializer(serializers.ModelSerializer):
66                 literal = serializers.CharField(source='name')
67                 class Meta:
68                     model = m
69                     fields = ['literal']
70             return CategorySerializer
71
72         authors = AuthorSerializer(many=True)
73         translators = AuthorSerializer(many=True)
74         epochs = category_serializer(models.Epoch)(many=True)
75         kinds = category_serializer(models.Kind)(many=True)
76         genres = category_serializer(models.Genre)(many=True)
77
78         class Meta:
79             model = models.Book
80             fields = [
81                 'title',
82                 'authors',
83                 'translators',
84                 'epochs',
85                 'kinds',
86                 'genres',
87                 'scans_source',
88                 'text_source',
89                 'original_year',
90                 'pd_year',
91             ]
92     
93
94 class TermSearchFilter(SearchFilter):
95     search_param = 'term'
96
97
98 class Terms(ListAPIView):
99     filter_backends = [TermSearchFilter]
100     search_fields = ['name']
101
102     class serializer_class(serializers.Serializer):
103         label = serializers.CharField(source='name')
104
105
106 class EpochTerms(Terms):
107     queryset = models.Epoch.objects.all()
108 class KindTerms(Terms):
109     queryset = models.Kind.objects.all()
110 class GenreTerms(Terms):
111     queryset = models.Genre.objects.all()
112
113 class AuthorTerms(Terms):
114     search_fields = ['first_name', 'last_name']
115     queryset = models.Author.objects.all()
116
117 class EditorTerms(Terms):
118     search_fields = ['first_name', 'last_name', 'username']
119     queryset = User.objects.all()
120
121     class serializer_class(serializers.Serializer):
122         label = serializers.SerializerMethodField()
123
124         def get_label(self, obj):
125             return f'{obj.last_name}, {obj.first_name}'
126     
127 class BookTitleTerms(Terms):
128     queryset = models.Book.objects.all()
129     search_fields = ['title', 'slug']
130
131     class serializer_class(serializers.Serializer):
132         label = serializers.CharField(source='title')
133
134 class WLURITerms(Terms):
135     queryset = models.Book.objects.all()
136     search_fields = ['title', 'slug']
137     
138     class serializer_class(serializers.Serializer):
139         label = serializers.CharField(source='wluri')
140
141
142 class WikidataView(APIView):
143     permission_classes = [IsAdminUser]
144
145     def get_object(self, model, qid, save):
146         try:
147             Model = apps.get_model('catalogue', model)
148         except LookupError:
149             raise Http404
150         if not issubclass(Model, models.WikidataModel):
151             raise Http404
152
153         obj = Model.objects.filter(wikidata=qid).first()
154         if obj is None:
155             obj = Model(wikidata=qid)
156         if not obj.pk and save:
157             obj.save()
158         else:
159             obj.wikidata_populate(save=False, force=True)
160         d = {
161             "id": obj.pk,
162             "__str__": str(obj),
163         }
164         for attname in dir(Model.Wikidata):
165             if attname.startswith("_"):
166                 continue
167             for fieldname, lang in obj.wikidata_fields_for_attribute(attname):
168                 try:
169                     d[fieldname] = getattr(obj, fieldname)
170                 except ValueError:
171                     # Like accessing related field on non-saved object.
172                     continue
173
174                 if isinstance(d[fieldname], models.WikidataModel):
175                     d[fieldname] = {
176                         "model": type(d[fieldname])._meta.model_name,
177                         "id": d[fieldname].pk,
178                         "wd": d[fieldname].wikidata,
179                         "label": str(d[fieldname]) or d[fieldname]._wikidata_label,
180                     }
181                 elif hasattr(d[fieldname], 'all'):
182                     d[fieldname] = [
183                         {
184                             "model": type(item)._meta.model_name,
185                             "id": item.pk,
186                             "wd": item.wikidata,
187                             "label": str(item) or item._wikidata_label
188                         } for item in d[fieldname].all()
189                     ]
190                 elif hasattr(d[fieldname], 'as_hint_json'):
191                     d[fieldname] = d[fieldname].as_hint_json()
192                 elif hasattr(d[fieldname], 'storage'):
193                     d[fieldname] = d[fieldname].url if d[fieldname] else None
194                 else:
195                     d[fieldname] = localize_input(d[fieldname])
196         return Response(d)
197     
198     def get(self, request, model, qid):
199         return self.get_object(model, qid, save=False)
200
201     def post(self, request, model, qid):
202         return self.get_object(model, qid, save=True)
203
204
205 @require_POST
206 @login_required
207 def publish_author(request, pk):
208     author = get_object_or_404(models.Author, pk=pk)
209     data = {
210         "description_pl": author.generate_description(),
211     }
212     apiclient.api_call(request.user, f"authors/{author.slug}/", data)
213     return redirect(reverse('admin:catalogue_author_change', args=[author.pk]))
214
215
216 @require_POST
217 @login_required
218 def publish_collection(request, pk):
219     collection = get_object_or_404(models.Collection, pk=pk)
220     data = {
221         "title": collection.name,
222         "description": collection.description,
223         "book_slugs": "\n".join(
224             book.slug
225             for book in collection.book_set.exclude(slug=None).exclude(slug='')
226         )
227     }
228     apiclient.api_call(
229         request.user,
230         f"collections/{collection.slug}/",
231         data,
232         method='PUT',
233         as_json=True,
234     )
235     return redirect(reverse(
236         'admin:catalogue_collection_change', args=[collection.pk]
237     ))