Untangle the callbacks; Add linkable diff tabs.
[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 EpochTerms(Terms):
110     queryset = models.Epoch.objects.all()
111 class KindTerms(Terms):
112     queryset = models.Kind.objects.all()
113 class GenreTerms(Terms):
114     queryset = models.Genre.objects.all()
115
116 class AuthorTerms(Terms):
117     search_fields = ['first_name', 'last_name']
118     queryset = models.Author.objects.all()
119
120 class EditorTerms(Terms):
121     search_fields = ['first_name', 'last_name', 'username']
122     queryset = User.objects.all()
123
124     class serializer_class(serializers.Serializer):
125         label = serializers.SerializerMethodField()
126
127         def get_label(self, obj):
128             return f'{obj.last_name}, {obj.first_name}'
129     
130 class BookTitleTerms(Terms):
131     queryset = models.Book.objects.all()
132     search_fields = ['title', 'slug']
133
134     class serializer_class(serializers.Serializer):
135         label = serializers.CharField(source='title')
136
137 class WLURITerms(Terms):
138     queryset = models.Book.objects.all()
139     search_fields = ['title', 'slug']
140     
141     class serializer_class(serializers.Serializer):
142         label = serializers.CharField(source='wluri')
143
144 class ThemaTerms(Terms):
145     queryset = models.Thema.objects.filter(usable=True, hidden=False)
146     search_fields = ['code', 'name', 'description']
147
148     class serializer_class(serializers.Serializer):
149         label = serializers.CharField(source='code')
150         name = serializers.CharField()
151         description = serializers.CharField()
152
153
154 class WikidataView(APIView):
155     permission_classes = [IsAdminUser]
156
157     def get_object(self, model, qid, save):
158         try:
159             Model = apps.get_model('catalogue', model)
160         except LookupError:
161             raise Http404
162         if not issubclass(Model, models.WikidataModel):
163             raise Http404
164
165         obj = Model.objects.filter(wikidata=qid).first()
166         if obj is None:
167             obj = Model(wikidata=qid)
168         if not obj.pk and save:
169             obj.save()
170         else:
171             obj.wikidata_populate(save=False, force=True)
172         d = {
173             "id": obj.pk,
174             "__str__": str(obj),
175         }
176         for attname in dir(Model.Wikidata):
177             if attname.startswith("_"):
178                 continue
179             for fieldname, lang in obj.wikidata_fields_for_attribute(attname):
180                 try:
181                     d[fieldname] = getattr(obj, fieldname)
182                 except ValueError:
183                     # Like accessing related field on non-saved object.
184                     continue
185
186                 if isinstance(d[fieldname], models.WikidataModel):
187                     d[fieldname] = {
188                         "model": type(d[fieldname])._meta.model_name,
189                         "id": d[fieldname].pk,
190                         "wd": d[fieldname].wikidata,
191                         "label": str(d[fieldname]) or d[fieldname]._wikidata_label,
192                     }
193                 elif hasattr(d[fieldname], 'all'):
194                     d[fieldname] = [
195                         {
196                             "model": type(item)._meta.model_name,
197                             "id": item.pk,
198                             "wd": item.wikidata,
199                             "label": str(item) or item._wikidata_label
200                         } for item in d[fieldname].all()
201                     ]
202                 elif hasattr(d[fieldname], 'as_hint_json'):
203                     d[fieldname] = d[fieldname].as_hint_json()
204                 elif hasattr(d[fieldname], 'storage'):
205                     d[fieldname] = d[fieldname].url if d[fieldname] else None
206                 else:
207                     d[fieldname] = localize_input(d[fieldname])
208         return Response(d)
209     
210     def get(self, request, model, qid):
211         return self.get_object(model, qid, save=False)
212
213     def post(self, request, model, qid):
214         return self.get_object(model, qid, save=True)
215
216
217 @require_POST
218 @login_required
219 def publish_author(request, pk):
220     author = get_object_or_404(models.Author, pk=pk)
221     data = {
222         "name_pl": author.name,
223         "description_pl": author.generate_description(),
224         "genitive": author.genitive,
225         "gazeta_link": author.gazeta_link,
226         "culturepl_link": author.culturepl_link,
227         "wiki_link_pl": author.plwiki,
228         "photo": request.build_absolute_uri(author.photo.url) if author.photo else None,
229         "photo_source": author.photo_source,
230         "photo_attribution": author.photo_attribution,
231     }
232     apiclient.api_call(request.user, f"authors/{author.slug}/", data)
233     return redirect(reverse('admin:catalogue_author_change', args=[author.pk]))
234
235
236 @require_POST
237 @login_required
238 def publish_genre(request, pk):
239     obj = get_object_or_404(models.Genre, pk=pk)
240     data = {
241         "name_pl": obj.name,
242         "description_pl": obj.description,
243         "plural": obj.plural,
244         "is_epoch_specific": obj.is_epoch_specific,
245     }
246     apiclient.api_call(request.user, f"genres/{obj.slug}/", data)
247     return redirect(reverse('admin:catalogue_genre_change', args=[obj.pk]))
248
249
250 @require_POST
251 @login_required
252 def publish_kind(request, pk):
253     obj = get_object_or_404(models.Kind, pk=pk)
254     data = {
255         "name_pl": obj.name,
256         "description_pl": obj.description,
257         "collective_noun": obj.collective_noun,
258     }
259     apiclient.api_call(request.user, f"kinds/{obj.slug}/", data)
260     return redirect(reverse('admin:catalogue_kind_change', args=[obj.pk]))
261
262
263 @require_POST
264 @login_required
265 def publish_epoch(request, pk):
266     obj = get_object_or_404(models.Epoch, pk=pk)
267     data = {
268         "name_pl": obj.name,
269         "description_pl": obj.description,
270         "adjective_feminine_singular": obj.adjective_feminine_singular,
271         "adjective_nonmasculine_plural": obj.adjective_feminine_singular,
272     }
273     apiclient.api_call(request.user, f"epochs/{obj.slug}/", data)
274     return redirect(reverse('admin:catalogue_epoch_change', args=[obj.pk]))
275
276
277 @require_POST
278 @login_required
279 def publish_collection(request, pk):
280     collection = get_object_or_404(models.Collection, pk=pk)
281     data = {
282         "title": collection.name,
283         "description": collection.description,
284         "book_slugs": "\n".join(
285             book.slug
286             for book in collection.book_set.exclude(slug=None).exclude(slug='')
287         )
288     }
289     apiclient.api_call(
290         request.user,
291         f"collections/{collection.slug}/",
292         data,
293         method='PUT',
294         as_json=True,
295     )
296     return redirect(reverse(
297         'admin:catalogue_collection_change', args=[collection.pk]
298     ))
299
300
301 @login_required
302 def woblink_author_autocomplete(request):
303     session = get_woblink_session()
304     term = request.GET.get('term')
305     if not term:
306         return JsonResponse({})
307     response = session.get(
308         'https://publisher.woblink.com/author/autocomplete/' + term
309     ).json()
310     return JsonResponse({
311         "results": [
312             {
313                 "id": item['autId'],
314                 "text": item['autFullname'],
315             }
316             for item in response
317         ],
318     })