36010c7508e4d4dc52f09d6d0996a5040e30422e
[redakcja.git] / apps / 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 StringIO import StringIO
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
22     def __init__(self, *args, **kwargs):
23         super(ImageAddForm, self).__init__(*args, **kwargs)
24         self.fields['file'].required = False
25
26     def clean_download_url(self):
27         cl = self.cleaned_data['download_url'] or None
28         if cl is not None:
29             try:
30                 img = Image.objects.get(download_url=cl)
31             except Image.DoesNotExist:
32                 pass
33             else:
34                 raise forms.ValidationError(mark_safe(
35                     ugettext('Image <a href="%(url)s">already in repository</a>.')
36                     % {'url': img.get_absolute_url()}))
37         return cl
38
39     def clean(self):
40         cleaned_data = super(ImageAddForm, self).clean()
41         download_url = cleaned_data.get('download_url', None)
42         uploaded_file = cleaned_data.get('file', None)
43         if not download_url and not uploaded_file:
44             raise forms.ValidationError('No image specified')
45         if download_url:
46             image_data = URLOpener().open(download_url).read()
47             width, height = PILImage.open(StringIO(image_data)).size
48         else:
49             width, height = PILImage.open(uploaded_file.file).size
50         min_width, min_height = settings.MIN_COVER_SIZE
51         if width < min_width or height < min_height:
52             raise forms.ValidationError('Image too small: %sx%s, minimal dimensions %sx%s' %
53                                         (width, height, min_width, min_height))
54         return cleaned_data
55
56
57 class ImageEditForm(forms.ModelForm):
58     """Form used for editing a Book."""
59     class Meta:
60         model = Image
61         exclude = ['download_url']
62
63     def clean(self):
64         cleaned_data = super(ImageEditForm, self).clean()
65         uploaded_file = cleaned_data.get('file', None)
66         width, height = PILImage.open(uploaded_file.file).size
67         min_width, min_height = settings.MIN_COVER_SIZE
68         if width < min_width or height < min_height:
69             raise forms.ValidationError('Image too small: %sx%s, minimal dimensions %sx%s' %
70                                         (width, height, min_width, min_height))
71
72
73 class ReadonlyImageEditForm(ImageEditForm):
74     """Form used for not editing an Image."""
75
76     def __init__(self, *args, **kwargs):
77         super(ReadonlyImageEditForm, self).__init__(*args, **kwargs)
78         for field in self.fields.values():
79             field.widget.attrs.update({"readonly": True})
80
81     def save(self, *args, **kwargs):
82         raise AssertionError("ReadonlyImageEditForm should not be saved.")
83
84
85 class FlickrForm(forms.Form):
86     source_url = forms.URLField(label=_('Flickr URL'))
87
88     def clean_source_url(self):
89         url = self.cleaned_data['source_url']
90         try:
91             flickr_data = get_flickr_data(url)
92         except FlickrError as e:
93             raise forms.ValidationError(e)
94         for field_name in ('license_url', 'license_name', 'author', 'title', 'download_url'):
95             self.cleaned_data[field_name] = flickr_data[field_name]
96         return flickr_data['source_url']