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 _, ugettext
10 from cover.models import Image
11 from django.utils.text import mark_safe
13 class ImageAddForm(forms.ModelForm):
17 def __init__(self, *args, **kwargs):
18 super(ImageAddForm, self).__init__(*args, **kwargs)
19 self.fields['file'].required = False
21 def clean_download_url(self):
22 cl = self.cleaned_data['download_url'] or None
25 img = Image.objects.get(download_url=cl)
26 except Image.DoesNotExist:
29 raise forms.ValidationError(mark_safe(
30 ugettext('Image <a href="%(url)s">already in repository</a>.'
31 ) % {'url': img.get_absolute_url()}))
35 cleaned_data = super(ImageAddForm, self).clean()
36 if not cleaned_data.get('download_url', None) and not cleaned_data.get('file', None):
37 raise forms.ValidationError('No image specified')
40 class ImageEditForm(forms.ModelForm):
41 """Form used for editing a Book."""
44 exclude = ['download_url']
47 class ReadonlyImageEditForm(ImageEditForm):
48 """Form used for not editing an Image."""
50 def __init__(self, *args, **kwargs):
51 ret = super(ReadonlyImageEditForm, self).__init__(*args, **kwargs)
52 for field in self.fields.values():
53 field.widget.attrs.update({"readonly": True})
56 def save(self, *args, **kwargs):
57 raise AssertionError, "ReadonlyImageEditForm should not be saved."
60 class FlickrForm(forms.Form):
61 source_url = forms.URLField(label=_('Flickr URL'))
63 def clean_source_url(self):
64 def normalize_html(html):
65 return re.sub('[\t\n]', '', html)
67 url = self.cleaned_data['source_url']
68 m = re.match(r'(https?://)?(www\.|secure\.)?flickr\.com/photos/(?P<author>[^/]+)/(?P<img>\d+)/?', url)
70 raise forms.ValidationError("It doesn't look like Flickr URL.")
71 author_slug, img_id = m.group('author'), m.group('img')
72 base_url = "https://www.flickr.com/photos/%s/%s/" % (author_slug, img_id)
75 html = normalize_html(urlopen(url).read().decode('utf-8'))
77 raise forms.ValidationError('Error reading page.')
78 match = re.search(r'<a href="([^"]*)" rel="license cc:license">Some rights reserved</a>', html)
81 license_url = match.group(1)
82 self.cleaned_data['license_url'] = license_url
83 re_license = re.compile(r'https?://creativecommons.org/licenses/([^/]*)/([^/]*)/.*')
84 m = re_license.match(license_url)
86 self.cleaned_data['license_name'] = 'CC %s %s' % (m.group(1).upper(), m.group(2))
87 except AssertionError:
88 raise forms.ValidationError('Error reading license name.')
90 m = re.search(r'"ownername":"([^"]*)', html)
92 self.cleaned_data['author'] = "%s@Flickr" % m.group(1)
94 raise forms.ValidationError('Error reading author name.')
96 m = re.search(r'<h1[^>]*>(.*?)</h1>', html)
98 raise forms.ValidationError('Error reading image title.')
99 self.cleaned_data['title'] = m.group(1)
101 url_size = base_url + "sizes/o/"
102 html = normalize_html(urlopen(url_size).read().decode('utf-8'))
103 m = re.search(r'<div id="allsizes-photo">\s*<img src="([^"]*)"', html)
105 self.cleaned_data['download_url'] = m.group(1)
107 raise forms.ValidationError('Error reading image URL.')