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.
5 from random import randint
6 from urlparse import urlparse
8 from django.conf import settings
9 from django import template
10 from django.template import Node, Variable, Template, Context
11 from django.core.urlresolvers import reverse
12 from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
13 from django.utils.cache import add_never_cache_headers
14 from django.utils.translation import ugettext as _
16 from ssify import ssi_variable
17 from catalogue.models import Book, BookMedia, Fragment, Tag, Source
18 from catalogue.constants import LICENSES
19 from picture.models import Picture
21 register = template.Library()
24 class RegistrationForm(UserCreationForm):
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)
30 class LoginForm(AuthenticationForm):
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)
46 return '%s%s' % (text[0].upper(), text[1:])
52 def html_title_from_tags(tags):
54 return title_from_tags(tags)
55 template = Template("{{ category }}: <a href='{{ tag.get_absolute_url }}'>{{ tag.name }}</a>")
56 return capfirst(",<br/>".join(
57 template.render(Context({'tag': tag, 'category': _(tag.category)})) for tag in tags))
60 def simple_title(tags):
63 title.append("%s: %s" % (_(tag.category), tag.name))
64 return capfirst(', '.join(title))
68 def book_title(book, html_links=False):
69 return book.pretty_title(html_links)
73 def book_title_html(book):
74 return book_title(book, html_links=True)
78 def title_from_tags(tags):
82 result[tag.category] = tag
85 # TODO: Remove this after adding flection mechanism
86 return simple_title(tags)
88 class Flection(object):
89 def get_case(self, name, flection):
93 self = split_tags(tags)
97 # Specjalny przypadek oglądania wszystkich lektur na danej półce
98 if len(self) == 1 and 'set' in self:
99 return u'Półka %s' % self['set']
101 # Specjalny przypadek "Twórczość w pozytywizmie", wtedy gdy tylko epoka
102 # jest wybrana przez użytkownika
103 if 'epoch' in self and len(self) == 1:
104 text = u'Twórczość w %s' % flection.get_case(unicode(self['epoch']), u'miejscownik')
105 return capfirst(text)
107 # Specjalny przypadek "Dramat w twórczości Sofoklesa", wtedy gdy podane
108 # są tylko rodzaj literacki i autor
109 if 'kind' in self and 'author' in self and len(self) == 2:
110 text = u'%s w twórczości %s' % (unicode(self['kind']),
111 flection.get_case(unicode(self['author']), u'dopełniacz'))
112 return capfirst(text)
114 # Przypadki ogólniejsze
116 title += u'Motyw %s' % unicode(self['theme'])
120 title += u' w %s' % flection.get_case(unicode(self['genre']), u'miejscownik')
122 title += unicode(self['genre'])
124 if 'kind' in self or 'author' in self or 'epoch' in self:
125 if 'genre' in self or 'theme' in self:
127 title += u' w %s ' % flection.get_case(unicode(self['kind']), u'miejscownik')
129 title += u' w twórczości '
131 title += u'%s ' % unicode(self.get('kind', u'twórczość'))
134 title += flection.get_case(unicode(self['author']), u'dopełniacz')
135 elif 'epoch' in self:
136 title += flection.get_case(unicode(self['epoch']), u'dopełniacz')
138 return capfirst(title)
142 def book_tree(book_list, books_by_parent):
143 text = "".join("<li><a href='%s'>%s</a>%s</li>" % (
144 book.get_absolute_url(), book.title, book_tree(books_by_parent.get(book, ()), books_by_parent)
145 ) for book in book_list)
148 return "<ol>%s</ol>" % text
153 def audiobook_tree(book_list, books_by_parent):
154 text = "".join("<li><a class='open-player' href='%s'>%s</a>%s</li>" % (
155 reverse("book_player", args=[book.slug]), book.title, audiobook_tree(books_by_parent.get(book, ()), books_by_parent)
156 ) for book in book_list)
159 return "<ol>%s</ol>" % text
164 def book_tree_texml(book_list, books_by_parent, depth=1):
166 <cmd name='hspace'><parm>%(depth)dem</parm></cmd>%(title)s
167 <spec cat='align' /><cmd name="note"><parm>%(audiences)s</parm></cmd>
168 <spec cat='align' /><cmd name="note"><parm>%(audiobook)s</parm></cmd>
174 "audiences": ", ".join(book.audiences_pl()),
175 "audiobook": "audiobook" if book.has_media('mp3') else "",
176 "children": book_tree_texml(books_by_parent.get(book.id, ()), books_by_parent, depth + 1)
177 } for book in book_list)
181 def book_tree_csv(author, book_list, books_by_parent, depth=1, max_depth=3, delimeter="\t"):
182 def quote_if_necessary(s):
185 s.replace('"', '\\"')
190 return "".join("""%(author)s%(d)s%(preindent)s%(title)s%(d)s%(postindent)s%(audiences)s%(d)s%(audiobook)s
193 "preindent": delimeter * (depth - 1),
194 "postindent": delimeter * (max_depth - depth),
196 "author": quote_if_necessary(author.name),
197 "title": quote_if_necessary(book.title),
198 "audiences": ", ".join(book.audiences_pl()),
199 "audiobook": "audiobook" if book.has_media('mp3') else "",
200 "children": book_tree_csv(author, books_by_parent.get(book.id, ()), books_by_parent, depth + 1)
201 } for book in book_list)
204 def all_editors(extra_info):
206 if 'editors' in extra_info:
207 editors += extra_info['editors']
208 if 'technical_editors' in extra_info:
209 editors += extra_info['technical_editors']
210 # support for extra_info-s from librarian<1.2
211 if 'editor' in extra_info:
212 editors.append(extra_info['editor'])
213 if 'technical_editor' in extra_info:
214 editors.append(extra_info['technical_editor'])
216 ' '.join(p.strip() for p in person.rsplit(',', 1)[::-1])
217 for person in sorted(set(editors)))
221 def user_creation_form():
222 return RegistrationForm(prefix='registration').as_ul()
226 def authentication_form():
227 return LoginForm(prefix='login').as_ul()
231 def catalogue_url(parser, token):
232 bits = token.split_contents()
238 tags_to_remove.append(bit[1:])
240 tags_to_add.append(bit)
242 return CatalogueURLNode(tags_to_add, tags_to_remove)
245 class CatalogueURLNode(Node):
246 def __init__(self, tags_to_add, tags_to_remove):
247 self.tags_to_add = [Variable(tag) for tag in tags_to_add]
248 self.tags_to_remove = [Variable(tag) for tag in tags_to_remove]
250 def render(self, context):
254 for tag_variable in self.tags_to_add:
255 tag = tag_variable.resolve(context)
256 if isinstance(tag, (list, dict)):
257 tags_to_add += [t for t in tag]
259 tags_to_add.append(tag)
261 for tag_variable in self.tags_to_remove:
262 tag = tag_variable.resolve(context)
264 tags_to_remove += [t for t in tag]
266 tags_to_remove.append(tag)
268 tag_slugs = [tag.url_chunk for tag in tags_to_add]
269 for tag in tags_to_remove:
271 tag_slugs.remove(tag.url_chunk)
275 if len(tag_slugs) > 0:
276 return reverse('tagged_object_list', kwargs={'tags': '/'.join(tag_slugs)})
278 return reverse('main_page')
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/collection_list.html')
296 def collection_list(collections):
300 @register.inclusion_tag('catalogue/book_info.html')
303 'is_picture': isinstance(book, Picture),
308 @register.inclusion_tag('catalogue/work-list.html', takes_context=True)
309 def work_list(context, object_list):
310 request = context.get('request')
314 @register.inclusion_tag('catalogue/related_books.html', takes_context=True)
315 def related_books(context, book, limit=6, random=1, taken=0):
316 limit = limit - taken
317 related = Book.tagged.related_to(book,
318 Book.objects.exclude(common_slug=book.common_slug)
319 ).exclude(ancestor=book)[:limit-random]
320 random_excluded = [b.pk for b in related] + [book.pk]
322 'request': context['request'],
325 'random_excluded': random_excluded,
329 @register.inclusion_tag('catalogue/menu.html')
330 def catalogue_menu():
331 return {'categories': [
332 ('author', _('Authors'), 'autorzy'),
333 ('genre', _('Genres'), 'gatunki'),
334 ('kind', _('Kinds'), 'rodzaje'),
335 ('epoch', _('Epochs'), 'epoki'),
336 ('theme', _('Themes'), 'motywy'),
341 def download_audio(book, daisy=True):
343 if book.has_media('mp3'):
344 links.append("<a href='%s'>%s</a>" %
345 (reverse('download_zip_mp3', args=[book.slug]),
346 BookMedia.formats['mp3'].name))
347 if book.has_media('ogg'):
348 links.append("<a href='%s'>%s</a>" %
349 (reverse('download_zip_ogg', args=[book.slug]),
350 BookMedia.formats['ogg'].name))
351 if daisy and book.has_media('daisy'):
352 for dsy in book.get_media('daisy'):
353 links.append("<a href='%s'>%s</a>" %
354 (dsy.file.url, BookMedia.formats['daisy'].name))
355 return ", ".join(links)
358 @register.inclusion_tag("catalogue/snippets/custom_pdf_link_li.html")
359 def custom_pdf_link_li(book):
362 'NO_CUSTOM_PDF': settings.NO_CUSTOM_PDF,
366 @register.inclusion_tag("catalogue/snippets/license_icon.html")
367 def license_icon(license_url):
368 """Creates a license icon, if the license_url is known."""
369 known = LICENSES.get(license_url)
373 "license_url": license_url,
374 "icon": "img/licenses/%s.png" % known['icon'],
375 "license_description": known['description'],
381 return obj.__class__.__name__
385 def source_name(url):
387 netloc = urlparse(url).netloc
389 netloc = urlparse('http://' + url).netloc
392 source, created = Source.objects.get_or_create(netloc=netloc)
393 return source.name or netloc
396 @ssi_variable(register, patch_response=[add_never_cache_headers])
397 def catalogue_random_book(request, exclude_ids):
398 queryset = Book.objects.exclude(pk__in=exclude_ids)
399 count = queryset.count()
401 return queryset[randint(0, count - 1)].pk
406 @ssi_variable(register, patch_response=[add_never_cache_headers])
407 def choose_fragment(request, book_id=None, tag_ids=None, unless=False):
411 if book_id is not None:
412 fragment = Book.objects.get(pk=book_id).choose_fragment()
414 if tag_ids is not None:
415 tags = Tag.objects.filter(pk__in=tag_ids)
416 fragments = Fragment.tagged.with_all(tags).order_by().only('id')
418 fragments = Fragment.objects.all().order_by().only('id')
419 fragment_count = fragments.count()
420 fragment = fragments[randint(0, fragment_count - 1)] if fragment_count else None
421 return fragment.pk if fragment is not None else None