publish PDF with images
[wolnelektury.git] / src / catalogue / forms.py
1 # -*- coding: utf-8 -*-
2 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
3 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
4 #
5 import urllib
6 import os.path
7
8 from django import forms
9 from django.utils.translation import ugettext_lazy as _
10
11 from catalogue.models import Book
12 from waiter.models import WaitedFile
13 from django.core.exceptions import ValidationError
14 from catalogue.utils import get_customized_pdf_path
15 from catalogue.tasks import build_custom_pdf
16 from wolnelektury.utils import makedirs
17
18
19 class BookImportForm(forms.Form):
20     book_xml_file = forms.FileField(required=False)
21     book_xml = forms.CharField(required=False)
22     gallery_url = forms.CharField(required=False)
23
24     def clean(self):
25         from django.core.files.base import ContentFile
26
27         if not self.cleaned_data['book_xml_file']:
28             if self.cleaned_data['book_xml']:
29                 self.cleaned_data['book_xml_file'] = \
30                     ContentFile(self.cleaned_data['book_xml'].encode('utf-8'))
31             else:
32                 raise forms.ValidationError(_("Please supply an XML."))
33         return super(BookImportForm, self).clean()
34
35     def save(self, commit=True, **kwargs):
36         return Book.from_xml_file(self.cleaned_data['book_xml_file'], overwrite=True,
37                                   remote_gallery_url=self.cleaned_data['gallery_url'], **kwargs)
38
39
40 FORMATS = [(f, f.upper()) for f in Book.ebook_formats]
41
42
43 class DownloadFormatsForm(forms.Form):
44     formats = forms.MultipleChoiceField(required=False, choices=FORMATS, widget=forms.CheckboxSelectMultiple)
45
46     def __init__(self, *args, **kwargs):
47         super(DownloadFormatsForm, self).__init__(*args, **kwargs)
48
49
50 CUSTOMIZATION_FLAGS = (
51     ('nofootnotes', _("Don't show footnotes")),
52     ('nothemes', _("Don't disply themes")),
53     ('nowlfont', _("Don't use our custom font")),
54     ('no-cover', _("Without cover")),
55     )
56 CUSTOMIZATION_OPTIONS = (
57     ('leading', _("Leading"), (
58         ('', _('Normal leading')),
59         ('onehalfleading', _('One and a half leading')),
60         ('doubleleading', _('Double leading')),
61     )),
62     ('fontsize', _("Font size"), (
63         ('', _('Default')),
64         ('13pt', _('Big'))
65     )),
66     # ('pagesize', _("Paper size"), (
67     #     ('a4paper', _('A4')),
68     #     ('a5paper', _('A5')),
69     # )),
70 )
71
72
73 class CustomPDFForm(forms.Form):
74     def __init__(self, book, *args, **kwargs):
75         super(CustomPDFForm, self).__init__(*args, **kwargs)
76         self.book = book
77         for name, label in CUSTOMIZATION_FLAGS:
78             self.fields[name] = forms.BooleanField(required=False, label=label)
79         for name, label, choices in CUSTOMIZATION_OPTIONS:
80             self.fields[name] = forms.ChoiceField(choices, required=False, label=label)
81
82     def clean(self):
83         self.cleaned_data['cust'] = self.customizations
84         self.cleaned_data['path'] = get_customized_pdf_path(self.book, self.cleaned_data['cust'])
85         if not WaitedFile.can_order(self.cleaned_data['path']):
86             raise ValidationError(_('Queue is full. Please try again later.'))
87         return self.cleaned_data
88
89     @property
90     def customizations(self):
91         c = []
92         for name, label in CUSTOMIZATION_FLAGS:
93             if self.cleaned_data.get(name):
94                 c.append(name)
95         for name, label, choices in CUSTOMIZATION_OPTIONS:
96             option = self.cleaned_data.get(name)
97             if option:
98                 c.append(option)
99         c.sort()
100         return c
101
102     def save(self, *args, **kwargs):
103         if not self.cleaned_data['cust'] and self.book.pdf_file:
104             # Don't build with default options, just redirect to the standard file.
105             return {"redirect": self.book.pdf_file.url}
106         url = WaitedFile.order(
107             self.cleaned_data['path'],
108             lambda p, waiter_id: build_custom_pdf.delay(self.book.id, self.cleaned_data['cust'], p, waiter_id),
109             self.book.pretty_title()
110         )
111         return {"redirect": url}