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.
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
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
28 class CatalogueView(TemplateView):
29 template_name = "catalogue/catalogue.html"
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')
38 class AuthorView(TemplateView):
40 template_name = "catalogue/author_detail.html"
42 def get_context_data(self, slug):
43 ctx = super().get_context_data()
44 authors = models.Author.objects.filter(slug=slug).prefetch_related(
46 Prefetch("translated_book_set"),
48 ctx["author"] = authors.first()
52 class BookView(DetailView):
55 class BookAPIView(RetrieveAPIView):
56 queryset = models.Book.objects.all()
59 class serializer_class(serializers.ModelSerializer):
60 class AuthorSerializer(serializers.ModelSerializer):
61 literal = serializers.CharField(source='name')
67 def category_serializer(m):
68 class CategorySerializer(serializers.ModelSerializer):
69 literal = serializers.CharField(source='name')
73 return CategorySerializer
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)
97 class TermSearchFilter(SearchFilter):
101 class Terms(ListAPIView):
102 filter_backends = [TermSearchFilter]
103 search_fields = ['name']
105 class serializer_class(serializers.Serializer):
106 label = serializers.CharField(source='name')
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()
116 class AuthorTerms(Terms):
117 search_fields = ['first_name', 'last_name']
118 queryset = models.Author.objects.all()
120 class EditorTerms(Terms):
121 search_fields = ['first_name', 'last_name', 'username']
122 queryset = User.objects.all()
124 class serializer_class(serializers.Serializer):
125 label = serializers.SerializerMethodField()
127 def get_label(self, obj):
128 return f'{obj.last_name}, {obj.first_name}'
130 class BookTitleTerms(Terms):
131 queryset = models.Book.objects.all()
132 search_fields = ['title', 'slug']
134 class serializer_class(serializers.Serializer):
135 label = serializers.CharField(source='title')
137 class WLURITerms(Terms):
138 queryset = models.Book.objects.all()
139 search_fields = ['title', 'slug']
141 class serializer_class(serializers.Serializer):
142 label = serializers.CharField(source='wluri')
145 class WikidataView(APIView):
146 permission_classes = [IsAdminUser]
148 def get_object(self, model, qid, save):
150 Model = apps.get_model('catalogue', model)
153 if not issubclass(Model, models.WikidataModel):
156 obj = Model.objects.filter(wikidata=qid).first()
158 obj = Model(wikidata=qid)
159 if not obj.pk and save:
162 obj.wikidata_populate(save=False, force=True)
167 for attname in dir(Model.Wikidata):
168 if attname.startswith("_"):
170 for fieldname, lang in obj.wikidata_fields_for_attribute(attname):
172 d[fieldname] = getattr(obj, fieldname)
174 # Like accessing related field on non-saved object.
177 if isinstance(d[fieldname], models.WikidataModel):
179 "model": type(d[fieldname])._meta.model_name,
180 "id": d[fieldname].pk,
181 "wd": d[fieldname].wikidata,
182 "label": str(d[fieldname]) or d[fieldname]._wikidata_label,
184 elif hasattr(d[fieldname], 'all'):
187 "model": type(item)._meta.model_name,
190 "label": str(item) or item._wikidata_label
191 } for item in d[fieldname].all()
193 elif hasattr(d[fieldname], 'as_hint_json'):
194 d[fieldname] = d[fieldname].as_hint_json()
195 elif hasattr(d[fieldname], 'storage'):
196 d[fieldname] = d[fieldname].url if d[fieldname] else None
198 d[fieldname] = localize_input(d[fieldname])
201 def get(self, request, model, qid):
202 return self.get_object(model, qid, save=False)
204 def post(self, request, model, qid):
205 return self.get_object(model, qid, save=True)
210 def publish_author(request, pk):
211 author = get_object_or_404(models.Author, pk=pk)
213 "description_pl": author.generate_description(),
215 apiclient.api_call(request.user, f"authors/{author.slug}/", data)
216 return redirect(reverse('admin:catalogue_author_change', args=[author.pk]))
221 def publish_genre(request, pk):
222 obj = get_object_or_404(models.Genre, pk=pk)
224 "description_pl": obj.description,
225 "plural": obj.plural,
226 "is_epoch_specific": obj.is_epoch_specific,
228 apiclient.api_call(request.user, f"genres/{obj.slug}/", data)
229 return redirect(reverse('admin:catalogue_genre_change', args=[obj.pk]))
234 def publish_kind(request, pk):
235 obj = get_object_or_404(models.Kind, pk=pk)
237 "description_pl": obj.description,
238 "collective_noun": obj.collective_noun,
240 apiclient.api_call(request.user, f"kinds/{obj.slug}/", data)
241 return redirect(reverse('admin:catalogue_kind_change', args=[obj.pk]))
246 def publish_epoch(request, pk):
247 obj = get_object_or_404(models.Epoch, pk=pk)
249 "description_pl": obj.description,
250 "adjective_feminine_singular": obj.adjective_feminine_singular,
251 "adjective_nonmasculine_plural": obj.adjective_feminine_singular,
253 apiclient.api_call(request.user, f"epochs/{obj.slug}/", data)
254 return redirect(reverse('admin:catalogue_epoch_change', args=[obj.pk]))
259 def publish_collection(request, pk):
260 collection = get_object_or_404(models.Collection, pk=pk)
262 "title": collection.name,
263 "description": collection.description,
264 "book_slugs": "\n".join(
266 for book in collection.book_set.exclude(slug=None).exclude(slug='')
271 f"collections/{collection.slug}/",
276 return redirect(reverse(
277 'admin:catalogue_collection_change', args=[collection.pk]