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