Handle image reupload correctly.
[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 import re
7 from urllib2 import urlopen
8 from django import forms
9 from django.utils.translation import ugettext_lazy as _
10 from cover.models import Image
11
12 class ImageAddForm(forms.ModelForm):
13     class Meta:
14         model = Image
15
16     def __init__(self, *args, **kwargs):
17         super(ImageAddForm, self).__init__(*args, **kwargs)
18         self.fields['file'].required = False
19
20     def clean_download_url(self):
21         return self.cleaned_data['download_url'] or None
22
23     def clean_source_url(self):
24         return self.cleaned_data['source_url'] or None
25
26     def clean(self):
27         cleaned_data = super(ImageAddForm, self).clean()
28         if not cleaned_data.get('download_url', None) and not cleaned_data.get('file', None):
29             raise forms.ValidationError('No image specified')
30         return cleaned_data
31
32
33 class ImageEditForm(forms.ModelForm):
34     """Form used for editing a Book."""
35     class Meta:
36         model = Image
37         exclude = ['download_url']
38
39
40 class ReadonlyImageEditForm(ImageEditForm):
41     """Form used for not editing an Image."""
42
43     def __init__(self, *args, **kwargs):
44         ret = super(ReadonlyImageEditForm, self).__init__(*args, **kwargs)
45         for field in self.fields.values():
46             field.widget.attrs.update({"readonly": True})
47         return ret
48
49     def save(self, *args, **kwargs):
50         raise AssertionError, "ReadonlyImageEditForm should not be saved."
51
52
53 class FlickrForm(forms.Form):
54     source_url = forms.URLField(label=_('Flickr URL'))
55
56     def clean_source_url(self):
57         def normalize_html(html):
58             return re.sub('[\t\n]', '', html)
59     
60         url = self.cleaned_data['source_url']
61         m = re.match(r'(https?://)?(www\.|secure\.)?flickr\.com/photos/(?P<author>[^/]+)/(?P<img>\d+)/?', url)
62         if not m:
63             raise forms.ValidationError("It doesn't look like Flickr URL.")
64         author_slug, img_id = m.group('author'), m.group('img')
65         base_url = "https://www.flickr.com/photos/%s/%s/" % (author_slug, img_id)
66
67         try:
68             html = normalize_html(urlopen(url).read().decode('utf-8'))
69         except:
70             raise forms.ValidationError('Error reading page.')
71         match = re.search(r'<a href="([^"]*)" rel="license cc:license">Some rights reserved</a>', html)
72         try:
73             assert match
74             license_url = match.group(1)
75             self.cleaned_data['license_url'] = license_url
76             re_license = re.compile(r'http://creativecommons.org/licenses/([^/]*)/([^/]*)/.*')
77             m = re_license.match(license_url)
78             assert m
79             self.cleaned_data['license_name'] = 'CC %s %s' % (m.group(1).upper(), m.group(2))
80         except AssertionError:
81             raise forms.ValidationError('Error reading license name.')
82
83         m = re.search(r'"ownername":"([^"]*)', html)
84         if m:
85             self.cleaned_data['author'] = "%s@Flickr" % m.group(1)
86         else:
87             raise forms.ValidationError('Error reading author name.')
88
89         m = re.search(r'<h1[^>]*>(.*?)</h1>', html)
90         if not m:
91             raise forms.ValidationError('Error reading image title.')
92         self.cleaned_data['title'] = m.group(1)
93
94         url_size = base_url + "sizes/o/"
95         html = normalize_html(urlopen(url_size).read().decode('utf-8'))
96         m = re.search(r'<div id="allsizes-photo">\s*<img src="([^"]*)"', html)
97         if m:
98             self.cleaned_data['download_url'] = m.group(1)
99         else:
100             raise forms.ValidationError('Error reading image URL.')
101         return base_url