e5bc400d96ef5e8580f0ae50ed1db3a9555e7d37
[redakcja.git] / src / cover / forms.py
1 # -*- coding: utf-8 -*-
2 #
3 # This file is part of FNP-Redakcja, licensed under GNU Affero GPLv3 or later.
4 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
5 #
6 from io import BytesIO
7
8 from django import forms
9 from django.conf import settings
10 from django.utils.translation import ugettext_lazy as _, ugettext
11 from cover.models import Image
12 from django.utils.text import mark_safe
13 from PIL import Image as PILImage
14
15 from cover.utils import get_flickr_data, FlickrError, URLOpener
16
17
18 class ImageAddForm(forms.ModelForm):
19     class Meta:
20         model = Image
21         exclude = [] 
22
23     def __init__(self, *args, **kwargs):
24         super(ImageAddForm, self).__init__(*args, **kwargs)
25         self.fields['file'].required = False
26
27     def clean_download_url(self):
28         cl = self.cleaned_data['download_url'] or None
29         if cl is not None:
30             try:
31                 img = Image.objects.get(download_url=cl)
32             except Image.DoesNotExist:
33                 pass
34             else:
35                 raise forms.ValidationError(mark_safe(
36                     ugettext('Image <a href="%(url)s">already in repository</a>.')
37                     % {'url': img.get_absolute_url()}))
38         return cl
39
40     def clean_source_url(self):
41         source_url = self.cleaned_data['source_url'] or None
42         if source_url is not None:
43             same_source = Image.objects.filter(source_url=source_url)
44             if same_source:
45                 raise forms.ValidationError(mark_safe(
46                     ugettext('Image <a href="%s">already in repository</a>'
47                              % same_source.first().get_absolute_url())))
48         return source_url
49
50     def clean(self):
51         cleaned_data = super(ImageAddForm, self).clean()
52         download_url = cleaned_data.get('download_url', None)
53         uploaded_file = cleaned_data.get('file', None)
54         if not download_url and not uploaded_file:
55             raise forms.ValidationError(ugettext('No image specified'))
56         if download_url:
57             image_data = URLOpener().open(download_url).read()
58             width, height = PILImage.open(BytesIO(image_data)).size
59         else:
60             width, height = PILImage.open(uploaded_file.file).size
61         min_width, min_height = settings.MIN_COVER_SIZE
62         if width < min_width or height < min_height:
63             raise forms.ValidationError(ugettext('Image too small: %sx%s, minimal dimensions %sx%s') %
64                                         (width, height, min_width, min_height))
65         return cleaned_data
66
67
68 class ImageEditForm(forms.ModelForm):
69     """Form used for editing a Book."""
70     class Meta:
71         model = Image
72         exclude = ['download_url']
73
74     def clean(self):
75         cleaned_data = super(ImageEditForm, self).clean()
76         uploaded_file = cleaned_data.get('file', None)
77         width, height = PILImage.open(uploaded_file.file).size
78         min_width, min_height = settings.MIN_COVER_SIZE
79         if width < min_width or height < min_height:
80             raise forms.ValidationError(ugettext('Image too small: %sx%s, minimal dimensions %sx%s') %
81                                         (width, height, min_width, min_height))
82
83
84 class ReadonlyImageEditForm(ImageEditForm):
85     """Form used for not editing an Image."""
86
87     def __init__(self, *args, **kwargs):
88         super(ReadonlyImageEditForm, self).__init__(*args, **kwargs)
89         for field in self.fields.values():
90             field.widget.attrs.update({"readonly": True})
91
92     def save(self, *args, **kwargs):
93         raise AssertionError("ReadonlyImageEditForm should not be saved.")
94
95
96 class FlickrForm(forms.Form):
97     source_url = forms.URLField(label=_('Flickr URL'))
98
99     def clean_source_url(self):
100         url = self.cleaned_data['source_url']
101         try:
102             flickr_data = get_flickr_data(url)
103         except FlickrError as e:
104             raise forms.ValidationError(e)
105         for field_name in ('license_url', 'license_name', 'author', 'title', 'download_url'):
106             self.cleaned_data[field_name] = flickr_data[field_name]
107         return flickr_data['source_url']