1 # -*- coding: utf-8 -*-
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.
6 from StringIO import StringIO
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
15 from cover.utils import get_flickr_data, FlickrError, URLOpener
18 class ImageAddForm(forms.ModelForm):
22 def __init__(self, *args, **kwargs):
23 super(ImageAddForm, self).__init__(*args, **kwargs)
24 self.fields['file'].required = False
26 def clean_download_url(self):
27 cl = self.cleaned_data['download_url'] or None
30 img = Image.objects.get(download_url=cl)
31 except Image.DoesNotExist:
34 raise forms.ValidationError(mark_safe(
35 ugettext('Image <a href="%(url)s">already in repository</a>.')
36 % {'url': img.get_absolute_url()}))
39 def clean_source_url(self):
40 source_url = self.cleaned_data['source_url'] or None
41 if source_url is not None:
42 same_source = Image.objects.filter(source_url=source_url)
44 raise forms.ValidationError(mark_safe(
45 ugettext('Image <a href="%s">already in repository</a>'
46 % same_source.first().get_absolute_url())))
50 cleaned_data = super(ImageAddForm, self).clean()
51 download_url = cleaned_data.get('download_url', None)
52 uploaded_file = cleaned_data.get('file', None)
53 if not download_url and not uploaded_file:
54 raise forms.ValidationError(ugettext('No image specified'))
56 image_data = URLOpener().open(download_url).read()
57 width, height = PILImage.open(StringIO(image_data)).size
59 width, height = PILImage.open(uploaded_file.file).size
60 min_width, min_height = settings.MIN_COVER_SIZE
61 if width < min_width or height < min_height:
62 raise forms.ValidationError(ugettext('Image too small: %sx%s, minimal dimensions %sx%s') %
63 (width, height, min_width, min_height))
67 class ImageEditForm(forms.ModelForm):
68 """Form used for editing a Book."""
71 exclude = ['download_url']
74 cleaned_data = super(ImageEditForm, self).clean()
75 uploaded_file = cleaned_data.get('file', None)
76 width, height = PILImage.open(uploaded_file.file).size
77 min_width, min_height = settings.MIN_COVER_SIZE
78 if width < min_width or height < min_height:
79 raise forms.ValidationError(ugettext('Image too small: %sx%s, minimal dimensions %sx%s') %
80 (width, height, min_width, min_height))
83 class ReadonlyImageEditForm(ImageEditForm):
84 """Form used for not editing an Image."""
86 def __init__(self, *args, **kwargs):
87 super(ReadonlyImageEditForm, self).__init__(*args, **kwargs)
88 for field in self.fields.values():
89 field.widget.attrs.update({"readonly": True})
91 def save(self, *args, **kwargs):
92 raise AssertionError("ReadonlyImageEditForm should not be saved.")
95 class FlickrForm(forms.Form):
96 source_url = forms.URLField(label=_('Flickr URL'))
98 def clean_source_url(self):
99 url = self.cleaned_data['source_url']
101 flickr_data = get_flickr_data(url)
102 except FlickrError as e:
103 raise forms.ValidationError(e)
104 for field_name in ('license_url', 'license_name', 'author', 'title', 'download_url'):
105 self.cleaned_data[field_name] = flickr_data[field_name]
106 return flickr_data['source_url']