detail page getting shape
[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 from django.utils.translation import ugettext as _
16
17 from catalogue.forms import SearchForm
18 from catalogue.utils import split_tags
19
20
21 register = template.Library()
22
23
24 class RegistrationForm(UserCreationForm):
25     def as_ul(self):
26         "Returns this form rendered as HTML <li>s -- excluding the <ul></ul>."
27         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)
28
29
30 class LoginForm(AuthenticationForm):
31     def as_ul(self):
32         "Returns this form rendered as HTML <li>s -- excluding the <ul></ul>."
33         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)
34
35
36 def iterable(obj):
37     try:
38         iter(obj)
39         return True
40     except TypeError:
41         return False
42
43
44 def capfirst(text):
45     try:
46         return '%s%s' % (text[0].upper(), text[1:])
47     except IndexError:
48         return ''
49
50
51
52 def simple_title(tags):
53     title = []
54     for tag in tags:
55         title.append("%s: %s" % (_(tag.category), tag.name))
56     return capfirst(', '.join(title))
57
58
59 @register.simple_tag
60 def book_title(book, html_links=False):
61     return book.pretty_title(html_links)
62
63
64 @register.simple_tag
65 def book_title_html(book):
66     return book_title(book, html_links=True)
67
68
69 @register.simple_tag
70 def title_from_tags(tags):
71     def split_tags(tags):
72         result = {}
73         for tag in tags:
74             result[tag.category] = tag
75         return result
76
77     # TODO: Remove this after adding flection mechanism
78     return simple_title(tags)
79
80     class Flection(object):
81         def get_case(self, name, flection):
82             return name
83     flection = Flection()
84
85     self = split_tags(tags)
86
87     title = u''
88
89     # Specjalny przypadek oglądania wszystkich lektur na danej półce
90     if len(self) == 1 and 'set' in self:
91         return u'Półka %s' % self['set']
92
93     # Specjalny przypadek "Twórczość w pozytywizmie", wtedy gdy tylko epoka
94     # jest wybrana przez użytkownika
95     if 'epoch' in self and len(self) == 1:
96         text = u'Twórczość w %s' % flection.get_case(unicode(self['epoch']), u'miejscownik')
97         return capfirst(text)
98
99     # Specjalny przypadek "Dramat w twórczości Sofoklesa", wtedy gdy podane
100     # są tylko rodzaj literacki i autor
101     if 'kind' in self and 'author' in self and len(self) == 2:
102         text = u'%s w twórczości %s' % (unicode(self['kind']),
103             flection.get_case(unicode(self['author']), u'dopełniacz'))
104         return capfirst(text)
105
106     # Przypadki ogólniejsze
107     if 'theme' in self:
108         title += u'Motyw %s' % unicode(self['theme'])
109
110     if 'genre' in self:
111         if 'theme' in self:
112             title += u' w %s' % flection.get_case(unicode(self['genre']), u'miejscownik')
113         else:
114             title += unicode(self['genre'])
115
116     if 'kind' in self or 'author' in self or 'epoch' in self:
117         if 'genre' in self or 'theme' in self:
118             if 'kind' in self:
119                 title += u' w %s ' % flection.get_case(unicode(self['kind']), u'miejscownik')
120             else:
121                 title += u' w twórczości '
122         else:
123             title += u'%s ' % unicode(self.get('kind', u'twórczość'))
124
125     if 'author' in self:
126         title += flection.get_case(unicode(self['author']), u'dopełniacz')
127     elif 'epoch' in self:
128         title += flection.get_case(unicode(self['epoch']), u'dopełniacz')
129
130     return capfirst(title)
131
132
133 @register.simple_tag
134 def book_tree(book_list, books_by_parent):
135     text = "".join("<li><a href='%s'>%s</a>%s</li>" % (
136         book.get_absolute_url(), book.title, book_tree(books_by_parent.get(book, ()), books_by_parent)
137         ) for book in book_list)
138
139     if text:
140         return "<ol>%s</ol>" % text
141     else:
142         return ''
143
144 @register.simple_tag
145 def book_tree_texml(book_list, books_by_parent, depth=1):
146     return "".join("""
147             <cmd name='hspace'><parm>%(depth)dem</parm></cmd>%(title)s
148             <spec cat='align' /><cmd name="note"><parm>%(audiences)s</parm></cmd>
149             <spec cat='align' /><cmd name="note"><parm>%(audiobook)s</parm></cmd>
150             <ctrl ch='\\' />
151             %(children)s
152             """ % {
153                 "depth": depth,
154                 "title": book.title, 
155                 "audiences": ", ".join(book.audiences_pl()),
156                 "audiobook": "audiobook" if book.has_media('mp3') else "",
157                 "children": book_tree_texml(books_by_parent.get(book.id, ()), books_by_parent, depth + 1)
158             } for book in book_list)
159
160
161 @register.simple_tag
162 def all_editors(extra_info):
163     editors = []
164     if 'editors' in extra_info:
165         editors += extra_info['editors']
166     if 'technical_editors' in extra_info:
167         editors += extra_info['technical_editors']
168     # support for extra_info-s from librarian<1.2
169     if 'editor' in extra_info:
170         editors.append(extra_info['editor'])
171     if 'technical_editor' in extra_info:
172         editors.append(extra_info['technical_editor'])
173     return ', '.join(
174                      ' '.join(p.strip() for p in person.rsplit(',', 1)[::-1])
175                      for person in sorted(set(editors)))
176
177
178 @register.simple_tag
179 def user_creation_form():
180     return RegistrationForm(prefix='registration').as_ul()
181
182
183 @register.simple_tag
184 def authentication_form():
185     return LoginForm(prefix='login').as_ul()
186
187
188 @register.tag
189 def catalogue_url(parser, token):
190     bits = token.split_contents()
191     tag_name = bits[0]
192
193     tags_to_add = []
194     tags_to_remove = []
195     for bit in bits[1:]:
196         if bit[0] == '-':
197             tags_to_remove.append(bit[1:])
198         else:
199             tags_to_add.append(bit)
200
201     return CatalogueURLNode(tags_to_add, tags_to_remove)
202
203
204 class CatalogueURLNode(Node):
205     def __init__(self, tags_to_add, tags_to_remove):
206         self.tags_to_add = [Variable(tag) for tag in tags_to_add]
207         self.tags_to_remove = [Variable(tag) for tag in tags_to_remove]
208
209     def render(self, context):
210         tags_to_add = []
211         tags_to_remove = []
212
213         for tag_variable in self.tags_to_add:
214             tag = tag_variable.resolve(context)
215             if isinstance(tag, (list, dict)):
216                 tags_to_add += [t for t in tag]
217             else:
218                 tags_to_add.append(tag)
219
220         for tag_variable in self.tags_to_remove:
221             tag = tag_variable.resolve(context)
222             if iterable(tag):
223                 tags_to_remove += [t for t in tag]
224             else:
225                 tags_to_remove.append(tag)
226
227         tag_slugs = [tag.url_chunk for tag in tags_to_add]
228         for tag in tags_to_remove:
229             try:
230                 tag_slugs.remove(tag.url_chunk)
231             except KeyError:
232                 pass
233
234         if len(tag_slugs) > 0:
235             return reverse('tagged_object_list', kwargs={'tags': '/'.join(tag_slugs)})
236         else:
237             return reverse('main_page')
238
239
240 @register.inclusion_tag('catalogue/latest_blog_posts.html')
241 def latest_blog_posts(feed_url, posts_to_show=5):
242     try:
243         feed = feedparser.parse(str(feed_url))
244         posts = []
245         for i in range(posts_to_show):
246             pub_date = feed['entries'][i].updated_parsed
247             published = datetime.date(pub_date[0], pub_date[1], pub_date[2] )
248             posts.append({
249                 'title': feed['entries'][i].title,
250                 'summary': feed['entries'][i].summary,
251                 'link': feed['entries'][i].link,
252                 'date': published,
253                 })
254         return {'posts': posts}
255     except:
256         return {'posts': []}
257
258
259 @register.inclusion_tag('catalogue/tag_list.html')
260 def tag_list(tags, choices=None):
261     if choices is None:
262         choices = []
263     if len(tags) == 1:
264         one_tag = tags[0]
265     return locals()
266
267 @register.inclusion_tag('catalogue/inline_tag_list.html')
268 def inline_tag_list(tags, choices=None):
269     if choices is None:
270         choices = []
271     if len(tags) == 1:
272         one_tag = tags[0]
273     return locals()
274
275
276 @register.inclusion_tag('catalogue/book_info.html')
277 def book_info(book):
278     return locals()
279
280
281 @register.inclusion_tag('catalogue/book_wide.html')
282 def book_wide(book):
283     tags = book.tags.filter(category__in=('author', 'kind', 'genre', 'epoch'))
284     tags = split_tags(tags)
285
286     formats = {}
287     # files generated during publication
288     for ebook_format in book.ebook_formats:
289         if book.has_media(ebook_format):
290             formats[ebook_format] = book.get_media(ebook_format)
291
292     extra_info = book.get_extra_info_value()
293
294     return locals()