1 # -*- coding: utf-8 -*-
2 from datetime import date, timedelta
7 from django.conf import settings
8 from django.contrib import auth
9 from django.contrib.auth.models import User
10 from django.contrib.auth.decorators import login_required
11 from django.core.urlresolvers import reverse
12 from django.db.models import Count
13 from django import http
14 from django.http import Http404
15 from django.shortcuts import get_object_or_404, render, redirect
16 from django.utils.http import urlquote_plus
17 from django.views.decorators.http import require_POST
19 from catalogue import forms
20 from catalogue import helpers
21 from catalogue.helpers import active_tab
22 from .constants import STAGES
23 from .models import Document, Plan
24 from dvcs.models import Revision
25 from organizations.models import Organization
26 from fileupload.views import UploadView, PackageView
29 # Quick hack around caching problems, TODO: use ETags
31 from django.views.decorators.cache import never_cache
32 # from fnpdjango.utils.text.slughifi import slughifi
34 logger = logging.getLogger("fnp.catalogue")
39 def document_list(request):
40 return render(request, 'catalogue/document_list.html')
44 def user(request, username):
45 user = get_object_or_404(User, username=username)
46 return render(request, 'catalogue/user_page.html', {"viewed_user": user})
53 return render(request, 'catalogue/my_page.html', {
55 request.session.get("wiki_last_books", {}).items(), key=lambda x: x[1]['time'], reverse=True),
63 return render(request, 'catalogue/user_list.html', {
64 'users': User.objects.all().annotate(count=Count('chunk')).order_by(
65 '-count', 'last_name', 'first_name'),
69 @active_tab('activity')
70 def activity(request, isodate=None):
73 day = helpers.parse_isodate(isodate)
80 next_day = day + timedelta(1)
81 prev_day = day - timedelta(1)
83 return render(request, 'catalogue/activity.html', locals())
87 def logout_then_redirect(request):
89 return http.HttpResponseRedirect(urlquote_plus(request.GET.get('next', '/'), safe='/?='))
92 # @permission_required('catalogue.add_book')
95 def create_missing(request):
96 if request.method == "POST":
97 form = forms.DocumentCreateForm(request.POST, request.FILES)
100 if request.user.is_authenticated():
101 creator = request.user
105 title = form.cleaned_data['title']
107 org = request.user.membership_set.get(
108 organization=int(form.cleaned_data['owner_organization'])).organization
109 kwargs = {'owner_organization': org}
111 kwargs = {'owner_user': request.user}
113 doc = Document.objects.create(**kwargs)
115 cover = request.FILES.get('cover')
117 uppath = 'uploads/%d/' % doc.pk
118 path = settings.MEDIA_ROOT + uppath
119 if not os.path.isdir(path):
121 dest_path = path + cover.name # UNSAFE
122 with open(dest_path, 'w') as destination:
123 for chunk in cover.chunks():
124 destination.write(chunk)
125 cover_url = 'http://milpeer.eu/media/dynamic/' + uppath + cover.name
130 text='''<section xmlns="http://nowoczesnapolska.org.pl/sst#" xmlns:dc="http://purl.org/dc/elements/1.1/">
132 <dc:publisher>''' + form.cleaned_data['publisher'] + '''</dc:publisher>
133 <dc:description>''' + form.cleaned_data['description'] + '''</dc:description>
134 <dc:language>''' + form.cleaned_data['language'] + '''</dc:language>
135 <dc:rights>''' + form.cleaned_data['rights'] + '''</dc:rights>
136 <dc:audience>''' + form.cleaned_data['audience'] + '''</dc:audience>
137 <dc:relation.coverImage.url>''' + cover_url + '''</dc:relation.coverImage.url>
139 <header>''' + title + '''</header>
140 <div class="p"> </div>
144 doc.assigned_to = request.user
147 return http.HttpResponseRedirect(reverse("wiki_editor", args=[doc.pk]))
149 org_pk = request.GET.get('organization')
152 org = Organization.objects.get(pk=org_pk)
153 except Organization.DoesNotExist:
156 if not org.is_member(request.user):
163 form = forms.DocumentCreateForm(initial={'owner_organization': org})
165 return render(request, "catalogue/document_create_missing.html", {
172 # @permission_required('catalogue.add_book')
173 # @active_tab('upload')
174 # def upload(request):
175 # if request.method == "POST":
176 # form = forms.DocumentsUploadForm(request.POST, request.FILES)
177 # if form.is_valid():
180 # if request.user.is_authenticated():
181 # creator = request.user
185 # zip = form.cleaned_data['zip']
190 # existing = [book.slug for book in Book.objects.all()]
191 # for filename in zip.namelist():
192 # if filename[-1] == '/':
194 # title = os.path.basename(filename)[:-4]
195 # slug = slughifi(title)
196 # if not (slug and filename.endswith('.xml')):
197 # skipped_list.append(filename)
198 # elif slug in slugs:
199 # error_list.append((filename, slug, _('Slug already used for %s' % slugs[slug])))
200 # elif slug in existing:
201 # error_list.append((filename, slug, _('Slug already used in repository.')))
204 # zip.read(filename).decode('utf-8') # test read
205 # ok_list.append((filename, slug, title))
206 # except UnicodeDecodeError:
207 # error_list.append((filename, title, _('File should be UTF-8 encoded.')))
208 # slugs[slug] = filename
211 # for filename, slug, title in ok_list:
212 # book = Book.create(
213 # text=zip.read(filename).decode('utf-8'),
219 # return render(request, "catalogue/document_upload.html", {
221 # "ok_list": ok_list,
222 # "skipped_list": skipped_list,
223 # "error_list": error_list,
228 # form = forms.DocumentsUploadForm()
230 # return render(request, "catalogue/document_upload.html", {
238 # def book_xml(request, slug):
239 # book = get_object_or_404(Book, slug=slug)
240 # if not book.accessible(request):
241 # return HttpResponseForbidden("Not authorized.")
242 # xml = book.materialize()
244 # response = http.HttpResponse(xml, content_type='application/xml', mimetype='application/wl+xml')
245 # response['Content-Disposition'] = 'attachment; filename=%s.xml' % slug
250 # def book_txt(request, slug):
251 # book = get_object_or_404(Book, slug=slug)
252 # if not book.accessible(request):
253 # return HttpResponseForbidden("Not authorized.")
255 # doc = book.wldocument()
256 # text = doc.as_text().get_string()
257 # response = http.HttpResponse(text, content_type='text/plain', mimetype='text/plain')
258 # response['Content-Disposition'] = 'attachment; filename=%s.txt' % slug
263 def book_html(request, pk, rev_pk=None, preview=False):
264 from librarian.document import Document as SST
265 from librarian.formats.html import HtmlFormat
267 doc = get_object_or_404(Document, pk=pk, deleted=False)
270 published_revision = doc.publish_log.all()[0].revision
272 published_revision = None
276 revision = doc.revision
278 if published_revision is not None:
279 revision = published_revision
281 # No published version, fallback to preview mode.
283 revision = doc.revision
285 revision = get_object_or_404(Revision, pk=rev_pk)
287 was_published = revision == published_revision or doc.publish_log.filter(revision=revision).exists()
289 sst = SST.from_string(revision.materialize())
290 html = HtmlFormat(sst).build(
291 files_path='http://%s/media/dynamic/uploads/%s/' % (request.get_host(), pk)).get_string()
293 # response = http.HttpResponse(html, content_type='text/html', mimetype='text/html')
296 # for fragment in book.fragments.all().iterator():
297 # for theme in fragment.tags.filter(category='theme').iterator():
298 # book_themes.setdefault(theme, []).append(fragment)
300 # book_themes = book_themes.items()
301 # book_themes.sort(key=lambda s: s[0].sort_key)
302 return render(request, 'catalogue/book_text.html', {
305 'revision': revision,
306 'published_revision': published_revision,
307 'specific': rev_pk is not None,
309 'can_edit': doc.can_edit(request.user) if doc else None,
310 'was_published': was_published,
315 def book_pdf(request, pk, rev_pk):
316 from librarian.utils import Context
317 from librarian.document import Document as SST
318 from librarian.formats.pdf import PdfFormat
320 doc = get_object_or_404(Document, pk=pk)
321 rev = get_object_or_404(Revision, pk=rev_pk)
324 sst = SST.from_string(rev.materialize())
327 files_path='http://%s/media/dynamic/uploads/%s/' % (request.get_host(), pk),
328 source_url='http://%s%s' % (request.get_host(), reverse('catalogue_html', args=[doc.pk])),
330 if doc.owner_organization is not None and doc.owner_organization.logo:
331 ctx.cover_logo = 'http://%s%s' % (request.get_host(), doc.owner_organization.logo.url)
332 pdf_file = PdfFormat(sst).build(ctx)
334 from catalogue.ebook_utils import serve_file
335 return serve_file(pdf_file.get_filename(), '%d.pdf' % doc.pk, 'application/pdf')
339 def book_epub(request, pk, rev_pk):
340 from librarian.utils import Context
341 from librarian.document import Document as SST
342 from librarian.formats.epub import EpubFormat
344 doc = get_object_or_404(Document, pk=pk)
345 rev = get_object_or_404(Revision, pk=rev_pk)
348 sst = SST.from_string(rev.materialize())
351 files_path='http://%s/media/dynamic/uploads/%s/' % (request.get_host(), pk),
352 source_url='http://%s%s' % (request.get_host(), reverse('catalogue_html', args=[doc.pk])),
354 if doc.owner_organization is not None and doc.owner_organization.logo:
355 ctx.cover_logo = 'http://%s%s' % (request.get_host(), doc.owner_organization.logo.url)
356 epub_file = EpubFormat(sst).build()
358 from catalogue.ebook_utils import serve_file
359 return serve_file(epub_file.get_filename(), '%d.epub' % doc.pk, 'application/epub+zip')
363 # def revision(request, slug, chunk=None):
365 # doc = Chunk.get(slug, chunk)
366 # except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
368 # if not doc.book.accessible(request):
369 # return HttpResponseForbidden("Not authorized.")
370 # return http.HttpResponse(str(doc.revision()))
374 def book_schedule(request, pk):
375 book = get_object_or_404(Document, pk=pk, deleted=False)
376 if request.method == 'POST':
377 Plan.objects.filter(document=book).delete()
378 for i, s in enumerate(STAGES):
379 user_id = request.POST.get('s%d-user' % i)
380 deadline = request.POST.get('s%d-deadline' % i) or None
381 Plan.objects.create(document=book, stage=s, user_id=user_id, deadline=deadline)
383 book.set_stage(request.POST.get('stage', ''))
384 return redirect('catalogue_user')
387 for p in Plan.objects.filter(document=book):
388 current[p.stage] = (getattr(p.user, 'pk', None), (p.deadline.isoformat() if p.deadline else None))
390 schedule = [(i, s, current.get(s, ())) for (i, s) in enumerate(STAGES)]
392 if book.owner_organization:
393 people = [m.user for m in book.owner_organization.membership_set.exclude(status='pending')]
395 people = [book.owner_user]
396 return render(request, 'catalogue/book_schedule.html', {
398 'schedule': schedule,
404 def book_owner(request, pk):
405 doc = get_object_or_404(Document, pk=pk, deleted=False)
406 user_is_owner = doc.owner_organization and doc.owner_organization.is_member(request.user)
407 if not (doc.owner_user == request.user or user_is_owner):
412 if request.method == 'POST':
414 new_org_pk = request.POST.get('owner_organization')
416 doc.owner_organization = None
417 doc.owner_user = request.user
420 org = Organization.objects.get(pk=new_org_pk)
421 if not org.is_member(request.user):
422 error = 'Bad organization'
424 doc.owner_organization = org
425 doc.owner_user = None
428 return redirect('catalogue_user')
430 return render(request, 'catalogue/book_owner.html', {
437 def book_delete(request, pk):
438 doc = get_object_or_404(Document, pk=pk, deleted=False)
439 if not (doc.owner_user == request.user or doc.owner_organization.is_member(request.user)):
442 if request.method == 'POST':
445 return redirect('catalogue_user')
447 return render(request, 'catalogue/book_delete.html', {
452 # def book(request, slug):
453 # book = get_object_or_404(Book, slug=slug)
454 # if not book.accessible(request):
455 # return HttpResponseForbidden("Not authorized.")
457 # if request.user.has_perm('catalogue.change_book'):
458 # if request.method == "POST":
459 # form = forms.BookForm(request.POST, instance=book)
460 # if form.is_valid():
462 # return http.HttpResponseRedirect(book.get_absolute_url())
464 # form = forms.BookForm(instance=book)
467 # form = forms.ReadonlyBookForm(instance=book)
470 # publish_error = book.publishable_error()
471 # publishable = publish_error is None
473 # return render(request, "catalogue/book_detail.html", {
475 # "publishable": publishable,
476 # "publishable_error": publish_error,
478 # "editable": editable,
482 # @permission_required('catalogue.add_chunk')
483 # def chunk_add(request, slug, chunk):
485 # doc = Chunk.get(slug, chunk)
486 # except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
488 # if not doc.book.accessible(request):
489 # return HttpResponseForbidden("Not authorized.")
491 # if request.method == "POST":
492 # form = forms.ChunkAddForm(request.POST, instance=doc)
493 # if form.is_valid():
494 # if request.user.is_authenticated():
495 # creator = request.user
498 # doc.split(creator=creator,
499 # slug=form.cleaned_data['slug'],
500 # title=form.cleaned_data['title'],
501 # gallery_start=form.cleaned_data['gallery_start'],
502 # user=form.cleaned_data['user'],
503 # stage=form.cleaned_data['stage']
506 # return http.HttpResponseRedirect(doc.book.get_absolute_url())
508 # form = forms.ChunkAddForm(initial={
509 # "slug": str(doc.number + 1),
510 # "title": "cz. %d" % (doc.number + 1, ),
513 # return render(request, "catalogue/chunk_add.html", {
520 # def chunk_edit(request, slug, chunk):
522 # doc = Chunk.get(slug, chunk)
523 # except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
525 # if not doc.book.accessible(request):
526 # return HttpResponseForbidden("Not authorized.")
528 # if request.method == "POST":
529 # form = forms.ChunkForm(request.POST, instance=doc)
530 # if form.is_valid():
532 # go_next = request.GET.get('next', None)
534 # go_next = urlquote_plus(unquote(iri_to_uri(go_next)), safe='/?=&')
536 # go_next = doc.book.get_absolute_url()
537 # return http.HttpResponseRedirect(go_next)
539 # form = forms.ChunkForm(instance=doc)
541 # referer = request.META.get('HTTP_REFERER')
543 # parts = urlsplit(referer)
544 # parts = ['', ''] + list(parts[2:])
545 # go_next = urlquote_plus(urlunsplit(parts))
549 # return render(request, "catalogue/chunk_edit.html", {
552 # "go_next": go_next,
556 # @transaction.atomic
558 # def chunk_mass_edit(request):
559 # if request.method == 'POST':
560 # ids = map(int, filter(lambda i: i.strip()!='', request.POST.get('ids').split(',')))
561 # chunks = map(lambda i: Chunk.objects.get(id=i), ids)
563 # stage = request.POST.get('stage')
566 # stage = Chunk.tag_model.objects.get(slug=stage)
567 # except Chunk.DoesNotExist, e:
570 # for c in chunks: c.stage = stage
572 # username = request.POST.get('user')
573 # logger.info("username: %s" % username)
574 # logger.info(request.POST)
577 # user = User.objects.get(username=username)
578 # except User.DoesNotExist, e:
581 # for c in chunks: c.user = user
583 # status = request.POST.get('status')
585 # books_affected = set()
587 # if status == 'publish':
588 # c.head.publishable = True
590 # elif status == 'unpublish':
591 # c.head.publishable = False
594 # books_affected.add(c.book)
595 # for b in books_affected:
598 # project_id = request.POST.get('project')
601 # project = Project.objects.get(pk=int(project_id))
602 # except (Project.DoesNotExist, ValueError), e:
606 # book.project = project
609 # for c in chunks: c.save()
611 # return HttpResponse("", content_type="text/plain")
616 # @permission_required('catalogue.change_book')
617 # def book_append(request, slug):
618 # book = get_object_or_404(Book, slug=slug)
619 # if not book.accessible(request):
620 # return HttpResponseForbidden("Not authorized.")
622 # if request.method == "POST":
623 # form = forms.BookAppendForm(book, request.POST)
624 # if form.is_valid():
625 # append_to = form.cleaned_data['append_to']
626 # append_to.append(book)
627 # return http.HttpResponseRedirect(append_to.get_absolute_url())
629 # form = forms.BookAppendForm(book)
630 # return render(request, "catalogue/book_append_to.html", {
640 def publish(request, pk):
641 from wiki import forms
642 from .models import PublishRecord
643 from dvcs.models import Revision
645 # FIXME: check permissions
647 doc = get_object_or_404(Document, pk=pk, deleted=False)
648 form = forms.DocumentTextPublishForm(request.POST, prefix="textpublish")
650 rev = Revision.objects.get(pk=form.cleaned_data['revision'])
651 # FIXME: check if in tree
652 # if PublishRecord.objects.filter(revision=rev, document=doc).exists():
653 # return http.HttpResponse('exists')
654 PublishRecord.objects.create(revision=rev, document=doc, user=request.user)
655 if request.is_ajax():
656 return http.HttpResponse('ok')
658 return redirect('catalogue_html', doc.pk)
660 if request.is_ajax():
661 return http.HttpResponse('error')
664 return redirect('catalogue_preview_rev', doc.pk, form.cleaned_data['revision'])
666 return redirect('catalogue_preview', doc.pk)
671 def unpublish(request, pk):
672 # FIXME: check permissions
674 doc = get_object_or_404(Document, pk=pk, deleted=False)
675 doc.publish_log.all().delete()
676 if request.is_ajax():
677 return http.HttpResponse('ok')
679 return redirect('catalogue_html', doc.pk)
682 class GalleryMixin(object):
683 def get_directory(self):
684 # return "%s%s/" % (settings.IMAGE_DIR, 'org%d' % self.org.pk if self.org is not None else self.request.user.pk)
685 return "uploads/%d/" % self.doc.pk
688 class GalleryView(GalleryMixin, UploadView):
690 def breadcrumbs(self):
692 (self.doc.meta()['title'], '/documents/%d/' % self.doc.pk),
695 def get_object(self, request, pk=None):
696 self.doc = Document.objects.get(pk=pk, deleted=False)
699 class GalleryPackageView(GalleryMixin, PackageView):
701 def get_redirect_url(self, slug):
702 return reverse('catalogue_book_gallery', kwargs=dict(slug=slug))
706 def fork(request, pk):
707 doc = get_object_or_404(Document, pk=pk, deleted=False)
708 if request.method == "POST":
709 form = forms.DocumentForkForm(request.POST, request.FILES)
712 org = request.user.membership_set.get(
713 organization=int(form.cleaned_data['owner_organization'])).organization
714 kwargs = {'owner_organization': org}
716 kwargs = {'owner_user': request.user}
718 new_doc = Document.objects.create(revision=doc.revision, **kwargs)
720 if os.path.isdir(settings.MEDIA_ROOT + "uploads/%d" % doc.pk):
722 settings.MEDIA_ROOT + "uploads/%d" % doc.pk,
723 settings.MEDIA_ROOT + "uploads/%d" % new_doc.pk
726 new_doc.assigned_to = request.user
729 return http.HttpResponseRedirect(reverse("wiki_editor", args=[new_doc.pk]))
731 form = forms.DocumentForkForm()
733 return render(request, "catalogue/document_fork.html", {
740 def upcoming(request):
741 return render(request, "catalogue/upcoming.html", {
742 'objects_list': Document.objects.filter(deleted=False).filter(publish_log=None),
746 def finished(request):
747 return render(request, "catalogue/finished.html", {
748 'objects_list': Document.objects.filter(deleted=False).exclude(publish_log=None),