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