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.
5 from django.apps import apps
6 from django.db.models import Prefetch, Q
7 from django.http import Http404, JsonResponse
8 from django.urls import reverse
9 from django.utils.formats import localize_input
10 from django.contrib.auth.decorators import login_required
11 from django.contrib.auth.models import User
12 from django.shortcuts import get_object_or_404, redirect
13 from django.views.decorators.http import require_POST
14 from django.views.generic import DetailView, TemplateView
17 import documents.models
18 from rest_framework.generics import ListAPIView, RetrieveAPIView
19 from rest_framework.filters import SearchFilter
20 from rest_framework.permissions import IsAdminUser
21 from rest_framework.response import Response
22 from rest_framework.views import APIView
23 from rest_framework import serializers
29 class CatalogueView(TemplateView):
30 template_name = "catalogue/catalogue.html"
32 def get_context_data(self):
33 ctx = super().get_context_data()
34 ctx["authors"] = models.Author.objects.all().prefetch_related('book_set__document_books', 'translated_book_set__document_books')
39 class AuthorView(TemplateView):
41 template_name = "catalogue/author_detail.html"
43 def get_context_data(self, slug):
44 ctx = super().get_context_data()
45 authors = models.Author.objects.filter(slug=slug).prefetch_related(
47 Prefetch("translated_book_set"),
49 ctx["author"] = authors.first()
53 class BookView(DetailView):
56 class BookAPIView(RetrieveAPIView):
57 queryset = models.Book.objects.all()
60 class serializer_class(serializers.ModelSerializer):
61 class AuthorSerializer(serializers.ModelSerializer):
62 literal = serializers.CharField(source='name')
68 def category_serializer(m):
69 class CategorySerializer(serializers.ModelSerializer):
70 literal = serializers.CharField(source='name')
74 return CategorySerializer
76 authors = AuthorSerializer(many=True)
77 translators = AuthorSerializer(many=True)
78 epochs = category_serializer(models.Epoch)(many=True)
79 kinds = category_serializer(models.Kind)(many=True)
80 genres = category_serializer(models.Genre)(many=True)
98 class TermSearchFilter(SearchFilter):
102 class Terms(ListAPIView):
103 filter_backends = [TermSearchFilter]
104 search_fields = ['name']
106 class serializer_class(serializers.Serializer):
107 label = serializers.CharField(source='name')
110 class AudienceTerms(Terms):
111 queryset = models.Audience.objects.all()
112 search_fields = ['code', 'name', 'description']
114 class serializer_class(serializers.Serializer):
115 label = serializers.CharField(source='code')
116 name = serializers.CharField()
117 description = serializers.CharField()
119 class EpochTerms(Terms):
120 queryset = models.Epoch.objects.all()
121 class KindTerms(Terms):
122 queryset = models.Kind.objects.all()
123 class GenreTerms(Terms):
124 queryset = models.Genre.objects.all()
126 class AuthorTerms(Terms):
127 search_fields = ['first_name', 'last_name']
128 queryset = models.Author.objects.all()
130 class EditorTerms(Terms):
131 search_fields = ['first_name', 'last_name', 'username']
132 queryset = User.objects.all()
134 class serializer_class(serializers.Serializer):
135 label = serializers.SerializerMethodField()
137 def get_label(self, obj):
138 return f'{obj.last_name}, {obj.first_name}'
140 class BookTitleTerms(Terms):
141 queryset = models.Book.objects.all()
142 search_fields = ['title', 'slug']
144 class serializer_class(serializers.Serializer):
145 label = serializers.CharField(source='title')
147 class WLURITerms(Terms):
148 queryset = models.Book.objects.all()
149 search_fields = ['title', 'slug']
151 class serializer_class(serializers.Serializer):
152 label = serializers.CharField(source='wluri')
154 class ThemaTerms(Terms):
155 queryset = models.Thema.objects.filter(usable=True, hidden=False)
156 search_fields = ['code', 'name', 'description']
158 class serializer_class(serializers.Serializer):
159 label = serializers.CharField(source='code')
160 name = serializers.CharField()
161 description = serializers.CharField()
163 class MainThemaTerms(ThemaTerms):
164 queryset = models.Thema.objects.filter(usable=True, hidden=False, usable_as_main=True)
168 class Chooser(APIView):
169 def get(self, request):
173 'description': 'desc',
178 'description': 'desc y',
184 class ThemaChooser(Chooser):
185 queryset = models.Thema.objects.filter(usable=True, hidden=False)
187 def get(self, request):
194 parent = getitem(code[:-1]).setdefault('sub', {})
195 return parent.setdefault(code, {})
198 for k, v in t.items():
202 for c in getmissing(v['sub']):
206 item = getitem(thema.code)
207 item['usable'] = thema.usable
208 item['hidden'] = thema.hidden
209 item['name'] = thema.name
210 item['description'] = thema.description
214 for k, v in tree.items():
217 v['sub'] = order(v['sub'])
219 while len(res) == 1 and 'name' not in res[0] and 'sub' in res[0]:
223 def apply_filter(filt):
225 return ~apply_filter(filt['not'])
226 if 'startswith' in filt:
228 for prefix in filt['startswith']:
229 q2 = Q(code__startswith=prefix)
239 filt = json.loads(request.GET.get('filter'))
243 qs = qs.filter(apply_filter(filt))
248 missing = list(getmissing(tree))
249 for thema in models.Thema.objects.filter(code__in=missing):
254 return Response(tree)
257 class MainThemaChooser(ThemaChooser):
258 queryset = models.Thema.objects.filter(usable=True, hidden=False, usable_as_main=True)[:1000]
261 class WikidataView(APIView):
262 permission_classes = [IsAdminUser]
264 def get_object(self, model, qid, save):
266 Model = apps.get_model('catalogue', model)
269 if not issubclass(Model, models.WikidataModel):
272 obj = Model.objects.filter(wikidata=qid).first()
274 obj = Model(wikidata=qid)
275 if not obj.pk and save:
278 obj.wikidata_populate(save=False, force=True)
283 for attname in dir(Model.Wikidata):
284 if attname.startswith("_"):
286 for fieldname, lang in obj.wikidata_fields_for_attribute(attname):
288 d[fieldname] = getattr(obj, fieldname)
290 # Like accessing related field on non-saved object.
293 if isinstance(d[fieldname], models.WikidataModel):
295 "model": type(d[fieldname])._meta.model_name,
296 "id": d[fieldname].pk,
297 "wd": d[fieldname].wikidata,
298 "label": str(d[fieldname]) or d[fieldname]._wikidata_label,
300 elif hasattr(d[fieldname], 'all'):
303 "model": type(item)._meta.model_name,
306 "label": str(item) or item._wikidata_label
307 } for item in d[fieldname].all()
309 elif hasattr(d[fieldname], 'as_hint_json'):
310 d[fieldname] = d[fieldname].as_hint_json()
311 elif hasattr(d[fieldname], 'storage'):
312 d[fieldname] = d[fieldname].url if d[fieldname] else None
314 d[fieldname] = localize_input(d[fieldname])
317 def get(self, request, model, qid):
318 return self.get_object(model, qid, save=False)
320 def post(self, request, model, qid):
321 return self.get_object(model, qid, save=True)
326 def publish_author(request, pk):
327 author = get_object_or_404(models.Author, pk=pk)
329 "name_pl": author.name,
330 "description_pl": author.generate_description(),
331 "genitive": author.genitive,
332 "gazeta_link": author.gazeta_link,
333 "culturepl_link": author.culturepl_link,
334 "wiki_link_pl": author.plwiki,
335 "photo": request.build_absolute_uri(author.photo.url) if author.photo else None,
336 "photo_source": author.photo_source,
337 "photo_attribution": author.photo_attribution,
339 apiclient.api_call(request.user, f"authors/{author.slug}/", data)
340 return redirect(reverse('admin:catalogue_author_change', args=[author.pk]))
345 def publish_genre(request, pk):
346 obj = get_object_or_404(models.Genre, pk=pk)
349 "description_pl": obj.description,
350 "plural": obj.plural,
351 "is_epoch_specific": obj.is_epoch_specific,
353 apiclient.api_call(request.user, f"genres/{obj.slug}/", data)
354 return redirect(reverse('admin:catalogue_genre_change', args=[obj.pk]))
359 def publish_kind(request, pk):
360 obj = get_object_or_404(models.Kind, pk=pk)
363 "description_pl": obj.description,
364 "collective_noun": obj.collective_noun,
366 apiclient.api_call(request.user, f"kinds/{obj.slug}/", data)
367 return redirect(reverse('admin:catalogue_kind_change', args=[obj.pk]))
372 def publish_epoch(request, pk):
373 obj = get_object_or_404(models.Epoch, pk=pk)
376 "description_pl": obj.description,
377 "adjective_feminine_singular": obj.adjective_feminine_singular,
378 "adjective_nonmasculine_plural": obj.adjective_feminine_singular,
380 apiclient.api_call(request.user, f"epochs/{obj.slug}/", data)
381 return redirect(reverse('admin:catalogue_epoch_change', args=[obj.pk]))
386 def publish_collection(request, pk):
387 collection = get_object_or_404(models.Collection, pk=pk)
389 "title": collection.name,
390 "description": collection.description,
391 "book_slugs": "\n".join(
393 for book in collection.book_set.exclude(slug=None).exclude(slug='')
398 f"collections/{collection.slug}/",
403 return redirect(reverse(
404 'admin:catalogue_collection_change', args=[collection.pk]
409 def woblink_autocomplete(request, category):
410 site = depot.models.Site.objects.filter(site_type='woblink').first()
412 return JsonResponse({})
413 woblink = site.get_publisher()
414 term = request.GET.get('term')
416 return JsonResponse({})
418 if category == 'author':
419 results = woblink.search_author_catalogue(term)
420 elif category == 'series':
421 results = woblink.search_series_catalogue(term)
425 return JsonResponse({"results": results})