c7189d47d0fc84a026bee1616c24a6714a29ed4c
[redakcja.git] / apps / catalogue / views.py
1 from datetime import datetime, date, timedelta
2 import logging
3 import os
4 from StringIO import StringIO
5 from urllib import unquote
6 from urlparse import urlsplit, urlunsplit
7
8 from django.contrib import auth
9 from django.contrib.auth.models import User
10 from django.contrib.auth.decorators import login_required, permission_required
11 from django.core.urlresolvers import reverse
12 from django.db.models import Count, Q
13 from django import http
14 from django.http import Http404, HttpResponseForbidden
15 from django.shortcuts import get_object_or_404, render
16 from django.utils.encoding import iri_to_uri
17 from django.utils.http import urlquote_plus
18 from django.utils.translation import ugettext_lazy as _
19 from django.views.decorators.http import require_POST
20 from django.views.generic.simple import direct_to_template
21
22 import librarian.html
23 import librarian.text
24
25 from apiclient import NotAuthorizedError
26 from catalogue import forms
27 from catalogue import helpers
28 from catalogue.helpers import active_tab
29 from catalogue.models import Book, Chunk, BookPublishRecord, ChunkPublishRecord
30 from catalogue.tasks import publishable_error
31
32 #
33 # Quick hack around caching problems, TODO: use ETags
34 #
35 from django.views.decorators.cache import never_cache
36
37 logger = logging.getLogger("fnp.catalogue")
38
39
40 @active_tab('all')
41 @never_cache
42 def document_list(request):
43     return render(request, 'catalogue/document_list.html')
44
45
46 @never_cache
47 def user(request, username):
48     user = get_object_or_404(User, username=username)
49     return render(request, 'catalogue/user_page.html', {"viewed_user": user})
50
51
52 @login_required
53 @active_tab('my')
54 @never_cache
55 def my(request):
56     return render(request, 'catalogue/my_page.html', {
57         'last_books': sorted(request.session.get("wiki_last_books", {}).items(),
58                         key=lambda x: x[1]['time'], reverse=True),
59
60         "logout_to": '/',
61         })
62
63
64 @active_tab('users')
65 def users(request):
66     return direct_to_template(request, 'catalogue/user_list.html', extra_context={
67         'users': User.objects.all().annotate(count=Count('chunk')).order_by(
68             '-count', 'last_name', 'first_name'),
69     })
70
71
72 @active_tab('activity')
73 def activity(request, isodate=None):
74     today = date.today()
75     try:
76         day = helpers.parse_isodate(isodate)
77     except ValueError:
78         day = today
79
80     if day > today:
81         raise Http404
82     if day != today:
83         next_day = day + timedelta(1)
84     prev_day = day - timedelta(1)
85
86     return render(request, 'catalogue/activity.html', locals())
87
88
89 @never_cache
90 def logout_then_redirect(request):
91     auth.logout(request)
92     return http.HttpResponseRedirect(urlquote_plus(request.GET.get('next', '/'), safe='/?='))
93
94
95 @permission_required('catalogue.add_book')
96 @active_tab('create')
97 def create_missing(request, slug=None):
98     if slug is None:
99         slug = ''
100     slug = slug.replace(' ', '-')
101
102     if request.method == "POST":
103         form = forms.DocumentCreateForm(request.POST, request.FILES)
104         if form.is_valid():
105             
106             if request.user.is_authenticated():
107                 creator = request.user
108             else:
109                 creator = None
110             book = Book.create(
111                 text=form.cleaned_data['text'],
112                 creator=creator,
113                 slug=form.cleaned_data['slug'],
114                 title=form.cleaned_data['title'],
115                 gallery=form.cleaned_data['gallery'],
116             )
117
118             return http.HttpResponseRedirect(reverse("catalogue_book", args=[book.slug]))
119     else:
120         form = forms.DocumentCreateForm(initial={
121                 "slug": slug,
122                 "title": slug.replace('-', ' ').title(),
123                 "gallery": slug,
124         })
125
126     return direct_to_template(request, "catalogue/document_create_missing.html", extra_context={
127         "slug": slug,
128         "form": form,
129
130         "logout_to": '/',
131     })
132
133
134 @permission_required('catalogue.add_book')
135 @active_tab('upload')
136 def upload(request):
137     if request.method == "POST":
138         form = forms.DocumentsUploadForm(request.POST, request.FILES)
139         if form.is_valid():
140             import slughifi
141
142             if request.user.is_authenticated():
143                 creator = request.user
144             else:
145                 creator = None
146
147             zip = form.cleaned_data['zip']
148             skipped_list = []
149             ok_list = []
150             error_list = []
151             slugs = {}
152             existing = [book.slug for book in Book.objects.all()]
153             for filename in zip.namelist():
154                 if filename[-1] == '/':
155                     continue
156                 title = os.path.basename(filename)[:-4]
157                 slug = slughifi(title)
158                 if not (slug and filename.endswith('.xml')):
159                     skipped_list.append(filename)
160                 elif slug in slugs:
161                     error_list.append((filename, slug, _('Slug already used for %s' % slugs[slug])))
162                 elif slug in existing:
163                     error_list.append((filename, slug, _('Slug already used in repository.')))
164                 else:
165                     try:
166                         zip.read(filename).decode('utf-8') # test read
167                         ok_list.append((filename, slug, title))
168                     except UnicodeDecodeError:
169                         error_list.append((filename, title, _('File should be UTF-8 encoded.')))
170                     slugs[slug] = filename
171
172             if not error_list:
173                 for filename, slug, title in ok_list:
174                     book = Book.create(
175                         text=zip.read(filename).decode('utf-8'),
176                         creator=creator,
177                         slug=slug,
178                         title=title,
179                     )
180
181             return direct_to_template(request, "catalogue/document_upload.html", extra_context={
182                 "form": form,
183                 "ok_list": ok_list,
184                 "skipped_list": skipped_list,
185                 "error_list": error_list,
186
187                 "logout_to": '/',
188             })
189     else:
190         form = forms.DocumentsUploadForm()
191
192     return direct_to_template(request, "catalogue/document_upload.html", extra_context={
193         "form": form,
194
195         "logout_to": '/',
196     })
197
198
199 @never_cache
200 def book_xml(request, slug):
201     book = get_object_or_404(Book, slug=slug)
202     if not book.accessible(request):
203         return HttpResponseForbidden("Not authorized.")
204     xml = book.materialize()
205
206     response = http.HttpResponse(xml, content_type='application/xml', mimetype='application/wl+xml')
207     response['Content-Disposition'] = 'attachment; filename=%s.xml' % slug
208     return response
209
210
211 @never_cache
212 def book_txt(request, slug):
213     book = get_object_or_404(Book, slug=slug)
214     if not book.accessible(request):
215         return HttpResponseForbidden("Not authorized.")
216     xml = book.materialize()
217     output = StringIO()
218     # errors?
219     librarian.text.transform(StringIO(xml), output)
220     text = output.getvalue()
221     response = http.HttpResponse(text, content_type='text/plain', mimetype='text/plain')
222     response['Content-Disposition'] = 'attachment; filename=%s.txt' % slug
223     return response
224
225
226 @never_cache
227 def book_html(request, slug):
228     book = get_object_or_404(Book, slug=slug)
229     if not book.accessible(request):
230         return HttpResponseForbidden("Not authorized.")
231     xml = book.materialize()
232     output = StringIO()
233     # errors?
234     librarian.html.transform(StringIO(xml), output, parse_dublincore=False,
235                              flags=['full-page'])
236     html = output.getvalue()
237     response = http.HttpResponse(html, content_type='text/html', mimetype='text/html')
238     return response
239
240 @never_cache
241 def revision(request, slug, chunk=None):
242     try:
243         doc = Chunk.get(slug, chunk)
244     except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
245         raise Http404
246     if not doc.book.accessible(request):
247         return HttpResponseForbidden("Not authorized.")
248     return http.HttpResponse(str(doc.revision()))
249
250
251 def book(request, slug):
252     book = get_object_or_404(Book, slug=slug)
253     if not book.accessible(request):
254         return HttpResponseForbidden("Not authorized.")
255
256     if request.user.has_perm('catalogue.change_book'):
257         if request.method == "POST":
258             form = forms.BookForm(request.POST, instance=book)
259             if form.is_valid():
260                 form.save()
261                 return http.HttpResponseRedirect(book.get_absolute_url())
262         else:
263             form = forms.BookForm(instance=book)
264             editable = True
265     else:
266         form = forms.ReadonlyBookForm(instance=book)
267         editable = False
268
269     publish_error = publishable_error(book)
270     publishable = publish_error is None
271
272     return direct_to_template(request, "catalogue/book_detail.html", extra_context={
273         "book": book,
274         "publishable": publishable,
275         "publishable_error": publish_error,
276         "form": form,
277         "editable": editable,
278     })
279
280
281 @permission_required('catalogue.add_chunk')
282 def chunk_add(request, slug, chunk):
283     try:
284         doc = Chunk.get(slug, chunk)
285     except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
286         raise Http404
287     if not doc.book.accessible(request):
288         return HttpResponseForbidden("Not authorized.")
289
290     if request.method == "POST":
291         form = forms.ChunkAddForm(request.POST, instance=doc)
292         if form.is_valid():
293             if request.user.is_authenticated():
294                 creator = request.user
295             else:
296                 creator = None
297             doc.split(creator=creator,
298                 slug=form.cleaned_data['slug'],
299                 title=form.cleaned_data['title'],
300                 gallery_start=form.cleaned_data['gallery_start'],
301                 user=form.cleaned_data['user'],
302                 stage=form.cleaned_data['stage']
303             )
304
305             return http.HttpResponseRedirect(doc.book.get_absolute_url())
306     else:
307         form = forms.ChunkAddForm(initial={
308                 "slug": str(doc.number + 1),
309                 "title": "cz. %d" % (doc.number + 1, ),
310         })
311
312     return direct_to_template(request, "catalogue/chunk_add.html", extra_context={
313         "chunk": doc,
314         "form": form,
315     })
316
317
318 def chunk_edit(request, slug, chunk):
319     try:
320         doc = Chunk.get(slug, chunk)
321     except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
322         raise Http404
323     if not doc.book.accessible(request):
324         return HttpResponseForbidden("Not authorized.")
325
326     if request.method == "POST":
327         form = forms.ChunkForm(request.POST, instance=doc)
328         if form.is_valid():
329             form.save()
330             go_next = request.GET.get('next', None)
331             if go_next:
332                 go_next = urlquote_plus(unquote(iri_to_uri(go_next)), safe='/?=&')
333             else:
334                 go_next = doc.book.get_absolute_url()
335             return http.HttpResponseRedirect(go_next)
336     else:
337         form = forms.ChunkForm(instance=doc)
338
339     referer = request.META.get('HTTP_REFERER')
340     if referer:
341         parts = urlsplit(referer)
342         parts = ['', ''] + list(parts[2:])
343         go_next = urlquote_plus(urlunsplit(parts))
344     else:
345         go_next = ''
346
347     return direct_to_template(request, "catalogue/chunk_edit.html", extra_context={
348         "chunk": doc,
349         "form": form,
350         "go_next": go_next,
351     })
352
353
354 @permission_required('catalogue.change_book')
355 def book_append(request, slug):
356     book = get_object_or_404(Book, slug=slug)
357     if not book.accessible(request):
358         return HttpResponseForbidden("Not authorized.")
359
360     if request.method == "POST":
361         form = forms.BookAppendForm(book, request.POST)
362         if form.is_valid():
363             append_to = form.cleaned_data['append_to']
364             append_to.append(book)
365             return http.HttpResponseRedirect(append_to.get_absolute_url())
366     else:
367         form = forms.BookAppendForm(book)
368     return direct_to_template(request, "catalogue/book_append_to.html", extra_context={
369         "book": book,
370         "form": form,
371
372         "logout_to": '/',
373     })
374
375
376 @require_POST
377 @login_required
378 def publish(request, slug):
379     book = get_object_or_404(Book, slug=slug)
380     if not book.accessible(request):
381         return HttpResponseForbidden("Not authorized.")
382
383     try:
384         book.publish(request.user)
385     except NotAuthorizedError:
386         return http.HttpResponseRedirect(reverse('apiclient_oauth'))
387     except BaseException, e:
388         return http.HttpResponse(e)
389     else:
390         return http.HttpResponseRedirect(book.get_absolute_url())