better related books
[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 datetime
6 import feedparser
7 import re
8
9 from django import template
10 from django.template import Node, Variable
11 from django.utils.encoding import smart_str
12 from django.core.cache import get_cache
13 from django.core.urlresolvers import reverse
14 from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
15 from django.db.models import Q
16 from django.conf import settings
17 from django.template.defaultfilters import stringfilter
18 from django.utils.translation import ugettext as _
19
20 from catalogue.utils import split_tags
21 from catalogue.models import Book, Fragment
22
23 register = template.Library()
24
25
26 class RegistrationForm(UserCreationForm):
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 class LoginForm(AuthenticationForm):
33     def as_ul(self):
34         "Returns this form rendered as HTML <li>s -- excluding the <ul></ul>."
35         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)
36
37
38 def iterable(obj):
39     try:
40         iter(obj)
41         return True
42     except TypeError:
43         return False
44
45
46 def capfirst(text):
47     try:
48         return '%s%s' % (text[0].upper(), text[1:])
49     except IndexError:
50         return ''
51
52
53
54 def simple_title(tags):
55     title = []
56     for tag in tags:
57         title.append("%s: %s" % (_(tag.category), tag.name))
58     return capfirst(', '.join(title))
59
60
61 @register.simple_tag
62 def book_title(book, html_links=False):
63     return book.pretty_title(html_links)
64
65
66 @register.simple_tag
67 def book_title_html(book):
68     return book_title(book, html_links=True)
69
70
71 @register.simple_tag
72 def title_from_tags(tags):
73     def split_tags(tags):
74         result = {}
75         for tag in tags:
76             result[tag.category] = tag
77         return result
78
79     # TODO: Remove this after adding flection mechanism
80     return simple_title(tags)
81
82     class Flection(object):
83         def get_case(self, name, flection):
84             return name
85     flection = Flection()
86
87     self = split_tags(tags)
88
89     title = u''
90
91     # Specjalny przypadek oglądania wszystkich lektur na danej półce
92     if len(self) == 1 and 'set' in self:
93         return u'Półka %s' % self['set']
94
95     # Specjalny przypadek "Twórczość w pozytywizmie", wtedy gdy tylko epoka
96     # jest wybrana przez użytkownika
97     if 'epoch' in self and len(self) == 1:
98         text = u'Twórczość w %s' % flection.get_case(unicode(self['epoch']), u'miejscownik')
99         return capfirst(text)
100
101     # Specjalny przypadek "Dramat w twórczości Sofoklesa", wtedy gdy podane
102     # są tylko rodzaj literacki i autor
103     if 'kind' in self and 'author' in self and len(self) == 2:
104         text = u'%s w twórczości %s' % (unicode(self['kind']),
105             flection.get_case(unicode(self['author']), u'dopełniacz'))
106         return capfirst(text)
107
108     # Przypadki ogólniejsze
109     if 'theme' in self:
110         title += u'Motyw %s' % unicode(self['theme'])
111
112     if 'genre' in self:
113         if 'theme' in self:
114             title += u' w %s' % flection.get_case(unicode(self['genre']), u'miejscownik')
115         else:
116             title += unicode(self['genre'])
117
118     if 'kind' in self or 'author' in self or 'epoch' in self:
119         if 'genre' in self or 'theme' in self:
120             if 'kind' in self:
121                 title += u' w %s ' % flection.get_case(unicode(self['kind']), u'miejscownik')
122             else:
123                 title += u' w twórczości '
124         else:
125             title += u'%s ' % unicode(self.get('kind', u'twórczość'))
126
127     if 'author' in self:
128         title += flection.get_case(unicode(self['author']), u'dopełniacz')
129     elif 'epoch' in self:
130         title += flection.get_case(unicode(self['epoch']), u'dopełniacz')
131
132     return capfirst(title)
133
134
135 @register.simple_tag
136 def book_tree(book_list, books_by_parent):
137     text = "".join("<li><a href='%s'>%s</a>%s</li>" % (
138         book.get_absolute_url(), book.title, book_tree(books_by_parent.get(book, ()), books_by_parent)
139         ) for book in book_list)
140
141     if text:
142         return "<ol>%s</ol>" % text
143     else:
144         return ''
145
146 @register.simple_tag
147 def book_tree_texml(book_list, books_by_parent, depth=1):
148     return "".join("""
149             <cmd name='hspace'><parm>%(depth)dem</parm></cmd>%(title)s
150             <spec cat='align' /><cmd name="note"><parm>%(audiences)s</parm></cmd>
151             <spec cat='align' /><cmd name="note"><parm>%(audiobook)s</parm></cmd>
152             <ctrl ch='\\' />
153             %(children)s
154             """ % {
155                 "depth": depth,
156                 "title": book.title, 
157                 "audiences": ", ".join(book.audiences_pl()),
158                 "audiobook": "audiobook" if book.has_media('mp3') else "",
159                 "children": book_tree_texml(books_by_parent.get(book.id, ()), books_by_parent, depth + 1)
160             } for book in book_list)
161
162
163 @register.simple_tag
164 def all_editors(extra_info):
165     editors = []
166     if 'editors' in extra_info:
167         editors += extra_info['editors']
168     if 'technical_editors' in extra_info:
169         editors += extra_info['technical_editors']
170     # support for extra_info-s from librarian<1.2
171     if 'editor' in extra_info:
172         editors.append(extra_info['editor'])
173     if 'technical_editor' in extra_info:
174         editors.append(extra_info['technical_editor'])
175     return ', '.join(
176                      ' '.join(p.strip() for p in person.rsplit(',', 1)[::-1])
177                      for person in sorted(set(editors)))
178
179
180 @register.simple_tag
181 def user_creation_form():
182     return RegistrationForm(prefix='registration').as_ul()
183
184
185 @register.simple_tag
186 def authentication_form():
187     return LoginForm(prefix='login').as_ul()
188
189
190 @register.tag
191 def catalogue_url(parser, token):
192     bits = token.split_contents()
193     tag_name = bits[0]
194
195     tags_to_add = []
196     tags_to_remove = []
197     for bit in bits[1:]:
198         if bit[0] == '-':
199             tags_to_remove.append(bit[1:])
200         else:
201             tags_to_add.append(bit)
202
203     return CatalogueURLNode(tags_to_add, tags_to_remove)
204
205
206 class CatalogueURLNode(Node):
207     def __init__(self, tags_to_add, tags_to_remove):
208         self.tags_to_add = [Variable(tag) for tag in tags_to_add]
209         self.tags_to_remove = [Variable(tag) for tag in tags_to_remove]
210
211     def render(self, context):
212         tags_to_add = []
213         tags_to_remove = []
214
215         for tag_variable in self.tags_to_add:
216             tag = tag_variable.resolve(context)
217             if isinstance(tag, (list, dict)):
218                 tags_to_add += [t for t in tag]
219             else:
220                 tags_to_add.append(tag)
221
222         for tag_variable in self.tags_to_remove:
223             tag = tag_variable.resolve(context)
224             if iterable(tag):
225                 tags_to_remove += [t for t in tag]
226             else:
227                 tags_to_remove.append(tag)
228
229         tag_slugs = [tag.url_chunk for tag in tags_to_add]
230         for tag in tags_to_remove:
231             try:
232                 tag_slugs.remove(tag.url_chunk)
233             except KeyError:
234                 pass
235
236         if len(tag_slugs) > 0:
237             return reverse('tagged_object_list', kwargs={'tags': '/'.join(tag_slugs)})
238         else:
239             return reverse('main_page')
240
241
242 @register.inclusion_tag('catalogue/latest_blog_posts.html')
243 def latest_blog_posts(feed_url, posts_to_show=5):
244     try:
245         feed = feedparser.parse(str(feed_url))
246         posts = []
247         for i in range(posts_to_show):
248             pub_date = feed['entries'][i].updated_parsed
249             published = datetime.date(pub_date[0], pub_date[1], pub_date[2] )
250             posts.append({
251                 'title': feed['entries'][i].title,
252                 'summary': feed['entries'][i].summary,
253                 'link': feed['entries'][i].link,
254                 'date': published,
255                 })
256         return {'posts': posts}
257     except:
258         return {'posts': []}
259
260
261 @register.inclusion_tag('catalogue/tag_list.html')
262 def tag_list(tags, choices=None):
263     if choices is None:
264         choices = []
265     if len(tags) == 1:
266         one_tag = tags[0]
267     return locals()
268
269 @register.inclusion_tag('catalogue/inline_tag_list.html')
270 def inline_tag_list(tags, choices=None):
271     if choices is None:
272         choices = []
273     if len(tags) == 1:
274         one_tag = tags[0]
275     return locals()
276
277
278 @register.inclusion_tag('catalogue/book_info.html')
279 def book_info(book):
280     return locals()
281
282
283 @register.inclusion_tag('catalogue/book_wide.html', takes_context=True)
284 def book_wide(context, book):
285     formats = {}
286     # files generated during publication
287     for ebook_format in book.ebook_formats:
288         if book.has_media(ebook_format):
289             formats[ebook_format] = book.get_media(ebook_format)
290
291     return {
292         'related': book.related_info(),
293         'book': book,
294         'formats': formats,
295         'extra_info': book.get_extra_info_value(),
296         'request': context.get('request'),
297         'fragment': book.choose_fragment(),
298     }
299
300
301 @register.inclusion_tag('catalogue/book_short.html', takes_context=True)
302 def book_short(context, book):
303     return {
304         'related': book.related_info(),
305         'book': book,
306         'request': context.get('request'),
307     }
308
309
310 @register.inclusion_tag('catalogue/book_mini_box.html')
311 def book_mini(book):
312     return {
313         'related': book.related_info(),
314         'book': book,
315     }
316
317
318 @register.inclusion_tag('catalogue/work-list.html', takes_context=True)
319 def work_list(context, object_list):
320     request = context.get('request')
321     if object_list:
322         object_type = type(object_list[0]).__name__
323     return locals()
324
325
326 @register.inclusion_tag('catalogue/fragment_promo.html')
327 def fragment_promo(arg=None):
328     if arg is None:
329         fragments = Fragment.objects.all().order_by('?')
330         fragment = fragments[0] if fragments.exists() else None
331     elif isinstance(arg, Book):
332         fragment = arg.choose_fragment()
333     else:
334         fragments = Fragment.tagged.with_all(arg).order_by('?')
335         fragment = fragments[0] if fragments.exists() else None
336
337     return {
338         'fragment': fragment,
339     }
340
341
342 @register.inclusion_tag('catalogue/related_books.html')
343 def related_books(book, limit=6):
344     related = list(Book.objects.filter(
345         common_slug=book.common_slug).exclude(pk=book.pk)[:limit])
346     limit -= len(related)
347     if limit:
348         related += Book.tagged.related_to(book,
349                 Book.objects.exclude(common_slug=book.common_slug),
350                 ignore_by_tag=book.book_tag())[:limit]
351     return {
352         'books': related,
353     }
354
355
356 @register.filter
357 @stringfilter
358 def removewholetags(value, tags):
359     """Removes a space separated list of [X]HTML tags from the output.
360
361     FIXME: It makes the assumption the removed tags aren't nested.
362
363     """
364     tags = [re.escape(tag) for tag in tags.split()]
365     tags_re = u'(%s)' % u'|'.join(tags)
366     tag_re = re.compile(ur'<%s[^>]*>.*?</\s*\1\s*>' % tags_re, re.U)
367     value = tag_re.sub(u'', value)
368     return value