Django 1.7, working version.
[wolnelektury.git] / apps / catalogue / templatetags / catalogue_tags.py
index 583c9c7..1cc0bb7 100644 (file)
@@ -4,21 +4,20 @@
 #
 import datetime
 import feedparser
-import re
+from random import randint
+from urlparse import urlparse
 
+from django.conf import settings
 from django import template
-from django.template import Node, Variable
-from django.utils.encoding import smart_str
-from django.core.cache import get_cache
+from django.template import Node, Variable, Template, Context
+from django.core.cache import cache
 from django.core.urlresolvers import reverse
 from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
-from django.db.models import Q
-from django.conf import settings
-from django.template.defaultfilters import stringfilter
 from django.utils.translation import ugettext as _
 
-from catalogue.utils import split_tags
-from catalogue.models import Book, Fragment
+from catalogue.utils import related_tag_name as _related_tag_name
+from catalogue.models import Book, BookMedia, Fragment, Tag, Source
+from catalogue.constants import LICENSES
 
 register = template.Library()
 
@@ -50,6 +49,14 @@ def capfirst(text):
         return ''
 
 
+@register.simple_tag
+def html_title_from_tags(tags):
+    if len(tags) < 2:
+        return title_from_tags(tags)
+    template = Template("{{ category }}: <a href='{{ tag.get_absolute_url }}'>{{ tag.name }}</a>")
+    return capfirst(",<br/>".join(
+        template.render(Context({'tag': tag, 'category': _(tag.category)})) for tag in tags))
+
 
 def simple_title(tags):
     title = []
@@ -143,6 +150,17 @@ def book_tree(book_list, books_by_parent):
     else:
         return ''
 
+@register.simple_tag
+def audiobook_tree(book_list, books_by_parent):
+    text = "".join("<li><a class='open-player' href='%s'>%s</a>%s</li>" % (
+        reverse("book_player", args=[book.slug]), book.title, audiobook_tree(books_by_parent.get(book, ()), books_by_parent)
+        ) for book in book_list)
+
+    if text:
+        return "<ol>%s</ol>" % text
+    else:
+        return ''
+
 @register.simple_tag
 def book_tree_texml(book_list, books_by_parent, depth=1):
     return "".join("""
@@ -153,13 +171,36 @@ def book_tree_texml(book_list, books_by_parent, depth=1):
             %(children)s
             """ % {
                 "depth": depth,
-                "title": book.title, 
+                "title": book.title,
                 "audiences": ", ".join(book.audiences_pl()),
                 "audiobook": "audiobook" if book.has_media('mp3') else "",
                 "children": book_tree_texml(books_by_parent.get(book.id, ()), books_by_parent, depth + 1)
             } for book in book_list)
 
 
+@register.simple_tag
+def book_tree_csv(author, book_list, books_by_parent, depth=1, max_depth=3, delimeter="\t"):
+    def quote_if_necessary(s):
+        try:
+            s.index(delimeter)
+            s.replace('"', '\\"')
+            return '"%s"' % s
+        except ValueError:
+            return s
+
+    return "".join("""%(author)s%(d)s%(preindent)s%(title)s%(d)s%(postindent)s%(audiences)s%(d)s%(audiobook)s
+%(children)s""" % {
+                "d": delimeter,
+                "preindent": delimeter * (depth - 1),
+                "postindent": delimeter * (max_depth - depth),
+                "depth": depth,
+                "author": quote_if_necessary(author.name),
+                "title": quote_if_necessary(book.title),
+                "audiences": ", ".join(book.audiences_pl()),
+                "audiobook": "audiobook" if book.has_media('mp3') else "",
+                "children": book_tree_csv(author, books_by_parent.get(book.id, ()), books_by_parent, depth + 1)
+            } for book in book_list)
+
 @register.simple_tag
 def all_editors(extra_info):
     editors = []
@@ -190,7 +231,6 @@ def authentication_form():
 @register.tag
 def catalogue_url(parser, token):
     bits = token.split_contents()
-    tag_name = bits[0]
 
     tags_to_add = []
     tags_to_remove = []
@@ -245,8 +285,8 @@ def latest_blog_posts(feed_url, posts_to_show=5):
         feed = feedparser.parse(str(feed_url))
         posts = []
         for i in range(posts_to_show):
-            pub_date = feed['entries'][i].updated_parsed
-            published = datetime.date(pub_date[0], pub_date[1], pub_date[2] )
+            pub_date = feed['entries'][i].published_parsed
+            published = datetime.date(pub_date[0], pub_date[1], pub_date[2])
             posts.append({
                 'title': feed['entries'][i].title,
                 'summary': feed['entries'][i].summary,
@@ -262,16 +302,18 @@ def latest_blog_posts(feed_url, posts_to_show=5):
 def tag_list(tags, choices=None):
     if choices is None:
         choices = []
-    if len(tags) == 1:
+    if len(tags) == 1 and tags[0].category not in [t.category for t in choices]:
         one_tag = tags[0]
     return locals()
 
+
 @register.inclusion_tag('catalogue/inline_tag_list.html')
 def inline_tag_list(tags, choices=None):
-    if choices is None:
-        choices = []
-    if len(tags) == 1:
-        one_tag = tags[0]
+    return tag_list(tags, choices)
+
+
+@register.inclusion_tag('catalogue/collection_list.html')
+def collection_list(collections):
     return locals()
 
 
@@ -282,44 +324,55 @@ def book_info(book):
 
 @register.inclusion_tag('catalogue/book_wide.html', takes_context=True)
 def book_wide(context, book):
-    formats = {}
-    # files generated during publication
-    for ebook_format in book.ebook_formats:
-        if book.has_media(ebook_format):
-            formats[ebook_format] = book.get_media(ebook_format)
+    book_themes = book.related_themes()
+    extra_info = book.extra_info
+    hide_about = extra_info.get('about', '').startswith('http://wiki.wolnepodreczniki.pl')
+    stage_note, stage_note_url = book.stage_note()
 
     return {
-        'related': book.related_info(),
         'book': book,
-        'formats': formats,
-        'extra_info': book.get_extra_info_value(),
+        'main_link': reverse('book_text', args=[book.slug]) if book.html_file else None,
+        'related': book.related_info(),
+        'extra_info': extra_info,
+        'hide_about': hide_about,
+        'themes': book_themes,
         'request': context.get('request'),
-        'fragment': book.choose_fragment(),
+        'show_lang': book.language_code() != settings.LANGUAGE_CODE,
+        'stage_note': stage_note,
+        'stage_note_url': stage_note_url,
     }
 
 
 @register.inclusion_tag('catalogue/book_short.html', takes_context=True)
 def book_short(context, book):
+    stage_note, stage_note_url = book.stage_note()
+
     return {
-        'related': book.related_info(),
         'book': book,
+        'main_link': book.get_absolute_url(),
+        'related': book.related_info(),
         'request': context.get('request'),
+        'show_lang': book.language_code() != settings.LANGUAGE_CODE,
+        'stage_note': stage_note,
+        'stage_note_url': stage_note_url,
     }
 
 
 @register.inclusion_tag('catalogue/book_mini_box.html')
-def book_mini(book):
+def book_mini(book, with_link=True):
+    author_str = ", ".join(related_tag_name(tag)
+        for tag in book.related_info()['tags'].get('author', ()))
     return {
-        'related': book.related_info(),
         'book': book,
+        'author_str': author_str,
+        'with_link': with_link,
+        'show_lang': book.language_code() != settings.LANGUAGE_CODE,
     }
 
 
 @register.inclusion_tag('catalogue/work-list.html', takes_context=True)
 def work_list(context, object_list):
     request = context.get('request')
-    if object_list:
-        object_type = type(object_list[0]).__name__
     return locals()
 
 
@@ -340,36 +393,105 @@ def fragment_promo(arg=None):
 
 
 @register.inclusion_tag('catalogue/related_books.html')
-def related_books(book, limit=6):
-    related = list(Book.objects.filter(
-        common_slug=book.common_slug).exclude(pk=book.pk)[:limit])
-    limit -= len(related)
-    if limit:
-        tagged = Book.tagged.with_any(book.tags).exclude(pk=book.pk)
-        book_tag = book.book_tag()
-        for rel_book in tagged:
-            if book_tag in rel_book.tags.all():
-                continue
-            related += [rel_book]
-            limit -= 1
-            if not limit:
-                break
-
+def related_books(book, limit=6, random=1, taken=0):
+    limit = limit - taken
+    cache_key = "catalogue.related_books.%d.%d" % (book.id, limit - random)
+    related = cache.get(cache_key)
+    if related is None:
+        related = Book.tagged.related_to(book,
+                Book.objects.exclude(common_slug=book.common_slug)
+                ).exclude(tag_relations__tag=book.book_tag())[:limit-random]
+        cache.set(cache_key, related, 1800)
+    if random:
+        random_books = Book.objects.exclude(
+                        pk__in=[b.pk for b in related] + [book.pk])
+        if random == 1:
+            count = random_books.count()
+            if count:
+                random_related = [random_books[randint(0, count - 1)]]
+        else:
+            random_related = list(random_books.order_by('?')[:random])
+    else:
+        random_related = []
     return {
         'books': related,
+        'random_related': random_related,
     }
 
 
+@register.inclusion_tag('catalogue/menu.html')
+def catalogue_menu():
+    return {'categories': [
+                ('author', _('Authors'), 'autorzy'),
+                ('genre', _('Genres'), 'gatunki'),
+                ('kind', _('Kinds'), 'rodzaje'),
+                ('epoch', _('Epochs'), 'epoki'),
+                ('theme', _('Themes'), 'motywy'),
+        ]}
+
+
+@register.simple_tag
+def tag_url(category, slug):
+    return Tag.create_url(category, slug)
+
+
+@register.simple_tag
+def download_audio(book, daisy=True):
+    related = book.related_info()
+    links = []
+    if related['media'].get('mp3'):
+        links.append("<a href='%s'>%s</a>" %
+            (reverse('download_zip_mp3', args=[book.slug]),
+                BookMedia.formats['mp3'].name))
+    if related['media'].get('ogg'):
+        links.append("<a href='%s'>%s</a>" %
+            (reverse('download_zip_ogg', args=[book.slug]),
+                BookMedia.formats['ogg'].name))
+    if daisy and related['media'].get('daisy'):
+        for dsy in book.get_media('daisy'):
+            links.append("<a href='%s'>%s</a>" %
+                (dsy.file.url, BookMedia.formats['daisy'].name))
+    return ", ".join(links)
+
+
+@register.inclusion_tag("catalogue/snippets/custom_pdf_link_li.html")
+def custom_pdf_link_li(book):
+    return {
+        'book': book,
+        'NO_CUSTOM_PDF': settings.NO_CUSTOM_PDF,
+    }
+
+
+@register.inclusion_tag("catalogue/snippets/license_icon.html")
+def license_icon(license_url):
+    """Creates a license icon, if the license_url is known."""
+    known = LICENSES.get(license_url)
+    if known is None:
+        return {}
+    return {
+        "license_url": license_url,
+        "icon": "img/licenses/%s.png" % known['icon'],
+        "license_description": known['description'],
+    }
+
+
+@register.simple_tag
+def related_tag_name(tag, lang=None):
+    return _related_tag_name(tag, lang)
+
+
 @register.filter
-@stringfilter
-def removewholetags(value, tags):
-    """Removes a space separated list of [X]HTML tags from the output.
-
-    FIXME: It makes the assumption the removed tags aren't nested.
-
-    """
-    tags = [re.escape(tag) for tag in tags.split()]
-    tags_re = u'(%s)' % u'|'.join(tags)
-    tag_re = re.compile(ur'<%s[^>]*>.*?</\s*\1\s*>' % tags_re, re.U)
-    value = tag_re.sub(u'', value)
-    return value
+def class_name(obj):
+    return obj.__class__.__name__
+
+
+@register.simple_tag
+def source_name(url):
+    url = url.lstrip()
+    netloc = urlparse(url).netloc
+    if not netloc:
+        netloc = urlparse('http://' + url).netloc
+    if not netloc:
+        return ''
+    source, created = Source.objects.get_or_create(netloc=netloc)
+    return source.name or netloc