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