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