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.
8 from django import template
9 from django.template import Node, Variable, Template, Context
10 from django.core.cache import cache
11 from django.core.urlresolvers import reverse
12 from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
13 from django.utils.translation import ugettext as _
15 from catalogue import forms
16 from catalogue.utils import split_tags
17 from catalogue.models import Book, Fragment, Tag
19 register = template.Library()
22 class RegistrationForm(UserCreationForm):
24 "Returns this form rendered as HTML <li>s -- excluding the <ul></ul>."
25 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 class LoginForm(AuthenticationForm):
30 "Returns this form rendered as HTML <li>s -- excluding the <ul></ul>."
31 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)
44 return '%s%s' % (text[0].upper(), text[1:])
49 def build_absolute_uri(uri, request):
50 return request.build_absolute_uri(uri)
54 def html_title_from_tags(tags):
56 return title_from_tags(tags)
57 template = Template("{{ category }}: <a href='{{ tag.get_absolute_url }}'>{{ tag.name }}</a>")
58 return capfirst(",<br/>".join(
59 template.render(Context({'tag': tag, 'category': _(tag.category)})) for tag in tags))
63 def simple_title(tags):
66 title.append("%s: %s" % (_(tag.category), tag.name))
67 return capfirst(', '.join(title))
71 def book_title(book, html_links=False):
72 return book.pretty_title(html_links)
76 def book_title_html(book):
77 return book_title(book, html_links=True)
81 def title_from_tags(tags):
85 result[tag.category] = tag
88 # TODO: Remove this after adding flection mechanism
89 return simple_title(tags)
91 class Flection(object):
92 def get_case(self, name, flection):
96 self = split_tags(tags)
100 # Specjalny przypadek oglądania wszystkich lektur na danej półce
101 if len(self) == 1 and 'set' in self:
102 return u'Półka %s' % self['set']
104 # Specjalny przypadek "Twórczość w pozytywizmie", wtedy gdy tylko epoka
105 # jest wybrana przez użytkownika
106 if 'epoch' in self and len(self) == 1:
107 text = u'Twórczość w %s' % flection.get_case(unicode(self['epoch']), u'miejscownik')
108 return capfirst(text)
110 # Specjalny przypadek "Dramat w twórczości Sofoklesa", wtedy gdy podane
111 # są tylko rodzaj literacki i autor
112 if 'kind' in self and 'author' in self and len(self) == 2:
113 text = u'%s w twórczości %s' % (unicode(self['kind']),
114 flection.get_case(unicode(self['author']), u'dopełniacz'))
115 return capfirst(text)
117 # Przypadki ogólniejsze
119 title += u'Motyw %s' % unicode(self['theme'])
123 title += u' w %s' % flection.get_case(unicode(self['genre']), u'miejscownik')
125 title += unicode(self['genre'])
127 if 'kind' in self or 'author' in self or 'epoch' in self:
128 if 'genre' in self or 'theme' in self:
130 title += u' w %s ' % flection.get_case(unicode(self['kind']), u'miejscownik')
132 title += u' w twórczości '
134 title += u'%s ' % unicode(self.get('kind', u'twórczość'))
137 title += flection.get_case(unicode(self['author']), u'dopełniacz')
138 elif 'epoch' in self:
139 title += flection.get_case(unicode(self['epoch']), u'dopełniacz')
141 return capfirst(title)
145 def book_tree(book_list, books_by_parent):
146 text = "".join("<li><a href='%s'>%s</a>%s</li>" % (
147 book.get_absolute_url(), book.title, book_tree(books_by_parent.get(book, ()), books_by_parent)
148 ) for book in book_list)
151 return "<ol>%s</ol>" % text
156 def audiobook_tree(book_list, books_by_parent):
157 text = "".join("<li><a class='open-player' href='%s'>%s</a>%s</li>" % (
158 reverse("book_player", args=[book.slug]), book.title, audiobook_tree(books_by_parent.get(book, ()), books_by_parent)
159 ) for book in book_list)
162 return "<ol>%s</ol>" % text
167 def book_tree_texml(book_list, books_by_parent, depth=1):
169 <cmd name='hspace'><parm>%(depth)dem</parm></cmd>%(title)s
170 <spec cat='align' /><cmd name="note"><parm>%(audiences)s</parm></cmd>
171 <spec cat='align' /><cmd name="note"><parm>%(audiobook)s</parm></cmd>
177 "audiences": ", ".join(book.audiences_pl()),
178 "audiobook": "audiobook" if book.has_media('mp3') else "",
179 "children": book_tree_texml(books_by_parent.get(book.id, ()), books_by_parent, depth + 1)
180 } for book in book_list)
184 def all_editors(extra_info):
186 if 'editors' in extra_info:
187 editors += extra_info['editors']
188 if 'technical_editors' in extra_info:
189 editors += extra_info['technical_editors']
190 # support for extra_info-s from librarian<1.2
191 if 'editor' in extra_info:
192 editors.append(extra_info['editor'])
193 if 'technical_editor' in extra_info:
194 editors.append(extra_info['technical_editor'])
196 ' '.join(p.strip() for p in person.rsplit(',', 1)[::-1])
197 for person in sorted(set(editors)))
201 def user_creation_form():
202 return RegistrationForm(prefix='registration').as_ul()
206 def authentication_form():
207 return LoginForm(prefix='login').as_ul()
211 def catalogue_url(parser, token):
212 bits = token.split_contents()
219 tags_to_remove.append(bit[1:])
221 tags_to_add.append(bit)
223 return CatalogueURLNode(tags_to_add, tags_to_remove)
226 class CatalogueURLNode(Node):
227 def __init__(self, tags_to_add, tags_to_remove):
228 self.tags_to_add = [Variable(tag) for tag in tags_to_add]
229 self.tags_to_remove = [Variable(tag) for tag in tags_to_remove]
231 def render(self, context):
235 for tag_variable in self.tags_to_add:
236 tag = tag_variable.resolve(context)
237 if isinstance(tag, (list, dict)):
238 tags_to_add += [t for t in tag]
240 tags_to_add.append(tag)
242 for tag_variable in self.tags_to_remove:
243 tag = tag_variable.resolve(context)
245 tags_to_remove += [t for t in tag]
247 tags_to_remove.append(tag)
249 tag_slugs = [tag.url_chunk for tag in tags_to_add]
250 for tag in tags_to_remove:
252 tag_slugs.remove(tag.url_chunk)
256 if len(tag_slugs) > 0:
257 return reverse('tagged_object_list', kwargs={'tags': '/'.join(tag_slugs)})
259 return reverse('main_page')
262 @register.inclusion_tag('catalogue/latest_blog_posts.html')
263 def latest_blog_posts(feed_url, posts_to_show=5):
265 feed = feedparser.parse(str(feed_url))
267 for i in range(posts_to_show):
268 pub_date = feed['entries'][i].updated_parsed
269 published = datetime.date(pub_date[0], pub_date[1], pub_date[2] )
271 'title': feed['entries'][i].title,
272 'summary': feed['entries'][i].summary,
273 'link': feed['entries'][i].link,
276 return {'posts': posts}
281 @register.inclusion_tag('catalogue/tag_list.html')
282 def tag_list(tags, choices=None):
285 if len(tags) == 1 and tags[0].category not in [t.category for t in choices]:
290 @register.inclusion_tag('catalogue/inline_tag_list.html')
291 def inline_tag_list(tags, choices=None):
292 return tag_list(tags, choices)
295 @register.inclusion_tag('catalogue/book_info.html')
300 @register.inclusion_tag('catalogue/book_wide.html', takes_context=True)
301 def book_wide(context, book):
302 theme_counter = book.theme_counter
303 book_themes = Tag.objects.filter(pk__in=theme_counter.keys())
304 for tag in book_themes:
305 tag.count = theme_counter[tag.pk]
306 extra_info = book.get_extra_info_value()
307 hide_about = extra_info.get('about', '').startswith('http://wiki.wolnepodreczniki.pl')
311 'main_link': reverse('book_text', args=[book.slug]) if book.html_file else None,
312 'related': book.related_info(),
313 'extra_info': book.get_extra_info_value(),
314 'hide_about': hide_about,
315 'themes': book_themes,
316 'custom_pdf_form': forms.CustomPDFForm(),
317 'request': context.get('request'),
321 @register.inclusion_tag('catalogue/book_short.html', takes_context=True)
322 def book_short(context, book):
325 'main_link': book.get_absolute_url(),
326 'related': book.related_info(),
327 'request': context.get('request'),
331 @register.inclusion_tag('catalogue/book_mini_box.html')
335 'related': book.related_info(),
339 @register.inclusion_tag('catalogue/work-list.html', takes_context=True)
340 def work_list(context, object_list):
341 request = context.get('request')
343 object_type = type(object_list[0]).__name__
347 @register.inclusion_tag('catalogue/fragment_promo.html')
348 def fragment_promo(arg=None):
350 fragments = Fragment.objects.all().order_by('?')
351 fragment = fragments[0] if fragments.exists() else None
352 elif isinstance(arg, Book):
353 fragment = arg.choose_fragment()
355 fragments = Fragment.tagged.with_all(arg).order_by('?')
356 fragment = fragments[0] if fragments.exists() else None
359 'fragment': fragment,
363 @register.inclusion_tag('catalogue/related_books.html')
364 def related_books(book, limit=6, random=1):
365 cache_key = "catalogue.related_books.%d.%d" % (book.id, limit - random)
366 related = cache.get(cache_key)
368 related = list(Book.objects.filter(
369 common_slug=book.common_slug).exclude(pk=book.pk)[:limit])
370 limit -= len(related)
372 related += Book.tagged.related_to(book,
373 Book.objects.exclude(common_slug=book.common_slug),
374 ignore_by_tag=book.book_tag())[:limit-random]
375 cache.set(cache_key, related, 1800)
377 related += list(Book.objects.exclude(
378 pk__in=[b.pk for b in related] + [book.pk]
379 ).order_by('?')[:random])
385 @register.inclusion_tag('catalogue/menu.html')
386 def catalogue_menu():
387 tags = Tag.objects.filter(
388 category__in=('author', 'epoch', 'genre', 'kind', 'theme')
389 ).exclude(book_count=0)
390 return split_tags(tags)
395 def tag_url(category, slug):
396 return reverse('catalogue.views.tagged_object_list', args=[
397 '/'.join((Tag.categories_dict[category], slug))