95f33fd0fd61772879906cd76383671677f82c99
[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                 d[fieldname] = getattr(obj, fieldname)
169
170                 if isinstance(d[fieldname], models.WikidataModel):
171                     d[fieldname] = {
172                         "model": type(d[fieldname])._meta.model_name,
173                         "id": d[fieldname].pk,
174                         "wd": d[fieldname].wikidata,
175                         "label": str(d[fieldname]) or d[fieldname]._wikidata_label,
176                     }
177                 elif hasattr(d[fieldname], 'all'):
178                     d[fieldname] = [
179                         {
180                             "model": type(item)._meta.model_name,
181                             "wd": item.wikidata,
182                             "label": str(item) or item._wikidata_label
183                         } for item in d[fieldname].all()
184                     ]
185                 elif hasattr(d[fieldname], 'as_hint_json'):
186                     d[fieldname] = d[fieldname].as_hint_json()
187                 elif hasattr(d[fieldname], 'storage'):
188                     d[fieldname] = d[fieldname].url if d[fieldname] else None
189                 else:
190                     d[fieldname] = localize_input(d[fieldname])
191         return Response(d)
192     
193     def get(self, request, model, qid):
194         return self.get_object(model, qid, save=False)
195
196     def post(self, request, model, qid):
197         return self.get_object(model, qid, save=True)
198
199
200 @require_POST
201 @login_required
202 def publish_author(request, pk):
203     author = get_object_or_404(models.Author, pk=pk)
204     data = {
205         "description_pl": author.generate_description(),
206     }
207     apiclient.api_call(request.user, f"authors/{author.slug}/", data)
208     return redirect(reverse('admin:catalogue_author_change', args=[author.pk]))
209
210
211 @require_POST
212 @login_required
213 def publish_collection(request, pk):
214     collection = get_object_or_404(models.Collection, pk=pk)
215     data = {
216         "title": collection.name,
217         "description": collection.description,
218         "book_slugs": "\n".join(
219             book.slug
220             for book in collection.book_set.exclude(slug=None).exclude(slug='')
221         )
222     }
223     apiclient.api_call(
224         request.user,
225         f"collections/{collection.slug}/",
226         data,
227         method='PUT',
228         as_json=True,
229     )
230     return redirect(reverse(
231         'admin:catalogue_collection_change', args=[collection.pk]
232     ))