Improved title generation (Request from Olga).
[wolnelektury.git] / apps / catalogue / templatetags / catalogue_tags.py
1 # -*- coding: utf-8 -*-
2 from django import template
3 from django.template import Node, Variable
4 from django.utils.encoding import smart_str
5 from django.core.urlresolvers import reverse
6 from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
7 from django.db.models import Q
8
9
10 register = template.Library()
11
12
13 class RegistrationForm(UserCreationForm):
14     def as_ul(self):
15         "Returns this form rendered as HTML <li>s -- excluding the <ul></ul>."
16         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)
17
18
19 class LoginForm(AuthenticationForm):
20     def as_ul(self):
21         "Returns this form rendered as HTML <li>s -- excluding the <ul></ul>."
22         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)
23
24
25 def iterable(obj):
26     try:
27         iter(obj)
28         return True
29     except TypeError:
30         return False
31
32
33 def capfirst(text):
34     try:
35         return '%s%s' % (text[0].upper(), text[1:])
36     except IndexError:
37         return ''
38
39
40
41 def simple_title(tags):
42     mapping = {
43         'author': u'Autor',
44         'theme': u'motyw',
45         'epoch': u'epoka',
46         'genre': u'gatunek',
47         'kind': u'rodzaj',
48         'set': u'półka',
49     }
50     
51     title = []
52     for tag in tags:
53         title.append("%s: %s" % (mapping[tag.category], tag.name))
54     return capfirst(', '.join(title))
55
56
57 @register.simple_tag
58 def title_from_tags(tags):
59     def split_tags(tags):
60         result = {}
61         for tag in tags:
62             result[tag.category] = tag
63         return result
64     
65     # TODO: Remove this after adding flection mechanism
66     return simple_title(tags)
67     
68     class Flection(object):
69         def get_case(self, name, flection):
70             return name
71     flection = Flection()
72     
73     self = split_tags(tags)
74     
75     title = u''
76     
77     # Specjalny przypadek oglądania wszystkich lektur na danej półce
78     if len(self) == 1 and 'set' in self:
79         return u'Półka %s' % self['set']
80     
81     # Specjalny przypadek "Twórczość w pozytywizmie", wtedy gdy tylko epoka
82     # jest wybrana przez użytkownika
83     if 'epoch' in self and len(self) == 1:
84         text = u'Twórczość w %s' % flection.get_case(unicode(self['epoch']), u'miejscownik')
85         return capfirst(text)
86     
87     # Specjalny przypadek "Dramat w twórczości Sofoklesa", wtedy gdy podane
88     # są tylko rodzaj literacki i autor
89     if 'kind' in self and 'author' in self and len(self) == 2:
90         text = u'%s w twórczości %s' % (unicode(self['kind']), 
91             flection.get_case(unicode(self['author']), u'dopełniacz'))
92         return capfirst(text)
93     
94     # Przypadki ogólniejsze
95     if 'theme' in self:
96         title += u'Motyw %s' % unicode(self['theme'])
97     
98     if 'genre' in self:
99         if 'theme' in self:
100             title += u' w %s' % flection.get_case(unicode(self['genre']), u'miejscownik')
101         else:
102             title += unicode(self['genre'])
103             
104     if 'kind' in self or 'author' in self or 'epoch' in self:
105         if 'genre' in self or 'theme' in self:
106             if 'kind' in self:
107                 title += u' w %s ' % flection.get_case(unicode(self['kind']), u'miejscownik')
108             else:
109                 title += u' w twórczości '
110         else:
111             title += u'%s ' % unicode(self.get('kind', u'twórczość'))
112             
113     if 'author' in self:
114         title += flection.get_case(unicode(self['author']), u'dopełniacz')
115     elif 'epoch' in self:
116         title += flection.get_case(unicode(self['epoch']), u'dopełniacz')
117     
118     return capfirst(title)
119
120
121 @register.simple_tag
122 def user_creation_form():
123     return RegistrationForm(prefix='registration').as_ul()
124
125
126 @register.simple_tag
127 def authentication_form():
128     return LoginForm(prefix='login').as_ul()
129
130
131 @register.inclusion_tag('catalogue/breadcrumbs.html')
132 def breadcrumbs(tags, search_form=True):
133     from catalogue.forms import SearchForm
134     context = {'tag_list': tags}
135     if search_form and len(tags) < 6:
136         context['search_form'] = SearchForm(tags=tags)
137     return context
138
139
140 @register.tag
141 def catalogue_url(parser, token):
142     bits = token.split_contents()
143     tag_name = bits[0]
144     
145     tags_to_add = []
146     tags_to_remove = []
147     for bit in bits[1:]:
148         if bit[0] == '-':
149             tags_to_remove.append(bit[1:])
150         else:
151             tags_to_add.append(bit)
152     
153     return CatalogueURLNode(tags_to_add, tags_to_remove)
154
155
156 class CatalogueURLNode(Node):
157     def __init__(self, tags_to_add, tags_to_remove):
158         self.tags_to_add = [Variable(tag) for tag in tags_to_add]
159         self.tags_to_remove = [Variable(tag) for tag in tags_to_remove]
160     
161     def render(self, context):
162         tags_to_add = []
163         tags_to_remove = []
164
165         for tag_variable in self.tags_to_add:
166             tag = tag_variable.resolve(context)
167             if isinstance(tag, (list, dict)):
168                 tags_to_add += [t for t in tag]
169             else:
170                 tags_to_add.append(tag)
171
172         for tag_variable in self.tags_to_remove:
173             tag = tag_variable.resolve(context)
174             if iterable(tag):
175                 tags_to_remove += [t for t in tag]
176             else:
177                 tags_to_remove.append(tag)
178             
179         tag_slugs = [tag.slug for tag in tags_to_add]
180         for tag in tags_to_remove:
181             try:
182                 tag_slugs.remove(tag.slug)
183             except KeyError:
184                 pass
185         
186         if len(tag_slugs) > 0:
187             return reverse('tagged_object_list', kwargs={'tags': '/'.join(tag_slugs)})
188         else:
189             return reverse('main_page')
190
191
192 @register.inclusion_tag('catalogue/latest_blog_posts.html')
193 def latest_blog_posts(feed_url, posts_to_show=5):
194     import feedparser
195     import datetime
196     
197     feed = feedparser.parse(feed_url)
198     posts = []
199     for i in range(posts_to_show):
200         pub_date = feed['entries'][i].updated_parsed
201         published = datetime.date(pub_date[0], pub_date[1], pub_date[2] )
202         posts.append({
203             'title': feed['entries'][i].title,
204             'summary': feed['entries'][i].summary,
205             'link': feed['entries'][i].link,
206             'date': published,
207             })
208     return {'posts': posts}
209
210
211 @register.inclusion_tag('catalogue/tag_list.html')
212 def tag_list(tags, choices=None):
213     if choices is None:
214         choices = []
215     if len(tags) == 1:
216         one_tag = tags[0]
217     return locals()
218
219
220 @register.inclusion_tag('catalogue/folded_tag_list.html')
221 def folded_tag_list(tags, choices=None):
222     if choices is None:
223         choices = []
224     some_tags_hidden = False
225     tag_count = len(tags)
226     
227     if tag_count == 1:
228         one_tag = tags[0]
229     else:
230         shown_tags = [tag for tag in tags if tag.main_page]
231         if tag_count > len(shown_tags):
232             some_tags_hidden = True
233     return locals()
234