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