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