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.
5 from urllib.request import urlopen
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
13 from cover.utils import get_import_data, FlickrError
16 class ImageAddForm(forms.ModelForm):
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
30 def clean_download_url(self):
31 cl = self.cleaned_data['download_url'] or None
34 img = Image.objects.get(download_url=cl)
35 except Image.DoesNotExist:
38 raise forms.ValidationError(mark_safe(
39 gettext('Image <a href="%(url)s">already in repository</a>.')
40 % {'url': img.get_absolute_url()}))
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)
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()}))
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
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'))
65 with urlopen(download_url) as f:
67 width, height = PILImage.open(BytesIO(image_data)).size
69 width, height = PILImage.open(uploaded_file.file).size
70 min_width, min_height = settings.MIN_COVER_SIZE
71 if width < min_width or height < min_height:
72 raise forms.ValidationError(gettext('Image too small: %sx%s, minimal dimensions %sx%s') %
73 (width, height, min_width, min_height))
77 class ImageEditForm(forms.ModelForm):
78 """Form used for editing a Book."""
81 exclude = ['download_url', 'use_file', 'example',]
83 def __init__(self, *args, **kwargs):
84 super().__init__(*args, **kwargs)
85 self.fields['file'].required = False
88 cleaned_data = super(ImageEditForm, self).clean()
89 uploaded_file = cleaned_data.get('file', None)
90 if uploaded_file is not None:
91 width, height = PILImage.open(uploaded_file.file).size
92 min_width, min_height = settings.MIN_COVER_SIZE
93 if width < min_width or height < min_height:
94 raise forms.ValidationError(gettext('Image too small: %sx%s, minimal dimensions %sx%s') %
95 (width, height, min_width, min_height))
98 class ReadonlyImageEditForm(ImageEditForm):
99 """Form used for not editing an Image."""
101 def __init__(self, *args, **kwargs):
102 super(ReadonlyImageEditForm, self).__init__(*args, **kwargs)
103 for field in self.fields.values():
104 field.widget.attrs.update({"readonly": True})
106 def save(self, *args, **kwargs):
107 raise AssertionError("ReadonlyImageEditForm should not be saved.")
110 class ImportForm(forms.Form):
111 source_url = forms.URLField(label=_('WikiCommons, MNW, Flickr, RawPixel URL'))
113 def clean_source_url(self):
114 url = self.cleaned_data['source_url']
116 import_data = get_import_data(url)
117 except FlickrError as e:
118 raise forms.ValidationError(e)
119 for field_name in ('license_url', 'license_name', 'author', 'title', 'download_url'):
120 self.cleaned_data[field_name] = import_data[field_name]
121 return import_data['source_url']