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):
23 def __init__(self, *args, **kwargs):
24 super(ImageAddForm, self).__init__(*args, **kwargs)
25 self.fields['file'].required = False
27 def clean_download_url(self):
28 cl = self.cleaned_data['download_url'] or None
31 img = Image.objects.get(download_url=cl)
32 except Image.DoesNotExist:
35 raise forms.ValidationError(mark_safe(
36 ugettext('Image <a href="%(url)s">already in repository</a>.')
37 % {'url': img.get_absolute_url()}))
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)
45 raise forms.ValidationError(mark_safe(
46 ugettext('Image <a href="%s">already in repository</a>'
47 % same_source.first().get_absolute_url())))
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'))
57 image_data = URLOpener().open(download_url).read()
58 width, height = PILImage.open(StringIO(image_data)).size
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))
68 class ImageEditForm(forms.ModelForm):
69 """Form used for editing a Book."""
72 exclude = ['download_url']
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))
84 class ReadonlyImageEditForm(ImageEditForm):
85 """Form used for not editing an Image."""
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})
92 def save(self, *args, **kwargs):
93 raise AssertionError("ReadonlyImageEditForm should not be saved.")
96 class FlickrForm(forms.Form):
97 source_url = forms.URLField(label=_('Flickr URL'))
99 def clean_source_url(self):
100 url = self.cleaned_data['source_url']
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']