Fundraising in PDF.
[wolnelektury.git] / src / api / handlers.py
1 # This file is part of Wolne Lektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Wolne Lektury. See NOTICE for more information.
3 #
4 from django.contrib.sites.models import Site
5 from django.utils.functional import lazy
6 from catalogue.models import Book, Tag
7
8
9 WL_BASE = lazy(
10     lambda: 'https://' + Site.objects.get_current().domain, str)()
11
12 category_singular = {
13     'authors': 'author',
14     'kinds': 'kind',
15     'genres': 'genre',
16     'epochs': 'epoch',
17     'themes': 'theme',
18     'books': 'book',
19 }
20
21
22 def read_tags(tags, request, allowed):
23     """ Reads a path of filtering tags.
24
25     :param str tags: a path of category and slug pairs, like: authors/an-author/...
26     :returns: list of Tag objects
27     :raises: ValueError when tags can't be found
28     """
29
30     def process(category, slug):
31         if category == 'book':
32             # FIXME: Unused?
33             try:
34                 books.append(Book.objects.get(slug=slug))
35             except Book.DoesNotExist:
36                 raise ValueError('Unknown book.')
37         try:
38             real_tags.append(Tag.objects.get(category=category, slug=slug))
39         except Tag.DoesNotExist:
40             raise ValueError('Tag not found')
41
42     if not tags:
43         return [], []
44
45     tags = tags.strip('/').split('/')
46     real_tags = []
47     books = []
48     while tags:
49         category = tags.pop(0)
50         slug = tags.pop(0)
51
52         try:
53             category = category_singular[category]
54         except KeyError:
55             raise ValueError('Unknown category.')
56
57         if category not in allowed:
58             raise ValueError('Category not allowed.')
59         process(category, slug)
60
61     for key in request.GET:
62         if key in category_singular:
63             category = category_singular[key]
64             if category in allowed:
65                 for slug in request.GET.getlist(key):
66                     process(category, slug)
67     return real_tags, books