Local changes.
[redakcja.git] / apps / catalogue / templatetags / book_list.py
1 from __future__ import absolute_import
2
3 from re import split
4 from django.db.models import Q, Count
5 from django import template
6 from django.utils.translation import ugettext_lazy as _
7 from django.contrib.auth.models import User
8 from catalogue.models import Chunk, Image
9
10 register = template.Library()
11
12
13 class ChunksList(object):
14     def __init__(self, chunk_qs):
15         #self.chunk_qs = chunk_qs#.annotate(
16             #book_length=Count('book__chunk')).select_related(
17             #'book')#, 'stage__name',
18             #'user')
19         self.chunk_qs = chunk_qs.select_related('book__hidden')
20
21         self.book_qs = chunk_qs.values('book_id')
22
23     def __getitem__(self, key):
24         if isinstance(key, slice):
25             return self.get_slice(key)
26         elif isinstance(key, int):
27             return self.get_slice(slice(key, key+1))[0]
28         else:
29             raise TypeError('Unsupported list index. Must be a slice or an int.')
30
31     def __len__(self):
32         return self.book_qs.count()
33
34     def get_slice(self, slice_):
35         book_ids = [x['book_id'] for x in self.book_qs[slice_]]
36         chunk_qs = self.chunk_qs.filter(book__in=book_ids)
37
38         chunks_list = []
39         book = None
40         for chunk in chunk_qs:
41             if chunk.book != book:
42                 book = chunk.book
43                 chunks_list.append(ChoiceChunks(book, [chunk]))
44             else:
45                 chunks_list[-1].chunks.append(chunk)
46         return chunks_list
47
48
49 class ChoiceChunks(object):
50     """
51         Associates the given chunks iterable for a book.
52     """
53
54     chunks = None
55
56     def __init__(self, book, chunks):
57         self.book = book
58         self.chunks = chunks
59
60
61 def foreign_filter(qs, value, filter_field, model, model_field='slug', unset='-'):
62     if value == unset:
63         return qs.filter(**{filter_field: None})
64     if not value:
65         return qs
66     try:
67         obj = model._default_manager.get(**{model_field: value})
68     except model.DoesNotExist:
69         return qs.none()
70     else:
71         return qs.filter(**{filter_field: obj})
72
73
74 def search_filter(qs, value, filter_fields):
75     if not value:
76         return qs
77     q = Q(**{"%s__icontains" % filter_fields[0]: value})
78     for field in filter_fields[1:]:
79         q |= Q(**{"%s__icontains" % field: value})
80     return qs.filter(q)
81
82
83 _states = [
84         ('publishable', _('publishable'), Q(book___new_publishable=True)),
85         ('changed', _('changed'), Q(_changed=True)),
86         ('published', _('published'), Q(book___published=True)),
87         ('unpublished', _('unpublished'), Q(book___published=False)),
88         ('empty', _('empty'), Q(head=None)),
89     ]
90 _states_options = [s[:2] for s in _states]
91 _states_dict = dict([(s[0], s[2]) for s in _states])
92
93
94 def document_list_filter(request, **kwargs):
95
96     def arg_or_GET(field):
97         return kwargs.get(field, request.GET.get(field))
98
99     if arg_or_GET('all'):
100         chunks = Chunk.objects.all()
101     else:
102         chunks = Chunk.visible_objects.all()
103
104     chunks = chunks.order_by('book__title', 'book', 'number')
105
106     if not request.user.is_authenticated():
107         chunks = chunks.filter(book__public=True)
108
109     state = arg_or_GET('status')
110     if state in _states_dict:
111         chunks = chunks.filter(_states_dict[state])
112
113     chunks = foreign_filter(chunks, arg_or_GET('user'), 'user', User, 'username')
114     chunks = foreign_filter(chunks, arg_or_GET('stage'), 'stage', Chunk.tag_model, 'slug')
115     chunks = search_filter(chunks, arg_or_GET('title'), ['book__title', 'title'])
116     return chunks
117
118
119 @register.inclusion_tag('catalogue/book_list/book_list.html', takes_context=True)
120 def book_list(context, user=None):
121     request = context['request']
122
123     if user:
124         filters = {"user": user}
125         new_context = {"viewed_user": user}
126     else:
127         filters = {}
128         new_context = {"users": User.objects.annotate(
129                 count=Count('chunk')).filter(count__gt=0).order_by(
130                 '-count', 'last_name', 'first_name')}
131
132     new_context.update({
133         "filters": True,
134         "request": request,
135         "books": ChunksList(document_list_filter(request, **filters)),
136         "stages": Chunk.tag_model.objects.all(),
137         "states": _states_options,
138     })
139
140     return new_context
141
142
143
144 _image_states = [
145         ('publishable', _('publishable'), Q(_new_publishable=True)),
146         ('changed', _('changed'), Q(_changed=True)),
147         ('published', _('published'), Q(_published=True)),
148         ('unpublished', _('unpublished'), Q(_published=False)),
149         ('empty', _('empty'), Q(head=None)),
150     ]
151 _image_states_options = [s[:2] for s in _image_states]
152 _image_states_dict = dict([(s[0], s[2]) for s in _image_states])
153
154 def image_list_filter(request, **kwargs):
155
156     def arg_or_GET(field):
157         return kwargs.get(field, request.GET.get(field))
158
159     images = Image.objects.all()
160
161     if not request.user.is_authenticated():
162         images = images.filter(public=True)
163
164     state = arg_or_GET('status')
165     if state in _image_states_dict:
166         images = images.filter(_image_states_dict[state])
167
168     images = foreign_filter(images, arg_or_GET('user'), 'user', User, 'username')
169     images = foreign_filter(images, arg_or_GET('stage'), 'stage', Image.tag_model, 'slug')
170     images = search_filter(images, arg_or_GET('title'), ['title', 'title'])
171     return images
172
173
174 @register.inclusion_tag('catalogue/image_table.html', takes_context=True)
175 def image_list(context, user=None):
176     request = context['request']
177
178     if user:
179         filters = {"user": user}
180         new_context = {"viewed_user": user}
181     else:
182         filters = {}
183         new_context = {"users": User.objects.annotate(
184                 count=Count('image')).filter(count__gt=0).order_by(
185                 '-count', 'last_name', 'first_name')}
186
187     new_context.update({
188         "filters": True,
189         "request": request,
190         "objects": image_list_filter(request, **filters),
191         "stages": Image.tag_model.objects.all(),
192         "states": _image_states_options,
193     })
194
195     return new_context