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