ptrad
[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 import json
5 from django.apps import apps
6 from django.db.models import Prefetch, Q
7 from django.http import Http404, JsonResponse
8 from django.urls import reverse
9 from django.utils.formats import localize_input
10 from django.contrib.auth.decorators import login_required
11 from django.contrib.auth.models import User
12 from django.shortcuts import get_object_or_404, redirect
13 from django.views.decorators.http import require_POST
14 from django.views.generic import DetailView, TemplateView
15 import apiclient
16 from . import models
17 import documents.models
18 from rest_framework.generics import ListAPIView, RetrieveAPIView
19 from rest_framework.filters import SearchFilter
20 from rest_framework.permissions import IsAdminUser
21 from rest_framework.response import Response
22 from rest_framework.views import APIView
23 from rest_framework import serializers
24 import depot.models
25
26
27
28
29 class CatalogueView(TemplateView):
30     template_name = "catalogue/catalogue.html"
31
32     def get_context_data(self):
33         ctx = super().get_context_data()
34         ctx["authors"] = models.Author.objects.all().prefetch_related('book_set__document_books', 'translated_book_set__document_books')
35
36         return ctx
37
38
39 class AuthorView(TemplateView):
40     model = models.Author
41     template_name = "catalogue/author_detail.html"
42
43     def get_context_data(self, slug):
44         ctx = super().get_context_data()
45         authors = models.Author.objects.filter(slug=slug).prefetch_related(
46             Prefetch("book_set"),
47             Prefetch("translated_book_set"),
48         )
49         ctx["author"] = authors.first()
50         return ctx
51
52
53 class BookView(DetailView):
54     model = models.Book
55
56 class BookAPIView(RetrieveAPIView):
57     queryset = models.Book.objects.all()
58     lookup_field = 'slug'
59
60     class serializer_class(serializers.ModelSerializer):
61         class AuthorSerializer(serializers.ModelSerializer):
62             literal = serializers.CharField(source='name')
63
64             class Meta:
65                 model = models.Author
66                 fields = ['literal']
67
68         def category_serializer(m):
69             class CategorySerializer(serializers.ModelSerializer):
70                 literal = serializers.CharField(source='name')
71                 class Meta:
72                     model = m
73                     fields = ['literal']
74             return CategorySerializer
75
76         authors = AuthorSerializer(many=True)
77         translators = AuthorSerializer(many=True)
78         epochs = category_serializer(models.Epoch)(many=True)
79         kinds = category_serializer(models.Kind)(many=True)
80         genres = category_serializer(models.Genre)(many=True)
81
82         class Meta:
83             model = models.Book
84             fields = [
85                 'title',
86                 'authors',
87                 'translators',
88                 'epochs',
89                 'kinds',
90                 'genres',
91                 'scans_source',
92                 'text_source',
93                 'original_year',
94                 'pd_year',
95             ]
96
97
98 class TermSearchFilter(SearchFilter):
99     search_param = 'term'
100
101
102 class Terms(ListAPIView):
103     filter_backends = [TermSearchFilter]
104     search_fields = ['name']
105
106     class serializer_class(serializers.Serializer):
107         label = serializers.CharField(source='name')
108
109
110 class AudienceTerms(Terms):
111     queryset = models.Audience.objects.all()
112     search_fields = ['code', 'name', 'description']
113
114     class serializer_class(serializers.Serializer):
115         label = serializers.CharField(source='code')
116         name = serializers.CharField()
117         description = serializers.CharField()
118
119 class EpochTerms(Terms):
120     queryset = models.Epoch.objects.all()
121 class KindTerms(Terms):
122     queryset = models.Kind.objects.all()
123 class GenreTerms(Terms):
124     queryset = models.Genre.objects.all()
125
126 class AuthorTerms(Terms):
127     search_fields = ['first_name', 'last_name']
128     queryset = models.Author.objects.all()
129
130 class EditorTerms(Terms):
131     search_fields = ['first_name', 'last_name', 'username']
132     queryset = User.objects.all()
133
134     class serializer_class(serializers.Serializer):
135         label = serializers.SerializerMethodField()
136
137         def get_label(self, obj):
138             return f'{obj.last_name}, {obj.first_name}'
139
140 class BookTitleTerms(Terms):
141     queryset = models.Book.objects.all()
142     search_fields = ['title', 'slug']
143
144     class serializer_class(serializers.Serializer):
145         label = serializers.CharField(source='title')
146
147 class WLURITerms(Terms):
148     queryset = models.Book.objects.all()
149     search_fields = ['title', 'slug']
150
151     class serializer_class(serializers.Serializer):
152         label = serializers.CharField(source='wluri')
153
154 class ThemaTerms(Terms):
155     queryset = models.Thema.objects.filter(usable=True, hidden=False)
156     search_fields = ['code', 'name', 'description']
157
158     class serializer_class(serializers.Serializer):
159         label = serializers.CharField(source='code')
160         name = serializers.CharField()
161         description = serializers.CharField()
162
163 class MainThemaTerms(ThemaTerms):
164     queryset = models.Thema.objects.filter(usable=True, hidden=False, usable_as_main=True)
165
166
167
168 class Chooser(APIView):
169     def get(self, request):
170         return Response([{
171             'value': 'x',
172             'name': 'name',
173             'description': 'desc',
174             'sub': [
175                 {
176                     'value': 'y',
177                     'name': 'name y',
178                     'description': 'desc y',
179                 }
180             ]
181         }])
182
183
184 class ThemaChooser(Chooser):
185     queryset = models.Thema.objects.filter(usable=True, hidden=False)
186
187     def get(self, request):
188         tree = {}
189
190         def getitem(code):
191             if len(code) == 1:
192                 parent = tree
193             else:
194                 parent = getitem(code[:-1]).setdefault('sub', {})
195             return parent.setdefault(code, {})
196
197         def getmissing(t):
198             for k, v in t.items():
199                 if 'name' not in v:
200                     yield k
201                 if 'sub' in v:
202                     for c in getmissing(v['sub']):
203                         yield c
204
205         def populate(thema):
206             item = getitem(thema.code)
207             item['usable'] = thema.usable
208             item['hidden'] = thema.hidden
209             item['name'] = thema.name
210             item['description'] = thema.description
211
212         def order(tree):
213             res = []
214             for k, v in tree.items():
215                 v.update(value=k)
216                 if 'sub' in v:
217                     v['sub'] = order(v['sub'])
218                 res.append(v)
219             while len(res) == 1 and 'name' not in res[0] and 'sub' in res[0]:
220                 res = res[0]['sub']
221             return res
222
223         def apply_filter(filt):
224             if 'not' in filt:
225                 return ~apply_filter(filt['not'])
226             if 'startswith' in filt:
227                 q = None
228                 for prefix in filt['startswith']:
229                     q2 = Q(code__startswith=prefix)
230                     if q:
231                         q |= q2
232                     else:
233                         q = q2
234                 return q
235             assert False
236
237         qs = self.queryset
238         try:
239             filt = json.loads(request.GET.get('filter'))
240         except:
241             pass
242         else:
243             qs = qs.filter(apply_filter(filt))
244
245         for thema in qs:
246             populate(thema)
247
248         missing = list(getmissing(tree))
249         for thema in models.Thema.objects.filter(code__in=missing):
250             populate(thema)
251
252         tree = order(tree)
253
254         return Response(tree)
255
256
257 class MainThemaChooser(ThemaChooser):
258     queryset = models.Thema.objects.filter(usable=True, hidden=False, usable_as_main=True)[:1000]
259
260
261 class WikidataView(APIView):
262     permission_classes = [IsAdminUser]
263
264     def get_object(self, model, qid, save):
265         try:
266             Model = apps.get_model('catalogue', model)
267         except LookupError:
268             raise Http404
269         if not issubclass(Model, models.WikidataModel):
270             raise Http404
271
272         obj = Model.objects.filter(wikidata=qid).first()
273         if obj is None:
274             obj = Model(wikidata=qid)
275         if not obj.pk and save:
276             obj.save()
277         else:
278             obj.wikidata_populate(save=False, force=True)
279         d = {
280             "id": obj.pk,
281             "__str__": str(obj),
282         }
283         for attname in dir(Model.Wikidata):
284             if attname.startswith("_"):
285                 continue
286             for fieldname, lang in obj.wikidata_fields_for_attribute(attname):
287                 try:
288                     d[fieldname] = getattr(obj, fieldname)
289                 except ValueError:
290                     # Like accessing related field on non-saved object.
291                     continue
292
293                 if isinstance(d[fieldname], models.WikidataModel):
294                     d[fieldname] = {
295                         "model": type(d[fieldname])._meta.model_name,
296                         "id": d[fieldname].pk,
297                         "wd": d[fieldname].wikidata,
298                         "label": str(d[fieldname]) or d[fieldname]._wikidata_label,
299                     }
300                 elif hasattr(d[fieldname], 'all'):
301                     d[fieldname] = [
302                         {
303                             "model": type(item)._meta.model_name,
304                             "id": item.pk,
305                             "wd": item.wikidata,
306                             "label": str(item) or item._wikidata_label
307                         } for item in d[fieldname].all()
308                     ]
309                 elif hasattr(d[fieldname], 'as_hint_json'):
310                     d[fieldname] = d[fieldname].as_hint_json()
311                 elif hasattr(d[fieldname], 'storage'):
312                     d[fieldname] = d[fieldname].url if d[fieldname] else None
313                 else:
314                     d[fieldname] = localize_input(d[fieldname])
315         return Response(d)
316
317     def get(self, request, model, qid):
318         return self.get_object(model, qid, save=False)
319
320     def post(self, request, model, qid):
321         return self.get_object(model, qid, save=True)
322
323
324 @require_POST
325 @login_required
326 def publish_author(request, pk):
327     author = get_object_or_404(models.Author, pk=pk)
328     data = {
329         "name_pl": author.name,
330         "description_pl": author.generate_description(),
331         "genitive": author.genitive,
332         "gazeta_link": author.gazeta_link,
333         "culturepl_link": author.culturepl_link,
334         "wiki_link_pl": author.plwiki,
335         "photo": request.build_absolute_uri(author.photo.url) if author.photo else None,
336         "photo_source": author.photo_source,
337         "photo_attribution": author.photo_attribution,
338     }
339     apiclient.api_call(request.user, f"authors/{author.slug}/", data)
340     return redirect(reverse('admin:catalogue_author_change', args=[author.pk]))
341
342
343 @require_POST
344 @login_required
345 def publish_genre(request, pk):
346     obj = get_object_or_404(models.Genre, pk=pk)
347     data = {
348         "name_pl": obj.name,
349         "description_pl": obj.description,
350         "plural": obj.plural,
351         "is_epoch_specific": obj.is_epoch_specific,
352     }
353     apiclient.api_call(request.user, f"genres/{obj.slug}/", data)
354     return redirect(reverse('admin:catalogue_genre_change', args=[obj.pk]))
355
356
357 @require_POST
358 @login_required
359 def publish_kind(request, pk):
360     obj = get_object_or_404(models.Kind, pk=pk)
361     data = {
362         "name_pl": obj.name,
363         "description_pl": obj.description,
364         "collective_noun": obj.collective_noun,
365     }
366     apiclient.api_call(request.user, f"kinds/{obj.slug}/", data)
367     return redirect(reverse('admin:catalogue_kind_change', args=[obj.pk]))
368
369
370 @require_POST
371 @login_required
372 def publish_epoch(request, pk):
373     obj = get_object_or_404(models.Epoch, pk=pk)
374     data = {
375         "name_pl": obj.name,
376         "description_pl": obj.description,
377         "adjective_feminine_singular": obj.adjective_feminine_singular,
378         "adjective_nonmasculine_plural": obj.adjective_feminine_singular,
379     }
380     apiclient.api_call(request.user, f"epochs/{obj.slug}/", data)
381     return redirect(reverse('admin:catalogue_epoch_change', args=[obj.pk]))
382
383
384 @require_POST
385 @login_required
386 def publish_collection(request, pk):
387     collection = get_object_or_404(models.Collection, pk=pk)
388     data = {
389         "title": collection.name,
390         "description": collection.description,
391         "book_slugs": "\n".join(
392             book.slug
393             for book in collection.book_set.exclude(slug=None).exclude(slug='')
394         )
395     }
396     apiclient.api_call(
397         request.user,
398         f"collections/{collection.slug}/",
399         data,
400         method='PUT',
401         as_json=True,
402     )
403     return redirect(reverse(
404         'admin:catalogue_collection_change', args=[collection.pk]
405     ))
406
407
408 @login_required
409 def woblink_autocomplete(request, category):
410     site = depot.models.Site.objects.filter(site_type='woblink').first()
411     if site is None:
412         return JsonResponse({})
413     woblink = site.get_publisher()
414     term = request.GET.get('term')
415     if not term:
416         return JsonResponse({})
417
418     if category == 'author':
419         results = woblink.search_author_catalogue(term)
420     elif category == 'series':
421         results = woblink.search_series_catalogue(term)
422     else:
423         raise Http404
424
425     return JsonResponse({"results": results})