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