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