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 cover.models import Image
11 class ImageAddForm(forms.ModelForm):
15 class ImageEditForm(forms.ModelForm):
16 """Form used for editing a Book."""
19 exclude = ['download_url']
22 class ReadonlyImageEditForm(ImageEditForm):
23 """Form used for not editing a Book."""
25 def __init__(self, *args, **kwargs):
26 ret = super(ReadonlyImageEditForm, self).__init__(*args, **kwargs)
27 for field in self.fields.values():
28 field.widget.attrs.update({"readonly": True})
31 def save(self, *args, **kwargs):
32 raise AssertionError, "ReadonlyImageEditForm should not be saved."
35 class FlickrForm(forms.Form):
36 source_url = forms.URLField()
38 def clean_source_url(self):
39 url = self.cleaned_data['source_url']
40 m = re.match(r'(https?://)?(www.)?flickr.com/photos/(?P<author>[^/]+)/(?P<img>\d+)', url)
42 raise forms.ValidationError("It doesn't look like Flickr URL.")
43 author_slug, img_id = m.group('author'), m.group('img')
44 base_url = "https://www.flickr.com/photos/%s/%s/" % (author_slug, img_id)
47 html = urlopen(url).read().decode('utf-8')
49 raise forms.ValidationError('Error reading page.')
50 match = re.search(r'<a href="([^"]*)" rel="license cc:license">Some rights reserved</a>', html)
53 license_url = match.group(1)
54 self.cleaned_data['license_url'] = license_url
55 re_license = re.compile(r'http://creativecommons.org/licenses/([^/]*)/([^/]*)/.*')
56 m = re_license.match(license_url)
58 self.cleaned_data['license_name'] = 'CC %s %s' % (m.group(1).upper(), m.group(2))
59 except AssertionError:
60 raise forms.ValidationError('Error reading license name.')
62 m = re.search(r'<strong class="username">By <a href="[^"]*">([^<]*)</a></strong>', html)
64 self.cleaned_data['author'] = "%s@Flickr" % m.group(1)
66 raise forms.ValidationError('Error reading author name.')
68 m = re.search(r'<h1[^>]*>(.*?)</h1>', html)
70 raise forms.ValidationError('Error reading image title.')
71 self.cleaned_data['title'] = m.group(1)
73 url_size = base_url + "sizes/o/"
74 html = urlopen(url_size).read().decode('utf-8')
75 m = re.search(r'<div id="allsizes-photo">\s*<img src="([^"]*)"', html)
77 self.cleaned_data['download_url'] = m.group(1)
79 raise forms.ValidationError('Error reading image URL.')