f5f2901dfe6e6cb85a3acb324be79262018ef683
[redakcja.git] / src / documents / forms.py
1 # This file is part of FNP-Redakcja, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
3 #
4 from django.db.models import Count
5 from django import forms
6 from django.utils.translation import ugettext_lazy as _
7 from django.conf import settings
8
9 from .constants import MASTERS
10 from .models import Book, Chunk, Image, User
11
12 class DocumentCreateForm(forms.ModelForm):
13     """
14         Form used for creating new documents.
15     """
16     file = forms.FileField(required=False)
17     text = forms.CharField(required=False, widget=forms.Textarea)
18
19     class Meta:
20         model = Book
21         exclude = ['parent', 'parent_number', 'project']
22
23     def __init__(self, *args, **kwargs):
24         super(DocumentCreateForm, self).__init__(*args, **kwargs)
25         self.fields['slug'].widget.attrs={'class': 'autoslug'}
26         self.fields['gallery'].widget.attrs={'class': 'autoslug'}
27         self.fields['title'].widget.attrs={'class': 'autoslug-source'}
28
29     def clean(self):
30         super(DocumentCreateForm, self).clean()
31         file = self.cleaned_data['file']
32
33         if file is not None:
34             try:
35                 self.cleaned_data['text'] = file.read().decode('utf-8')
36             except UnicodeDecodeError:
37                 raise forms.ValidationError(_("Text file must be UTF-8 encoded."))
38
39         if not self.cleaned_data["text"]:
40             self._errors["file"] = self.error_class([_("You must either enter text or upload a file")])
41
42         return self.cleaned_data
43
44
45 class DocumentsUploadForm(forms.Form):
46     """
47         Form used for uploading new documents.
48     """
49     file = forms.FileField(required=True, label=_('ZIP file'))
50     dirs = forms.BooleanField(label=_('Directories are documents in chunks'),
51             widget = forms.CheckboxInput(attrs={'disabled':'disabled'}))
52
53     def clean(self):
54         file = self.cleaned_data['file']
55
56         import zipfile
57         try:
58             z = self.cleaned_data['zip'] = zipfile.ZipFile(file)
59         except zipfile.BadZipfile:
60             raise forms.ValidationError("Should be a ZIP file.")
61         if z.testzip():
62             raise forms.ValidationError("ZIP file corrupt.")
63
64         return self.cleaned_data
65
66
67 class ChunkForm(forms.ModelForm):
68     """
69         Form used for editing a chunk.
70     """
71     user = forms.ModelChoiceField(queryset=
72         User.objects.annotate(count=Count('chunk')).
73         order_by('last_name', 'first_name'), required=False,
74         label=_('Assigned to')) 
75
76     class Meta:
77         model = Chunk
78         fields = ['title', 'slug', 'gallery_start', 'user', 'stage']
79         exclude = ['number']
80
81     def __init__(self, *args, **kwargs):
82         super(ChunkForm, self).__init__(*args, **kwargs)
83         self.fields['gallery_start'].widget.attrs={'class': 'number-input'}
84         self.fields['slug'].widget.attrs={'class': 'autoslug'}
85         self.fields['title'].widget.attrs={'class': 'autoslug-source'}
86
87     def clean_slug(self):
88         slug = self.cleaned_data['slug']
89         try:
90             chunk = Chunk.objects.get(book=self.instance.book, slug=slug)
91         except Chunk.DoesNotExist:
92             return slug
93         if chunk == self.instance:
94             return slug
95         raise forms.ValidationError(_('Chunk with this slug already exists'))
96
97
98 class ChunkAddForm(ChunkForm):
99     """
100         Form used for adding a chunk to a document.
101     """
102
103     def clean_slug(self):
104         slug = self.cleaned_data['slug']
105         try:
106             user = Chunk.objects.get(book=self.instance.book, slug=slug)
107         except Chunk.DoesNotExist:
108             return slug
109         raise forms.ValidationError(_('Chunk with this slug already exists'))
110
111
112 class BookAppendForm(forms.Form):
113     """
114         Form for appending a book to another book.
115         It means moving all chunks from book A to book B and deleting A.
116     """
117     append_to = forms.ModelChoiceField(queryset=Book.objects.all(),
118             label=_("Append to"))
119
120     def __init__(self, book, *args, **kwargs):
121         ret =  super(BookAppendForm, self).__init__(*args, **kwargs)
122         self.fields['append_to'].queryset = Book.objects.exclude(pk=book.pk)
123         return ret
124
125
126 class BookForm(forms.ModelForm):
127     """Form used for editing a Book."""
128
129     class Meta:
130         model = Book
131         exclude = ['project']
132
133     def __init__(self, *args, **kwargs):
134         ret = super(BookForm, self).__init__(*args, **kwargs)
135         self.fields['slug'].widget.attrs.update({"class": "autoslug"})
136         self.fields['title'].widget.attrs.update({"class": "autoslug-source"})
137         return ret
138
139     def save(self, **kwargs):
140         orig_instance = Book.objects.get(pk=self.instance.pk)
141         old_gallery = orig_instance.gallery
142         new_gallery = self.cleaned_data['gallery']
143         if new_gallery and old_gallery and new_gallery != old_gallery:
144             import shutil
145             import os.path
146             from django.conf import settings
147             shutil.move(orig_instance.gallery_path(),
148                         os.path.join(settings.MEDIA_ROOT, settings.IMAGE_DIR, new_gallery))
149         super(BookForm, self).save(**kwargs)
150
151
152 class ReadonlyBookForm(BookForm):
153     """Form used for not editing a Book."""
154
155     def __init__(self, *args, **kwargs):
156         ret = super(ReadonlyBookForm, self).__init__(*args, **kwargs)
157         for field in self.fields.values():
158             field.widget.attrs.update({"disabled": "disabled"})
159         return ret
160
161
162 class ChooseMasterForm(forms.Form):
163     """
164         Form used for fixing the chunks in a book.
165     """
166
167     master = forms.ChoiceField(choices=((m, m) for m in MASTERS))
168
169
170 class ImageForm(forms.ModelForm):
171     """Form used for editing an Image."""
172     user = forms.ModelChoiceField(queryset=
173         User.objects.annotate(count=Count('chunk')).
174         order_by('-count', 'last_name', 'first_name'), required=False,
175         label=_('Assigned to')) 
176
177     class Meta:
178         model = Image
179         fields = ['title', 'slug', 'user', 'stage']
180
181     def __init__(self, *args, **kwargs):
182         super(ImageForm, self).__init__(*args, **kwargs)
183         self.fields['slug'].widget.attrs={'class': 'autoslug'}
184         self.fields['title'].widget.attrs={'class': 'autoslug-source'}
185
186
187 class ReadonlyImageForm(ImageForm):
188     """Form used for not editing an Image."""
189
190     def __init__(self, *args, **kwargs):
191         super(ReadonlyImageForm, self).__init__(*args, **kwargs)
192         for field in self.fields.values():
193             field.widget.attrs.update({"disabled": "disabled"})
194
195
196 class MarkFinalForm(forms.Form):
197     username = forms.CharField(initial=settings.LITERARY_DIRECTOR_USERNAME)
198     comment = forms.CharField(initial=u'Ostateczna akceptacja merytoryczna przez kierownika literackiego.')
199     books = forms.CharField(widget=forms.Textarea, help_text=u'linki do książek w redakcji, po jednym na wiersz')
200
201     def clean_books(self):
202         books_value = self.cleaned_data['books']
203         slugs = [line.strip().strip('/').split('/')[-1] for line in books_value.split('\n') if line.strip()]
204         books = Book.objects.filter(slug__in=slugs)
205         if len(books) != len(slugs):
206             raise forms.ValidationError(
207                 'Incorrect slug(s): %s' % ' '.join(slug for slug in slugs if not Book.objects.filter(slug=slug)))
208         return books
209
210     def clean_username(self):
211         username = self.cleaned_data['username']
212         if not User.objects.filter(username=username):
213             raise forms.ValidationError('Invalid username')
214         return username
215
216     def save(self):
217         for book in self.cleaned_data['books']:
218             for chunk in book.chunk_set.all():
219                 src = chunk.head.materialize()
220                 chunk.commit(
221                     text=src,
222                     author=User.objects.get(username=self.cleaned_data['username']),
223                     description=self.cleaned_data['comment'],
224                     tags=[Chunk.tag_model.objects.get(slug='editor-proofreading')],
225                     publishable=True
226                 )
227
228
229 class PublishOptionsForm(forms.Form):
230     days = forms.IntegerField(label=u'po ilu dniach udostępnienić (0 = od razu)', min_value=0, initial=0)
231     beta = forms.BooleanField(label=u'Opublikuj na wersji testowej', required=False)