update librarian
[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_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)
43             if same_source:
44                 raise forms.ValidationError(mark_safe(
45                     ugettext('Image <a href="%s">already in repository</a>'
46                              % same_source.first().get_absolute_url())))
47
48     def clean(self):
49         cleaned_data = super(ImageAddForm, self).clean()
50         download_url = cleaned_data.get('download_url', None)
51         uploaded_file = cleaned_data.get('file', None)
52         if not download_url and not uploaded_file:
53             raise forms.ValidationError(ugettext('No image specified'))
54         if download_url:
55             image_data = URLOpener().open(download_url).read()
56             width, height = PILImage.open(StringIO(image_data)).size
57         else:
58             width, height = PILImage.open(uploaded_file.file).size
59         min_width, min_height = settings.MIN_COVER_SIZE
60         if width < min_width or height < min_height:
61             raise forms.ValidationError(ugettext('Image too small: %sx%s, minimal dimensions %sx%s') %
62                                         (width, height, min_width, min_height))
63         return cleaned_data
64
65
66 class ImageEditForm(forms.ModelForm):
67     """Form used for editing a Book."""
68     class Meta:
69         model = Image
70         exclude = ['download_url']
71
72     def clean(self):
73         cleaned_data = super(ImageEditForm, self).clean()
74         uploaded_file = cleaned_data.get('file', None)
75         width, height = PILImage.open(uploaded_file.file).size
76         min_width, min_height = settings.MIN_COVER_SIZE
77         if width < min_width or height < min_height:
78             raise forms.ValidationError(ugettext('Image too small: %sx%s, minimal dimensions %sx%s') %
79                                         (width, height, min_width, min_height))
80
81
82 class ReadonlyImageEditForm(ImageEditForm):
83     """Form used for not editing an Image."""
84
85     def __init__(self, *args, **kwargs):
86         super(ReadonlyImageEditForm, self).__init__(*args, **kwargs)
87         for field in self.fields.values():
88             field.widget.attrs.update({"readonly": True})
89
90     def save(self, *args, **kwargs):
91         raise AssertionError("ReadonlyImageEditForm should not be saved.")
92
93
94 class FlickrForm(forms.Form):
95     source_url = forms.URLField(label=_('Flickr URL'))
96
97     def clean_source_url(self):
98         url = self.cleaned_data['source_url']
99         try:
100             flickr_data = get_flickr_data(url)
101         except FlickrError as e:
102             raise forms.ValidationError(e)
103         for field_name in ('license_url', 'license_name', 'author', 'title', 'download_url'):
104             self.cleaned_data[field_name] = flickr_data[field_name]
105         return flickr_data['source_url']