ad hoc changes
[redakcja.git] / src / cover / 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 io import BytesIO
5
6 from django import forms
7 from django.conf import settings
8 from django.utils.translation import gettext_lazy as _, gettext
9 from cover.models import Image
10 from django.utils.safestring import mark_safe
11 from PIL import Image as PILImage
12
13 from cover.utils import get_import_data, FlickrError, URLOpener
14
15
16 class ImageAddForm(forms.ModelForm):
17     class Meta:
18         model = Image
19         exclude = [] 
20
21     def __init__(self, *args, **kwargs):
22         super(ImageAddForm, self).__init__(*args, **kwargs)
23         self.fields['file'].required = False
24         self.fields['use_file'].required = False
25         self.fields['cut_top'].required = False
26         self.fields['cut_left'].required = False
27         self.fields['cut_bottom'].required = False
28         self.fields['cut_right'].required = False
29
30     def clean_download_url(self):
31         cl = self.cleaned_data['download_url'] or None
32         if cl is not None:
33             try:
34                 img = Image.objects.get(download_url=cl)
35             except Image.DoesNotExist:
36                 pass
37             else:
38                 raise forms.ValidationError(mark_safe(
39                     gettext('Image <a href="%(url)s">already in repository</a>.')
40                     % {'url': img.get_absolute_url()}))
41         return cl
42
43     def clean_source_url(self):
44         source_url = self.cleaned_data['source_url'] or None
45         if source_url is not None:
46             same_source = Image.objects.filter(source_url=source_url)
47             if same_source:
48                 raise forms.ValidationError(mark_safe(
49                     gettext('Image <a href="%(url)s">already in repository</a>.')
50                     % {'url': same_source.first().get_absolute_url()}))
51         return source_url
52
53     clean_cut_top = lambda self: self.cleaned_data.get('cut_top') or 0
54     clean_cut_bottom = lambda self: self.cleaned_data.get('cut_bottom') or 0
55     clean_cut_left = lambda self: self.cleaned_data.get('cut_left') or 0
56     clean_cut_right = lambda self: self.cleaned_data.get('cut_right') or 0
57     
58     def clean(self):
59         cleaned_data = super(ImageAddForm, self).clean()
60         download_url = cleaned_data.get('download_url', None)
61         uploaded_file = cleaned_data.get('file', None)
62         if not download_url and not uploaded_file:
63             raise forms.ValidationError(gettext('No image specified'))
64         if download_url:
65             image_data = URLOpener().open(download_url).read()
66             width, height = PILImage.open(BytesIO(image_data)).size
67         else:
68             width, height = PILImage.open(uploaded_file.file).size
69         min_width, min_height = settings.MIN_COVER_SIZE
70         if width < min_width or height < min_height:
71             raise forms.ValidationError(gettext('Image too small: %sx%s, minimal dimensions %sx%s') %
72                                         (width, height, min_width, min_height))
73         return cleaned_data
74
75
76 class ImageEditForm(forms.ModelForm):
77     """Form used for editing a Book."""
78     class Meta:
79         model = Image
80         exclude = ['download_url']
81
82     def clean(self):
83         cleaned_data = super(ImageEditForm, self).clean()
84         uploaded_file = cleaned_data.get('file', None)
85         width, height = PILImage.open(uploaded_file.file).size
86         min_width, min_height = settings.MIN_COVER_SIZE
87         if width < min_width or height < min_height:
88             raise forms.ValidationError(gettext('Image too small: %sx%s, minimal dimensions %sx%s') %
89                                         (width, height, min_width, min_height))
90
91
92 class ReadonlyImageEditForm(ImageEditForm):
93     """Form used for not editing an Image."""
94
95     def __init__(self, *args, **kwargs):
96         super(ReadonlyImageEditForm, self).__init__(*args, **kwargs)
97         for field in self.fields.values():
98             field.widget.attrs.update({"readonly": True})
99
100     def save(self, *args, **kwargs):
101         raise AssertionError("ReadonlyImageEditForm should not be saved.")
102
103
104 class ImportForm(forms.Form):
105     source_url = forms.URLField(label=_('WikiCommons, MNW, Flickr, RawPixel URL'))
106
107     def clean_source_url(self):
108         url = self.cleaned_data['source_url']
109         try:
110             import_data = get_import_data(url)
111         except FlickrError as e:
112             raise forms.ValidationError(e)
113         for field_name in ('license_url', 'license_name', 'author', 'title', 'download_url'):
114             self.cleaned_data[field_name] = import_data[field_name]
115         return import_data['source_url']
116