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 url = self.cleaned_data['source_url']
41 m = re.match(r'(https?://)?(www\.|secure\.)?flickr\.com/photos/(?P<author>[^/]+)/(?P<img>\d+)', url)
43 raise forms.ValidationError("It doesn't look like Flickr URL.")
44 author_slug, img_id = m.group('author'), m.group('img')
45 base_url = "https://www.flickr.com/photos/%s/%s/" % (author_slug, img_id)
48 html = urlopen(url).read().decode('utf-8')
50 raise forms.ValidationError('Error reading page.')
51 match = re.search(r'<a href="([^"]*)" rel="license cc:license">Some rights reserved</a>', html)
54 license_url = match.group(1)
55 self.cleaned_data['license_url'] = license_url
56 re_license = re.compile(r'http://creativecommons.org/licenses/([^/]*)/([^/]*)/.*')
57 m = re_license.match(license_url)
59 self.cleaned_data['license_name'] = 'CC %s %s' % (m.group(1).upper(), m.group(2))
60 except AssertionError:
61 raise forms.ValidationError('Error reading license name.')
63 m = re.search(r'<strong class="username">By <a href="[^"]*">([^<]*)</a></strong>', html)
65 self.cleaned_data['author'] = "%s@Flickr" % m.group(1)
67 raise forms.ValidationError('Error reading author name.')
69 m = re.search(r'<h1[^>]*>(.*?)</h1>', html)
71 raise forms.ValidationError('Error reading image title.')
72 self.cleaned_data['title'] = m.group(1)
74 url_size = base_url + "sizes/o/"
75 html = urlopen(url_size).read().decode('utf-8')
76 m = re.search(r'<div id="allsizes-photo">\s*<img src="([^"]*)"', html)
78 self.cleaned_data['download_url'] = m.group(1)
80 raise forms.ValidationError('Error reading image URL.')