Merge branch 'master' of git@github.com:fnp/wolnelektury
[wolnelektury.git] / apps / catalogue / templatetags / catalogue_tags.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 import feedparser
6 import datetime
7
8 from django import template
9 from django.template import Node, Variable
10 from django.utils.encoding import smart_str
11 from django.core.urlresolvers import reverse
12 from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
13 from django.db.models import Q
14 from django.conf import settings
15
16
17 register = template.Library()
18
19
20 class RegistrationForm(UserCreationForm):
21     def as_ul(self):
22         "Returns this form rendered as HTML <li>s -- excluding the <ul></ul>."
23         return self._html_output(u'<li>%(errors)s%(label)s %(field)s<span class="help-text">%(help_text)s</span></li>', u'<li>%s</li>', '</li>', u' %s', False)
24
25
26 class LoginForm(AuthenticationForm):
27     def as_ul(self):
28         "Returns this form rendered as HTML <li>s -- excluding the <ul></ul>."
29         return self._html_output(u'<li>%(errors)s%(label)s %(field)s<span class="help-text">%(help_text)s</span></li>', u'<li>%s</li>', '</li>', u' %s', False)
30
31
32 def iterable(obj):
33     try:
34         iter(obj)
35         return True
36     except TypeError:
37         return False
38
39
40 def capfirst(text):
41     try:
42         return '%s%s' % (text[0].upper(), text[1:])
43     except IndexError:
44         return ''
45
46
47
48 def simple_title(tags):
49     mapping = {
50         'author': u'Autor',
51         'theme': u'motyw',
52         'epoch': u'epoka',
53         'genre': u'gatunek',
54         'kind': u'rodzaj',
55         'set': u'półka',
56     }
57
58     title = []
59     for tag in tags:
60         title.append("%s: %s" % (mapping[tag.category], tag.name))
61     return capfirst(', '.join(title))
62
63
64 def book_stub_title(book):
65     return ', '.join((book.author, book.title))
66
67
68 @register.simple_tag
69 def book_title(book, html_links=False):
70     try:
71         names = list(book.tags.filter(category='author'))
72     except AttributeError:
73         return book_stub_title(book)
74
75     books = []
76     while book:
77         books.append(book)
78         book = book.parent
79     names.extend(reversed(books))
80
81     if html_links:
82         names = ['<a href="%s">%s</a>' % (tag.get_absolute_url(), tag.name) for tag in names]
83     else:
84         names = [tag.name for tag in names]
85
86     return ', '.join(names)
87
88
89 @register.simple_tag
90 def book_title_html(book):
91     return book_title(book, html_links=True)
92
93
94 @register.simple_tag
95 def title_from_tags(tags):
96     def split_tags(tags):
97         result = {}
98         for tag in tags:
99             result[tag.category] = tag
100         return result
101
102     # TODO: Remove this after adding flection mechanism
103     return simple_title(tags)
104
105     class Flection(object):
106         def get_case(self, name, flection):
107             return name
108     flection = Flection()
109
110     self = split_tags(tags)
111
112     title = u''
113
114     # Specjalny przypadek oglądania wszystkich lektur na danej półce
115     if len(self) == 1 and 'set' in self:
116         return u'Półka %s' % self['set']
117
118     # Specjalny przypadek "Twórczość w pozytywizmie", wtedy gdy tylko epoka
119     # jest wybrana przez użytkownika
120     if 'epoch' in self and len(self) == 1:
121         text = u'Twórczość w %s' % flection.get_case(unicode(self['epoch']), u'miejscownik')
122         return capfirst(text)
123
124     # Specjalny przypadek "Dramat w twórczości Sofoklesa", wtedy gdy podane
125     # są tylko rodzaj literacki i autor
126     if 'kind' in self and 'author' in self and len(self) == 2:
127         text = u'%s w twórczości %s' % (unicode(self['kind']),
128             flection.get_case(unicode(self['author']), u'dopełniacz'))
129         return capfirst(text)
130
131     # Przypadki ogólniejsze
132     if 'theme' in self:
133         title += u'Motyw %s' % unicode(self['theme'])
134
135     if 'genre' in self:
136         if 'theme' in self:
137             title += u' w %s' % flection.get_case(unicode(self['genre']), u'miejscownik')
138         else:
139             title += unicode(self['genre'])
140
141     if 'kind' in self or 'author' in self or 'epoch' in self:
142         if 'genre' in self or 'theme' in self:
143             if 'kind' in self:
144                 title += u' w %s ' % flection.get_case(unicode(self['kind']), u'miejscownik')
145             else:
146                 title += u' w twórczości '
147         else:
148             title += u'%s ' % unicode(self.get('kind', u'twórczość'))
149
150     if 'author' in self:
151         title += flection.get_case(unicode(self['author']), u'dopełniacz')
152     elif 'epoch' in self:
153         title += flection.get_case(unicode(self['epoch']), u'dopełniacz')
154
155     return capfirst(title)
156
157
158 @register.simple_tag
159 def user_creation_form():
160     return RegistrationForm(prefix='registration').as_ul()
161
162
163 @register.simple_tag
164 def authentication_form():
165     return LoginForm(prefix='login').as_ul()
166
167
168 @register.inclusion_tag('catalogue/breadcrumbs.html')
169 def breadcrumbs(tags, search_form=True):
170     from catalogue.forms import SearchForm
171     context = {'tag_list': tags}
172     try:
173         max_tag_list = settings.MAX_TAG_LIST
174     except AttributeError:
175         max_tag_list = -1
176     if search_form and (max_tag_list == -1 or len(tags) < max_tag_list):
177         context['search_form'] = SearchForm(tags=tags)
178     return context
179
180
181 @register.tag
182 def catalogue_url(parser, token):
183     bits = token.split_contents()
184     tag_name = bits[0]
185
186     tags_to_add = []
187     tags_to_remove = []
188     for bit in bits[1:]:
189         if bit[0] == '-':
190             tags_to_remove.append(bit[1:])
191         else:
192             tags_to_add.append(bit)
193
194     return CatalogueURLNode(tags_to_add, tags_to_remove)
195
196
197 class CatalogueURLNode(Node):
198     def __init__(self, tags_to_add, tags_to_remove):
199         self.tags_to_add = [Variable(tag) for tag in tags_to_add]
200         self.tags_to_remove = [Variable(tag) for tag in tags_to_remove]
201
202     def render(self, context):
203         tags_to_add = []
204         tags_to_remove = []
205
206         for tag_variable in self.tags_to_add:
207             tag = tag_variable.resolve(context)
208             if isinstance(tag, (list, dict)):
209                 tags_to_add += [t for t in tag]
210             else:
211                 tags_to_add.append(tag)
212
213         for tag_variable in self.tags_to_remove:
214             tag = tag_variable.resolve(context)
215             if iterable(tag):
216                 tags_to_remove += [t for t in tag]
217             else:
218                 tags_to_remove.append(tag)
219
220         tag_slugs = [tag.url_chunk for tag in tags_to_add]
221         for tag in tags_to_remove:
222             try:
223                 tag_slugs.remove(tag.url_chunk)
224             except KeyError:
225                 pass
226
227         if len(tag_slugs) > 0:
228             return reverse('tagged_object_list', kwargs={'tags': '/'.join(tag_slugs)})
229         else:
230             return reverse('main_page')
231
232
233 @register.inclusion_tag('catalogue/latest_blog_posts.html')
234 def latest_blog_posts(feed_url, posts_to_show=5):
235     try:
236         feed = feedparser.parse(str(feed_url))
237         posts = []
238         for i in range(posts_to_show):
239             pub_date = feed['entries'][i].updated_parsed
240             published = datetime.date(pub_date[0], pub_date[1], pub_date[2] )
241             posts.append({
242                 'title': feed['entries'][i].title,
243                 'summary': feed['entries'][i].summary,
244                 'link': feed['entries'][i].link,
245                 'date': published,
246                 })
247         return {'posts': posts}
248     except:
249         return {'posts': []}
250
251
252 @register.inclusion_tag('catalogue/tag_list.html')
253 def tag_list(tags, choices=None):
254     if choices is None:
255         choices = []
256     if len(tags) == 1:
257         one_tag = tags[0]
258     return locals()
259
260
261 @register.inclusion_tag('catalogue/folded_tag_list.html')
262 def folded_tag_list(tags, choices=None):
263     tags = [tag for tag in tags if tag.count]
264     if choices is None:
265         choices = []
266     some_tags_hidden = False
267     tag_count = len(tags)
268
269     if tag_count == 1:
270         one_tag = tags[0]
271     else:
272         shown_tags = [tag for tag in tags if tag.main_page]
273         if tag_count > len(shown_tags):
274             some_tags_hidden = True
275     return locals()
276