d20b9ca65b7b0bff244b47c333d3601bd74a3007
[wolnelektury.git] / apps / stats / templatetags / stats.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 from functools import wraps
7 import datetime
8
9 from django import template
10
11 from catalogue.models import Book, BookMedia
12
13
14 register = template.Library()
15
16 class StatsNode(template.Node):
17     def __init__(self, value, varname=None):
18         self.value = value
19         self.varname = varname
20
21     def render(self, context):
22         print self.varname
23         if self.varname:
24             context[self.varname] = self.value
25             return ''
26         else:
27             return self.value
28
29
30 def register_counter(f):
31     """Turns a simple counting function into a registered counter tag.
32
33     You can run a counter tag as a simple {% tag_name %} tag, or
34     as {% tag_name var_name %} to store the result in a variable.
35
36     """
37     @wraps(f)
38     def wrapped(parser, token):
39         try:
40             tag_name, args = token.contents.split(None, 1)
41         except ValueError:
42             args = None
43         return StatsNode(f(), args)
44
45     return register.tag(wrapped)
46
47
48 @register_counter
49 def count_books_all():
50     return Book.objects.all().count()
51
52 @register_counter
53 def count_books_nonempty():
54     return Book.objects.exclude(html_file='').count()
55
56 @register_counter
57 def count_books_empty():
58     return Book.objects.filter(html_file='').count()
59
60 @register_counter
61 def count_books_root():
62     return Book.objects.filter(parent=None).count()