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