Added extraction of wiki_url from DublinCore.
[wolnelektury.git] / apps / catalogue / views.py
1 # -*- coding: utf-8 -*-
2 import tempfile
3 import zipfile
4
5 from django.template import RequestContext
6 from django.shortcuts import render_to_response, get_object_or_404
7 from django.http import HttpResponse, HttpResponseRedirect, Http404
8 from django.core.urlresolvers import reverse
9 from django.db.models import Q
10 from django.contrib.auth.decorators import login_required
11 from django.utils.datastructures import SortedDict
12 from django.views.decorators.http import require_POST
13 from django.contrib import auth
14 from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
15 from django.utils import simplejson
16 from django.utils.functional import Promise
17 from django.utils.encoding import force_unicode
18 from django.views.decorators import cache
19
20 from catalogue import models
21 from catalogue import forms
22 from catalogue.utils import split_tags
23 from newtagging import views as newtagging_views
24
25
26 class LazyEncoder(simplejson.JSONEncoder):
27     def default(self, obj):
28         if isinstance(obj, Promise):
29             return force_unicode(obj)
30         return obj
31
32
33 def main_page(request):    
34     if request.user.is_authenticated():
35         shelves = models.Tag.objects.filter(category='set', user=request.user)
36         new_set_form = forms.NewSetForm()
37     extra_where = 'NOT catalogue_tag.category = "set"'
38     tags = models.Tag.objects.usage_for_model(models.Book, counts=True, extra={'where': [extra_where]})
39     fragment_tags = models.Tag.objects.usage_for_model(models.Fragment, counts=True,
40         extra={'where': ['catalogue_tag.category = "theme"'] + [extra_where]})
41     categories = split_tags(tags)
42     
43     form = forms.SearchForm()
44     return render_to_response('catalogue/main_page.html', locals(),
45         context_instance=RequestContext(request))
46
47
48 def book_list(request):
49     books = models.Book.objects.all()
50     form = forms.SearchForm()
51     
52     books_by_first_letter = SortedDict()
53     for book in books:
54         books_by_first_letter.setdefault(book.title[0], []).append(book)
55     
56     return render_to_response('catalogue/book_list.html', locals(),
57         context_instance=RequestContext(request))
58
59
60 def tagged_object_list(request, tags=''):
61     # Prevent DoS attacks on our database
62     if len(tags.split('/')) > 6:
63         raise Http404
64         
65     try:
66         tags = models.Tag.get_tag_list(tags)
67     except models.Tag.DoesNotExist:
68         raise Http404
69     
70     model = models.Book
71     shelf = [tag for tag in tags if tag.category == 'set']
72     shelf_is_set = (len(tags) == 1 and tags[0].category == 'set')
73     theme_is_set = len([tag for tag in tags if tag.category == 'theme']) > 0
74     if theme_is_set:
75         model = models.Fragment
76
77     user_is_owner = (len(shelf) and request.user.is_authenticated() and request.user == shelf[0].user)
78     
79     extra_where = 'NOT catalogue_tag.category = "set"'
80     related_tags = models.Tag.objects.related_for_model(tags, model, counts=True, extra={'where': [extra_where]})
81     categories = split_tags(related_tags)
82
83     if not (theme_is_set or shelf_is_set):
84         model=models.Book.objects.filter(parent=None)
85     
86     return newtagging_views.tagged_object_list(
87         request,
88         tag_model=models.Tag,
89         queryset_or_model=model,
90         tags=tags,
91         template_name='catalogue/tagged_object_list.html',
92         extra_context = {'categories': categories, 'shelf_is_set': shelf_is_set, 'user_is_owner': user_is_owner },
93     )
94
95
96 def book_detail(request, slug):
97     book = get_object_or_404(models.Book, slug=slug)
98     tags = list(book.tags.filter(~Q(category='set')))
99     categories = split_tags(tags)
100     book_children = book.children.all().order_by('parent_number')
101     
102     form = forms.SearchForm()
103     return render_to_response('catalogue/book_detail.html', locals(),
104         context_instance=RequestContext(request))
105
106
107 def book_text(request, slug):
108     book = get_object_or_404(models.Book, slug=slug)
109     book_themes = {}
110     for fragment in book.fragments.all():
111         for theme in fragment.tags.filter(category='theme'):
112             book_themes.setdefault(theme, []).append(fragment)
113     
114     book_themes = book_themes.items()
115     book_themes.sort(key=lambda s: s[0].sort_key)
116     return render_to_response('catalogue/book_text.html', locals(),
117         context_instance=RequestContext(request))
118
119
120 # ==========
121 # = Search =
122 # ==========
123 def _tags_starting_with(prefix, user):
124     books = models.Book.objects.filter(title__icontains=prefix)
125     tags = models.Tag.objects.filter(name__icontains=prefix)
126     if user.is_authenticated():
127         tags = tags.filter(~Q(category='set') | Q(user=user))
128     else:
129         tags = tags.filter(~Q(category='set'))
130
131     return list(books) + list(tags)
132         
133
134 def search(request):
135     tags = request.GET.get('tags', '')
136     prefix = request.GET.get('q', '')
137     # Prefix must have at least 2 characters
138     if len(prefix) < 2:
139         return HttpResponse('')
140     
141     try:
142         tag_list = models.Tag.get_tag_list(tags)
143     except:
144         tag_list = []
145     
146     result = _tags_starting_with(prefix, request.user)
147     if len(result) > 0:
148         tag = result[0]
149         if isinstance(tag, models.Book):
150             return HttpResponseRedirect(tag.get_absolute_url())
151         else:
152             tag_list.append(tag)
153         
154     return HttpResponseRedirect(reverse('catalogue.views.tagged_object_list', 
155         kwargs={'tags': '/'.join(tag.slug for tag in tag_list)}
156     ))
157
158
159 def tags_starting_with(request):
160     prefix = request.GET.get('q', '')
161     # Prefix must have at least 2 characters
162     if len(prefix) < 2:
163         return HttpResponse('')
164     
165     return HttpResponse('\n'.join(tag.name for tag in _tags_starting_with(prefix, request.user)))
166
167
168 # ====================
169 # = Shelf management =
170 # ====================
171 @login_required
172 @cache.never_cache
173 def user_shelves(request):
174     shelves = models.Tag.objects.filter(category='set', user=request.user)
175     new_set_form = forms.NewSetForm()
176     return render_to_response('catalogue/user_shelves.html', locals(),
177             context_instance=RequestContext(request))
178
179 @cache.never_cache
180 def book_sets(request, slug):
181     book = get_object_or_404(models.Book, slug=slug)
182     user_sets = models.Tag.objects.filter(category='set', user=request.user)
183     book_sets = book.tags.filter(category='set', user=request.user)
184     
185     if not request.user.is_authenticated():
186         return HttpResponse('<p>Aby zarządzać swoimi półkami, musisz się zalogować.</p>')
187     
188     if request.method == 'POST':
189         form = forms.ObjectSetsForm(book, request.user, request.POST)
190         if form.is_valid():
191             old_shelves = list(book.tags.filter(category='set'))
192             new_shelves = [models.Tag.objects.get(pk=id) for id in form.cleaned_data['set_ids']]
193             
194             for shelf in [shelf for shelf in old_shelves if shelf not in new_shelves]:
195                 shelf.book_count -= 1
196                 shelf.save()
197                 
198             for shelf in [shelf for shelf in new_shelves if shelf not in old_shelves]:
199                 shelf.book_count += 1
200                 shelf.save()
201             
202             book.tags = new_shelves + list(book.tags.filter(~Q(category='set') | ~Q(user=request.user)))
203             if request.is_ajax():
204                 return HttpResponse('<p>Półki zostały zapisane.</p>')
205             else:
206                 return HttpResponseRedirect('/')
207     else:
208         form = forms.ObjectSetsForm(book, request.user)
209         new_set_form = forms.NewSetForm()
210     
211     return render_to_response('catalogue/book_sets.html', locals(),
212         context_instance=RequestContext(request))
213
214
215 @login_required
216 @require_POST
217 @cache.never_cache
218 def remove_from_shelf(request, shelf, book):
219     book = get_object_or_404(models.Book, slug=book)
220     shelf = get_object_or_404(models.Tag, slug=shelf, category='set', user=request.user)
221     
222     models.Tag.objects.remove_tag(book, shelf)
223     
224     shelf.book_count -= 1
225     shelf.save()
226     
227     return HttpResponse('Usunieto')
228
229
230 @cache.never_cache
231 def download_shelf(request, slug):
232     """"
233     Create a ZIP archive on disk and transmit it in chunks of 8KB,
234     without loading the whole file into memory. A similar approach can
235     be used for large dynamic PDF files.                                        
236     """
237     shelf = get_object_or_404(models.Tag, slug=slug, category='set')
238             
239     # Create a ZIP archive
240     temp = temp = tempfile.TemporaryFile()
241     archive = zipfile.ZipFile(temp, 'w')
242     
243     # Collect all books to include in ZIP archive
244     def collect_books(books):
245         result = []
246         for book in books:
247             if len(book.children.all()) == 0:
248                 result.append(book)
249             else:
250                 result += collect_books(book.children.all())
251         return result
252     
253     for book in collect_books(models.Book.tagged.with_all(shelf)):
254         if book.pdf_file:
255             filename = book.pdf_file.path
256             archive.write(filename, str('%s.pdf' % book.slug))
257         if book.odt_file:
258             filename = book.odt_file.path
259             archive.write(filename, str('%s.odt' % book.slug))
260         if book.txt_file:
261             filename = book.txt_file.path
262             archive.write(filename, str('%s.txt' % book.slug))
263     archive.close()
264     
265     response = HttpResponse(content_type='application/zip', mimetype='application/x-zip-compressed')
266     response['Content-Disposition'] = 'attachment; filename=%s.zip' % shelf.sort_key
267     response['Content-Length'] = temp.tell()
268     
269     temp.seek(0)
270     response.write(temp.read())
271     return response
272
273
274 @login_required
275 @require_POST
276 @cache.never_cache
277 def new_set(request):
278     new_set_form = forms.NewSetForm(request.POST)
279     if new_set_form.is_valid():
280         new_set = new_set_form.save(request.user)
281
282         if request.is_ajax():
283             return HttpResponse(u'<p>Półka <strong>%s</strong> została utworzona</p>' % new_set)
284         else:
285             return HttpResponseRedirect('/')
286
287     return HttpResponseRedirect('/')
288
289
290 @login_required
291 @require_POST
292 @cache.never_cache
293 def delete_shelf(request, slug):
294     user_set = get_object_or_404(models.Tag, slug=slug, category='set', user=request.user)
295     user_set.delete()
296
297     if request.is_ajax():
298         return HttpResponse(u'<p>Półka <strong>%s</strong> została usunięta</p>' % user_set.name)
299     else:
300         return HttpResponseRedirect('/')
301
302
303 # ==================
304 # = Authentication =
305 # ==================
306 @require_POST
307 @cache.never_cache
308 def login(request):
309     form = AuthenticationForm(data=request.POST, prefix='login')
310     if form.is_valid():
311         auth.login(request, form.get_user())
312         response_data = {'success': True, 'errors': {}}
313     else:
314         response_data = {'success': False, 'errors': form.errors}
315     return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
316
317
318 @require_POST
319 @cache.never_cache
320 def register(request):
321     registration_form = UserCreationForm(request.POST, prefix='registration')
322     if registration_form.is_valid():
323         user = registration_form.save()
324         user = auth.authenticate(
325             username=registration_form.cleaned_data['username'], 
326             password=registration_form.cleaned_data['password1']
327         )
328         auth.login(request, user)
329         response_data = {'success': True, 'errors': {}}
330     else:
331         response_data = {'success': False, 'errors': registration_form.errors}
332     return HttpResponse(LazyEncoder(ensure_ascii=False).encode(response_data))
333
334
335 @cache.never_cache
336 def logout_then_redirect(request):
337     auth.logout(request)
338     return HttpResponseRedirect(request.GET.get('next', '/'))
339