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:])
50 def html_title_from_tags(tags):
52 return title_from_tags(tags)
53 template = Template("{{ category }}: <a href='{{ tag.get_absolute_url }}'>{{ tag.name }}</a>")
54 return capfirst(",<br/>".join(
55 template.render(Context({'tag': tag, 'category': _(tag.category)})) for tag in tags))
59 def simple_title(tags):
62 title.append("%s: %s" % (_(tag.category), tag.name))
63 return capfirst(', '.join(title))
67 def book_title(book, html_links=False):
68 return book.pretty_title(html_links)
72 def book_title_html(book):
73 return book_title(book, html_links=True)
77 def title_from_tags(tags):
81 result[tag.category] = tag
84 # TODO: Remove this after adding flection mechanism
85 return simple_title(tags)
87 class Flection(object):
88 def get_case(self, name, flection):
92 self = split_tags(tags)
96 # Specjalny przypadek oglądania wszystkich lektur na danej półce
97 if len(self) == 1 and 'set' in self:
98 return u'Półka %s' % self['set']
100 # Specjalny przypadek "Twórczość w pozytywizmie", wtedy gdy tylko epoka
101 # jest wybrana przez użytkownika
102 if 'epoch' in self and len(self) == 1:
103 text = u'Twórczość w %s' % flection.get_case(unicode(self['epoch']), u'miejscownik')
104 return capfirst(text)
106 # Specjalny przypadek "Dramat w twórczości Sofoklesa", wtedy gdy podane
107 # są tylko rodzaj literacki i autor
108 if 'kind' in self and 'author' in self and len(self) == 2:
109 text = u'%s w twórczości %s' % (unicode(self['kind']),
110 flection.get_case(unicode(self['author']), u'dopełniacz'))
111 return capfirst(text)
113 # Przypadki ogólniejsze
115 title += u'Motyw %s' % unicode(self['theme'])
119 title += u' w %s' % flection.get_case(unicode(self['genre']), u'miejscownik')
121 title += unicode(self['genre'])
123 if 'kind' in self or 'author' in self or 'epoch' in self:
124 if 'genre' in self or 'theme' in self:
126 title += u' w %s ' % flection.get_case(unicode(self['kind']), u'miejscownik')
128 title += u' w twórczości '
130 title += u'%s ' % unicode(self.get('kind', u'twórczość'))
133 title += flection.get_case(unicode(self['author']), u'dopełniacz')
134 elif 'epoch' in self:
135 title += flection.get_case(unicode(self['epoch']), u'dopełniacz')
137 return capfirst(title)
141 def book_tree(book_list, books_by_parent):
142 text = "".join("<li><a href='%s'>%s</a>%s</li>" % (
143 book.get_absolute_url(), book.title, book_tree(books_by_parent.get(book, ()), books_by_parent)
144 ) for book in book_list)
147 return "<ol>%s</ol>" % text
152 def book_tree_texml(book_list, books_by_parent, depth=1):
154 <cmd name='hspace'><parm>%(depth)dem</parm></cmd>%(title)s
155 <spec cat='align' /><cmd name="note"><parm>%(audiences)s</parm></cmd>
156 <spec cat='align' /><cmd name="note"><parm>%(audiobook)s</parm></cmd>
162 "audiences": ", ".join(book.audiences_pl()),
163 "audiobook": "audiobook" if book.has_media('mp3') else "",
164 "children": book_tree_texml(books_by_parent.get(book.id, ()), books_by_parent, depth + 1)
165 } for book in book_list)
169 def all_editors(extra_info):
171 if 'editors' in extra_info:
172 editors += extra_info['editors']
173 if 'technical_editors' in extra_info:
174 editors += extra_info['technical_editors']
175 # support for extra_info-s from librarian<1.2
176 if 'editor' in extra_info:
177 editors.append(extra_info['editor'])
178 if 'technical_editor' in extra_info:
179 editors.append(extra_info['technical_editor'])
181 ' '.join(p.strip() for p in person.rsplit(',', 1)[::-1])
182 for person in sorted(set(editors)))
186 def user_creation_form():
187 return RegistrationForm(prefix='registration').as_ul()
191 def authentication_form():
192 return LoginForm(prefix='login').as_ul()
196 def catalogue_url(parser, token):
197 bits = token.split_contents()
204 tags_to_remove.append(bit[1:])
206 tags_to_add.append(bit)
208 return CatalogueURLNode(tags_to_add, tags_to_remove)
211 class CatalogueURLNode(Node):
212 def __init__(self, tags_to_add, tags_to_remove):
213 self.tags_to_add = [Variable(tag) for tag in tags_to_add]
214 self.tags_to_remove = [Variable(tag) for tag in tags_to_remove]
216 def render(self, context):
220 for tag_variable in self.tags_to_add:
221 tag = tag_variable.resolve(context)
222 if isinstance(tag, (list, dict)):
223 tags_to_add += [t for t in tag]
225 tags_to_add.append(tag)
227 for tag_variable in self.tags_to_remove:
228 tag = tag_variable.resolve(context)
230 tags_to_remove += [t for t in tag]
232 tags_to_remove.append(tag)
234 tag_slugs = [tag.url_chunk for tag in tags_to_add]
235 for tag in tags_to_remove:
237 tag_slugs.remove(tag.url_chunk)
241 if len(tag_slugs) > 0:
242 return reverse('tagged_object_list', kwargs={'tags': '/'.join(tag_slugs)})
244 return reverse('main_page')
247 @register.inclusion_tag('catalogue/latest_blog_posts.html')
248 def latest_blog_posts(feed_url, posts_to_show=5):
250 feed = feedparser.parse(str(feed_url))
252 for i in range(posts_to_show):
253 pub_date = feed['entries'][i].updated_parsed
254 published = datetime.date(pub_date[0], pub_date[1], pub_date[2] )
256 'title': feed['entries'][i].title,
257 'summary': feed['entries'][i].summary,
258 'link': feed['entries'][i].link,
261 return {'posts': posts}
266 @register.inclusion_tag('catalogue/tag_list.html')
267 def tag_list(tags, choices=None):
270 if len(tags) == 1 and tags[0].category not in [t.category for t in choices]:
275 @register.inclusion_tag('catalogue/inline_tag_list.html')
276 def inline_tag_list(tags, choices=None):
277 return tag_list(tags, choices)
280 @register.inclusion_tag('catalogue/book_info.html')
285 @register.inclusion_tag('catalogue/book_wide.html', takes_context=True)
286 def book_wide(context, book):
287 theme_counter = book.theme_counter
288 book_themes = Tag.objects.filter(pk__in=theme_counter.keys())
289 for tag in book_themes:
290 tag.count = theme_counter[tag.pk]
291 extra_info = book.get_extra_info_value()
292 hide_about = extra_info.get('about', '').startswith('http://wiki.wolnepodreczniki.pl')
296 'main_link': reverse('book_text', args=[book.slug]),
297 'related': book.related_info(),
298 'extra_info': book.get_extra_info_value(),
299 'hide_about': hide_about,
300 'themes': book_themes,
301 'custom_pdf_form': forms.CustomPDFForm(),
302 'request': context.get('request'),
306 @register.inclusion_tag('catalogue/book_short.html', takes_context=True)
307 def book_short(context, book):
310 'main_link': book.get_absolute_url(),
311 'related': book.related_info(),
312 'request': context.get('request'),
316 @register.inclusion_tag('catalogue/book_mini_box.html')
320 'related': book.related_info(),
324 @register.inclusion_tag('catalogue/work-list.html', takes_context=True)
325 def work_list(context, object_list):
326 request = context.get('request')
328 object_type = type(object_list[0]).__name__
332 @register.inclusion_tag('catalogue/fragment_promo.html')
333 def fragment_promo(arg=None):
335 fragments = Fragment.objects.all().order_by('?')
336 fragment = fragments[0] if fragments.exists() else None
337 elif isinstance(arg, Book):
338 fragment = arg.choose_fragment()
340 fragments = Fragment.tagged.with_all(arg).order_by('?')
341 fragment = fragments[0] if fragments.exists() else None
344 'fragment': fragment,
348 @register.inclusion_tag('catalogue/related_books.html')
349 def related_books(book, limit=6, random=1):
350 cache_key = "catalogue.related_books.%d.%d" % (book.id, limit - random)
351 related = cache.get(cache_key)
353 related = list(Book.objects.filter(
354 common_slug=book.common_slug).exclude(pk=book.pk)[:limit])
355 limit -= len(related)
357 related += Book.tagged.related_to(book,
358 Book.objects.exclude(common_slug=book.common_slug),
359 ignore_by_tag=book.book_tag())[:limit-random]
360 cache.set(cache_key, related, 1800)
362 related += list(Book.objects.exclude(
363 pk__in=[b.pk for b in related] + [book.pk]
364 ).order_by('?')[:random])
370 @register.inclusion_tag('catalogue/menu.html')
371 def catalogue_menu():
372 tags = Tag.objects.filter(
373 category__in=('author', 'epoch', 'genre', 'kind', 'theme')
374 ).exclude(book_count=0)
375 return split_tags(tags)
380 def tag_url(category, slug):
381 return reverse('catalogue.views.tagged_object_list', args=[
382 '/'.join((Tag.categories_dict[category], slug))