Finished logging in/registration.
[wolnelektury.git] / catalogue / templatetags / catalogue.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 import forms
7
8
9 register = template.Library()
10
11
12 class RegistrationForm(forms.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(forms.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.tag
111 def catalogue_url(parser, token):
112     bits = token.split_contents()
113     tag_name = bits[0]
114     
115     tags_to_add = []
116     tags_to_remove = []
117     for bit in bits[1:]:
118         if bit[0] == '-':
119             tags_to_remove.append(bit[1:])
120         else:
121             tags_to_add.append(bit)
122     
123     return CatalogueURLNode(tags_to_add, tags_to_remove)
124
125
126 class CatalogueURLNode(Node):
127     def __init__(self, tags_to_add, tags_to_remove):
128         self.tags_to_add = [Variable(tag) for tag in tags_to_add]
129         self.tags_to_remove = [Variable(tag) for tag in tags_to_remove]
130     
131     def render(self, context):
132         tags_to_add = []
133         tags_to_remove = []
134
135         for tag_variable in self.tags_to_add:
136             tag = tag_variable.resolve(context)
137             if isinstance(tag, (list, dict)):
138                 tags_to_add += [t for t in tag]
139             else:
140                 tags_to_add.append(tag)
141
142         for tag_variable in self.tags_to_remove:
143             tag = tag_variable.resolve(context)
144             if iterable(tag):
145                 tags_to_remove += [t for t in tag]
146             else:
147                 tags_to_remove.append(tag)
148             
149         tag_slugs = [tag.slug for tag in tags_to_add]
150         for tag in tags_to_remove:
151             try:
152                 tag_slugs.remove(tag.slug)
153             except KeyError:
154                 pass
155         
156         if len(tag_slugs) > 0:
157             return reverse('tagged_book_list', kwargs={'tags': '/'.join(tag_slugs)})
158         else:
159             return reverse('main_page')
160
161
162 @register.inclusion_tag('catalogue/latest_blog_posts.html')
163 def latest_blog_posts(feed_url, posts_to_show=5):
164     import feedparser
165     import datetime
166     
167     feed = feedparser.parse(feed_url)
168     posts = []
169     for i in range(posts_to_show):
170         pub_date = feed['entries'][i].updated_parsed
171         published = datetime.date(pub_date[0], pub_date[1], pub_date[2] )
172         posts.append({
173             'title': feed['entries'][i].title,
174             'summary': feed['entries'][i].summary,
175             'link': feed['entries'][i].link,
176             'date': published,
177             })
178     return {'posts': posts}
179