44ad3058c7dc13bba4d678645bec08adb6f30639
[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 from depot.woblink import get_woblink_session
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 class WikidataView(APIView):
167     permission_classes = [IsAdminUser]
168
169     def get_object(self, model, qid, save):
170         try:
171             Model = apps.get_model('catalogue', model)
172         except LookupError:
173             raise Http404
174         if not issubclass(Model, models.WikidataModel):
175             raise Http404
176
177         obj = Model.objects.filter(wikidata=qid).first()
178         if obj is None:
179             obj = Model(wikidata=qid)
180         if not obj.pk and save:
181             obj.save()
182         else:
183             obj.wikidata_populate(save=False, force=True)
184         d = {
185             "id": obj.pk,
186             "__str__": str(obj),
187         }
188         for attname in dir(Model.Wikidata):
189             if attname.startswith("_"):
190                 continue
191             for fieldname, lang in obj.wikidata_fields_for_attribute(attname):
192                 try:
193                     d[fieldname] = getattr(obj, fieldname)
194                 except ValueError:
195                     # Like accessing related field on non-saved object.
196                     continue
197
198                 if isinstance(d[fieldname], models.WikidataModel):
199                     d[fieldname] = {
200                         "model": type(d[fieldname])._meta.model_name,
201                         "id": d[fieldname].pk,
202                         "wd": d[fieldname].wikidata,
203                         "label": str(d[fieldname]) or d[fieldname]._wikidata_label,
204                     }
205                 elif hasattr(d[fieldname], 'all'):
206                     d[fieldname] = [
207                         {
208                             "model": type(item)._meta.model_name,
209                             "id": item.pk,
210                             "wd": item.wikidata,
211                             "label": str(item) or item._wikidata_label
212                         } for item in d[fieldname].all()
213                     ]
214                 elif hasattr(d[fieldname], 'as_hint_json'):
215                     d[fieldname] = d[fieldname].as_hint_json()
216                 elif hasattr(d[fieldname], 'storage'):
217                     d[fieldname] = d[fieldname].url if d[fieldname] else None
218                 else:
219                     d[fieldname] = localize_input(d[fieldname])
220         return Response(d)
221     
222     def get(self, request, model, qid):
223         return self.get_object(model, qid, save=False)
224
225     def post(self, request, model, qid):
226         return self.get_object(model, qid, save=True)
227
228
229 @require_POST
230 @login_required
231 def publish_author(request, pk):
232     author = get_object_or_404(models.Author, pk=pk)
233     data = {
234         "name_pl": author.name,
235         "description_pl": author.generate_description(),
236         "genitive": author.genitive,
237         "gazeta_link": author.gazeta_link,
238         "culturepl_link": author.culturepl_link,
239         "wiki_link_pl": author.plwiki,
240         "photo": request.build_absolute_uri(author.photo.url) if author.photo else None,
241         "photo_source": author.photo_source,
242         "photo_attribution": author.photo_attribution,
243     }
244     apiclient.api_call(request.user, f"authors/{author.slug}/", data)
245     return redirect(reverse('admin:catalogue_author_change', args=[author.pk]))
246
247
248 @require_POST
249 @login_required
250 def publish_genre(request, pk):
251     obj = get_object_or_404(models.Genre, pk=pk)
252     data = {
253         "name_pl": obj.name,
254         "description_pl": obj.description,
255         "plural": obj.plural,
256         "is_epoch_specific": obj.is_epoch_specific,
257     }
258     apiclient.api_call(request.user, f"genres/{obj.slug}/", data)
259     return redirect(reverse('admin:catalogue_genre_change', args=[obj.pk]))
260
261
262 @require_POST
263 @login_required
264 def publish_kind(request, pk):
265     obj = get_object_or_404(models.Kind, pk=pk)
266     data = {
267         "name_pl": obj.name,
268         "description_pl": obj.description,
269         "collective_noun": obj.collective_noun,
270     }
271     apiclient.api_call(request.user, f"kinds/{obj.slug}/", data)
272     return redirect(reverse('admin:catalogue_kind_change', args=[obj.pk]))
273
274
275 @require_POST
276 @login_required
277 def publish_epoch(request, pk):
278     obj = get_object_or_404(models.Epoch, pk=pk)
279     data = {
280         "name_pl": obj.name,
281         "description_pl": obj.description,
282         "adjective_feminine_singular": obj.adjective_feminine_singular,
283         "adjective_nonmasculine_plural": obj.adjective_feminine_singular,
284     }
285     apiclient.api_call(request.user, f"epochs/{obj.slug}/", data)
286     return redirect(reverse('admin:catalogue_epoch_change', args=[obj.pk]))
287
288
289 @require_POST
290 @login_required
291 def publish_collection(request, pk):
292     collection = get_object_or_404(models.Collection, pk=pk)
293     data = {
294         "title": collection.name,
295         "description": collection.description,
296         "book_slugs": "\n".join(
297             book.slug
298             for book in collection.book_set.exclude(slug=None).exclude(slug='')
299         )
300     }
301     apiclient.api_call(
302         request.user,
303         f"collections/{collection.slug}/",
304         data,
305         method='PUT',
306         as_json=True,
307     )
308     return redirect(reverse(
309         'admin:catalogue_collection_change', args=[collection.pk]
310     ))
311
312
313 @login_required
314 def woblink_author_autocomplete(request):
315     session = get_woblink_session()
316     term = request.GET.get('term')
317     if not term:
318         return JsonResponse({})
319     response = session.get(
320         'https://publisher.woblink.com/author/autocomplete/' + term
321     ).json()
322     return JsonResponse({
323         "results": [
324             {
325                 "id": item['autId'],
326                 "text": item['autFullname'],
327             }
328             for item in response
329         ],
330     })