89232ea04e3837727b26e49d03c1b871ebc2acd2
[redakcja.git] / apps / catalogue / views.py
1 from datetime import datetime
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):
74     return render(request, 'catalogue/activity.html')
75
76
77 @never_cache
78 def logout_then_redirect(request):
79     auth.logout(request)
80     return http.HttpResponseRedirect(urlquote_plus(request.GET.get('next', '/'), safe='/?='))
81
82
83 @permission_required('catalogue.add_book')
84 @active_tab('create')
85 def create_missing(request, slug=None):
86     if slug is None:
87         slug = ''
88     slug = slug.replace(' ', '-')
89
90     if request.method == "POST":
91         form = forms.DocumentCreateForm(request.POST, request.FILES)
92         if form.is_valid():
93             
94             if request.user.is_authenticated():
95                 creator = request.user
96             else:
97                 creator = None
98             book = Book.create(
99                 text=form.cleaned_data['text'],
100                 creator=creator,
101                 slug=form.cleaned_data['slug'],
102                 title=form.cleaned_data['title'],
103                 gallery=form.cleaned_data['gallery'],
104             )
105
106             return http.HttpResponseRedirect(reverse("catalogue_book", args=[book.slug]))
107     else:
108         form = forms.DocumentCreateForm(initial={
109                 "slug": slug,
110                 "title": slug.replace('-', ' ').title(),
111                 "gallery": slug,
112         })
113
114     return direct_to_template(request, "catalogue/document_create_missing.html", extra_context={
115         "slug": slug,
116         "form": form,
117
118         "logout_to": '/',
119     })
120
121
122 @permission_required('catalogue.add_book')
123 @active_tab('upload')
124 def upload(request):
125     if request.method == "POST":
126         form = forms.DocumentsUploadForm(request.POST, request.FILES)
127         if form.is_valid():
128             import slughifi
129
130             if request.user.is_authenticated():
131                 creator = request.user
132             else:
133                 creator = None
134
135             zip = form.cleaned_data['zip']
136             skipped_list = []
137             ok_list = []
138             error_list = []
139             slugs = {}
140             existing = [book.slug for book in Book.objects.all()]
141             for filename in zip.namelist():
142                 if filename[-1] == '/':
143                     continue
144                 title = os.path.basename(filename)[:-4]
145                 slug = slughifi(title)
146                 if not (slug and filename.endswith('.xml')):
147                     skipped_list.append(filename)
148                 elif slug in slugs:
149                     error_list.append((filename, slug, _('Slug already used for %s' % slugs[slug])))
150                 elif slug in existing:
151                     error_list.append((filename, slug, _('Slug already used in repository.')))
152                 else:
153                     try:
154                         zip.read(filename).decode('utf-8') # test read
155                         ok_list.append((filename, slug, title))
156                     except UnicodeDecodeError:
157                         error_list.append((filename, title, _('File should be UTF-8 encoded.')))
158                     slugs[slug] = filename
159
160             if not error_list:
161                 for filename, slug, title in ok_list:
162                     book = Book.create(
163                         text=zip.read(filename).decode('utf-8'),
164                         creator=creator,
165                         slug=slug,
166                         title=title,
167                     )
168
169             return direct_to_template(request, "catalogue/document_upload.html", extra_context={
170                 "form": form,
171                 "ok_list": ok_list,
172                 "skipped_list": skipped_list,
173                 "error_list": error_list,
174
175                 "logout_to": '/',
176             })
177     else:
178         form = forms.DocumentsUploadForm()
179
180     return direct_to_template(request, "catalogue/document_upload.html", extra_context={
181         "form": form,
182
183         "logout_to": '/',
184     })
185
186
187 @never_cache
188 def book_xml(request, slug):
189     book = get_object_or_404(Book, slug=slug)
190     if not book.accessible(request):
191         return HttpResponseForbidden("Not authorized.")
192     xml = book.materialize()
193
194     response = http.HttpResponse(xml, content_type='application/xml', mimetype='application/wl+xml')
195     response['Content-Disposition'] = 'attachment; filename=%s.xml' % slug
196     return response
197
198
199 @never_cache
200 def book_txt(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     output = StringIO()
206     # errors?
207     librarian.text.transform(StringIO(xml), output)
208     text = output.getvalue()
209     response = http.HttpResponse(text, content_type='text/plain', mimetype='text/plain')
210     response['Content-Disposition'] = 'attachment; filename=%s.txt' % slug
211     return response
212
213
214 @never_cache
215 def book_html(request, slug):
216     book = get_object_or_404(Book, slug=slug)
217     if not book.accessible(request):
218         return HttpResponseForbidden("Not authorized.")
219     xml = book.materialize()
220     output = StringIO()
221     # errors?
222     librarian.html.transform(StringIO(xml), output, parse_dublincore=False,
223                              flags=['full-page'])
224     html = output.getvalue()
225     response = http.HttpResponse(html, content_type='text/html', mimetype='text/html')
226     return response
227
228 @never_cache
229 def revision(request, slug, chunk=None):
230     try:
231         doc = Chunk.get(slug, chunk)
232     except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
233         raise Http404
234     if not doc.book.accessible(request):
235         return HttpResponseForbidden("Not authorized.")
236     return http.HttpResponse(str(doc.revision()))
237
238
239 def book(request, slug):
240     book = get_object_or_404(Book, slug=slug)
241     if not book.accessible(request):
242         return HttpResponseForbidden("Not authorized.")
243
244     if request.user.has_perm('catalogue.change_book'):
245         if request.method == "POST":
246             form = forms.BookForm(request.POST, instance=book)
247             if form.is_valid():
248                 form.save()
249                 return http.HttpResponseRedirect(book.get_absolute_url())
250         else:
251             form = forms.BookForm(instance=book)
252             editable = True
253     else:
254         form = forms.ReadonlyBookForm(instance=book)
255         editable = False
256
257     publish_error = publishable_error(book)
258     publishable = publish_error is None
259
260     return direct_to_template(request, "catalogue/book_detail.html", extra_context={
261         "book": book,
262         "publishable": publishable,
263         "publishable_error": publish_error,
264         "form": form,
265         "editable": editable,
266     })
267
268
269 @permission_required('catalogue.add_chunk')
270 def chunk_add(request, slug, chunk):
271     try:
272         doc = Chunk.get(slug, chunk)
273     except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
274         raise Http404
275     if not doc.book.accessible(request):
276         return HttpResponseForbidden("Not authorized.")
277
278     if request.method == "POST":
279         form = forms.ChunkAddForm(request.POST, instance=doc)
280         if form.is_valid():
281             if request.user.is_authenticated():
282                 creator = request.user
283             else:
284                 creator = None
285             doc.split(creator=creator,
286                 slug=form.cleaned_data['slug'],
287                 title=form.cleaned_data['title'],
288                 gallery_start=form.cleaned_data['gallery_start'],
289                 user=form.cleaned_data['user'],
290                 stage=form.cleaned_data['stage']
291             )
292
293             return http.HttpResponseRedirect(doc.book.get_absolute_url())
294     else:
295         form = forms.ChunkAddForm(initial={
296                 "slug": str(doc.number + 1),
297                 "title": "cz. %d" % (doc.number + 1, ),
298         })
299
300     return direct_to_template(request, "catalogue/chunk_add.html", extra_context={
301         "chunk": doc,
302         "form": form,
303     })
304
305
306 def chunk_edit(request, slug, chunk):
307     try:
308         doc = Chunk.get(slug, chunk)
309     except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
310         raise Http404
311     if not doc.book.accessible(request):
312         return HttpResponseForbidden("Not authorized.")
313
314     if request.method == "POST":
315         form = forms.ChunkForm(request.POST, instance=doc)
316         if form.is_valid():
317             form.save()
318             go_next = request.GET.get('next', None)
319             if go_next:
320                 go_next = urlquote_plus(unquote(iri_to_uri(go_next)), safe='/?=&')
321             else:
322                 go_next = doc.book.get_absolute_url()
323             return http.HttpResponseRedirect(go_next)
324     else:
325         form = forms.ChunkForm(instance=doc)
326
327     parts = urlsplit(request.META['HTTP_REFERER'])
328     parts = ['', ''] + list(parts[2:])
329     go_next = urlquote_plus(urlunsplit(parts))
330
331     return direct_to_template(request, "catalogue/chunk_edit.html", extra_context={
332         "chunk": doc,
333         "form": form,
334         "go_next": go_next,
335     })
336
337
338 @permission_required('catalogue.change_book')
339 def book_append(request, slug):
340     book = get_object_or_404(Book, slug=slug)
341     if not book.accessible(request):
342         return HttpResponseForbidden("Not authorized.")
343
344     if request.method == "POST":
345         form = forms.BookAppendForm(book, request.POST)
346         if form.is_valid():
347             append_to = form.cleaned_data['append_to']
348             append_to.append(book)
349             return http.HttpResponseRedirect(append_to.get_absolute_url())
350     else:
351         form = forms.BookAppendForm(book)
352     return direct_to_template(request, "catalogue/book_append_to.html", extra_context={
353         "book": book,
354         "form": form,
355
356         "logout_to": '/',
357     })
358
359
360 @require_POST
361 @login_required
362 def publish(request, slug):
363     book = get_object_or_404(Book, slug=slug)
364     if not book.accessible(request):
365         return HttpResponseForbidden("Not authorized.")
366
367     try:
368         book.publish(request.user)
369     except NotAuthorizedError:
370         return http.HttpResponseRedirect(reverse('apiclient_oauth'))
371     except BaseException, e:
372         return http.HttpResponse(e)
373     else:
374         return http.HttpResponseRedirect(book.get_absolute_url())