3c75801a7c1a193347b476a10d780985bc4eda72
[wolnelektury.git] / 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
8
9 register = template.Library()
10
11
12 class RegistrationForm(UserCreationForm):
13     def as_ul(self):
14         "Returns this form rendered as HTML <li>s -- excluding the <ul></ul>."
15         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)
16
17
18 class LoginForm(AuthenticationForm):
19     def as_ul(self):
20         "Returns this form rendered as HTML <li>s -- excluding the <ul></ul>."
21         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)
22
23
24 def iterable(obj):
25     try:
26         iter(obj)
27         return True
28     except TypeError:
29         return False
30
31
32 def capfirst(text):
33     try:
34         return '%s%s' % (text[0].upper(), text[1:])
35     except IndexError:
36         return ''
37
38
39 @register.simple_tag
40 def title_from_tags(tags):
41     def split_tags(tags):
42         result = {}
43         for tag in tags:
44             result[tag.category] = tag
45         return result
46     
47     class Flection(object):
48         def get_case(self, name, flection):
49             return name
50     flection = Flection()
51     
52     self = split_tags(tags)
53     
54     title = u''
55     
56     # Specjalny przypadek oglądania wszystkich lektur w danym zestawie
57     if len(self) == 1 and 'set' in self:
58         return u'Zestaw %s' % self['set']
59     
60     # Specjalny przypadek "Twórczość w pozytywizmie", wtedy gdy tylko epoka
61     # jest wybrana przez użytkownika
62     if 'epoch' in self and len(self) == 1:
63         text = u'Twórczość w %s' % flection.get_case(unicode(self['epoch']), u'miejscownik')
64         return capfirst(text)
65     
66     # Specjalny przypadek "Dramat w twórczości Sofoklesa", wtedy gdy podane
67     # są tylko rodzaj literacki i autor
68     if 'kind' in self and 'author' in self and len(self) == 2:
69         text = u'%s w twórczości %s' % (unicode(self['kind']), 
70             flection.get_case(unicode(self['author']), u'dopełniacz'))
71         return capfirst(text)
72     
73     # Przypadki ogólniejsze
74     if 'theme' in self:
75         title += u'Motyw %s' % unicode(self['theme'])
76     
77     if 'genre' in self:
78         if 'theme' in self:
79             title += u' w %s' % flection.get_case(unicode(self['genre']), u'miejscownik')
80         else:
81             title += unicode(self['genre'])
82             
83     if 'kind' in self or 'author' in self or 'epoch' in self:
84         if 'genre' in self or 'theme' in self:
85             if 'kind' in self:
86                 title += u' w %s ' % flection.get_case(unicode(self['kind']), u'miejscownik')
87             else:
88                 title += u' w twórczości '
89         else:
90             title += u'%s ' % unicode(self.get('kind', u'twórczość'))
91             
92     if 'author' in self:
93         title += flection.get_case(unicode(self['author']), u'dopełniacz')
94     elif 'epoch' in self:
95         title += flection.get_case(unicode(self['epoch']), u'dopełniacz')
96     
97     return capfirst(title)
98
99
100 @register.simple_tag
101 def user_creation_form():
102     return RegistrationForm(prefix='registration').as_ul()
103
104
105 @register.simple_tag
106 def authentication_form():
107     return LoginForm(prefix='login').as_ul()
108
109
110 @register.inclusion_tag('catalogue/breadcrumbs.html')
111 def breadcrumbs(tags, search_form=True):
112     from wolnelektury.catalogue.forms import SearchForm
113     context = {'tag_list': tags}
114     if search_form:
115         context['search_form'] = SearchForm(tags=tags)
116     return context
117
118
119 @register.tag
120 def catalogue_url(parser, token):
121     bits = token.split_contents()
122     tag_name = bits[0]
123     
124     tags_to_add = []
125     tags_to_remove = []
126     for bit in bits[1:]:
127         if bit[0] == '-':
128             tags_to_remove.append(bit[1:])
129         else:
130             tags_to_add.append(bit)
131     
132     return CatalogueURLNode(tags_to_add, tags_to_remove)
133
134
135 class CatalogueURLNode(Node):
136     def __init__(self, tags_to_add, tags_to_remove):
137         self.tags_to_add = [Variable(tag) for tag in tags_to_add]
138         self.tags_to_remove = [Variable(tag) for tag in tags_to_remove]
139     
140     def render(self, context):
141         tags_to_add = []
142         tags_to_remove = []
143
144         for tag_variable in self.tags_to_add:
145             tag = tag_variable.resolve(context)
146             if isinstance(tag, (list, dict)):
147                 tags_to_add += [t for t in tag]
148             else:
149                 tags_to_add.append(tag)
150
151         for tag_variable in self.tags_to_remove:
152             tag = tag_variable.resolve(context)
153             if iterable(tag):
154                 tags_to_remove += [t for t in tag]
155             else:
156                 tags_to_remove.append(tag)
157             
158         tag_slugs = [tag.slug for tag in tags_to_add]
159         for tag in tags_to_remove:
160             try:
161                 tag_slugs.remove(tag.slug)
162             except KeyError:
163                 pass
164         
165         if len(tag_slugs) > 0:
166             return reverse('tagged_book_list', kwargs={'tags': '/'.join(tag_slugs)})
167         else:
168             return reverse('main_page')
169
170
171 @register.inclusion_tag('catalogue/latest_blog_posts.html')
172 def latest_blog_posts(feed_url, posts_to_show=5):
173     import feedparser
174     import datetime
175     
176     feed = feedparser.parse(feed_url)
177     posts = []
178     for i in range(posts_to_show):
179         pub_date = feed['entries'][i].updated_parsed
180         published = datetime.date(pub_date[0], pub_date[1], pub_date[2] )
181         posts.append({
182             'title': feed['entries'][i].title,
183             'summary': feed['entries'][i].summary,
184             'link': feed['entries'][i].link,
185             'date': published,
186             })
187     return {'posts': posts}
188