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):
16 class ImageEditForm(forms.ModelForm):
17 """Form used for editing a Book."""
20 exclude = ['download_url']
23 class ReadonlyImageEditForm(ImageEditForm):
24 """Form used for not editing a Book."""
26 def __init__(self, *args, **kwargs):
27 ret = super(ReadonlyImageEditForm, self).__init__(*args, **kwargs)
28 for field in self.fields.values():
29 field.widget.attrs.update({"readonly": True})
32 def save(self, *args, **kwargs):
33 raise AssertionError, "ReadonlyImageEditForm should not be saved."
36 class FlickrForm(forms.Form):
37 source_url = forms.URLField(label=_('Flickr URL'))
39 def clean_source_url(self):
40 def normalize_html(html):
41 return re.sub('[\t\n]', '', html)
43 url = self.cleaned_data['source_url']
44 m = re.match(r'(https?://)?(www\.|secure\.)?flickr\.com/photos/(?P<author>[^/]+)/(?P<img>\d+)/?', url)
46 raise forms.ValidationError("It doesn't look like Flickr URL.")
47 author_slug, img_id = m.group('author'), m.group('img')
48 base_url = "https://www.flickr.com/photos/%s/%s/" % (author_slug, img_id)
51 html = normalize_html(urlopen(url).read().decode('utf-8'))
53 raise forms.ValidationError('Error reading page.')
54 match = re.search(r'<a href="([^"]*)" rel="license cc:license">Some rights reserved</a>', html)
57 license_url = match.group(1)
58 self.cleaned_data['license_url'] = license_url
59 re_license = re.compile(r'http://creativecommons.org/licenses/([^/]*)/([^/]*)/.*')
60 m = re_license.match(license_url)
62 self.cleaned_data['license_name'] = 'CC %s %s' % (m.group(1).upper(), m.group(2))
63 except AssertionError:
64 raise forms.ValidationError('Error reading license name.')
66 m = re.search(r'<span class="photo-name-line-2">([^<]*)</span>', html)
68 self.cleaned_data['author'] = "%s@Flickr" % m.group(1)
70 raise forms.ValidationError('Error reading author name.')
72 m = re.search(r'<h1[^>]*>(.*?)</h1>', html)
74 raise forms.ValidationError('Error reading image title.')
75 self.cleaned_data['title'] = m.group(1)
77 url_size = base_url + "sizes/o/"
78 html = normalize_html(urlopen(url_size).read().decode('utf-8'))
79 m = re.search(r'<div id="allsizes-photo">\s*<img src="([^"]*)"', html)
81 self.cleaned_data['download_url'] = m.group(1)
83 raise forms.ValidationError('Error reading image URL.')