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.
8 from urllib2 import urlopen
9 from django import forms
10 from django.utils.translation import ugettext_lazy as _, ugettext
11 from cover.models import Image
12 from django.utils.text import mark_safe
14 class ImageAddForm(forms.ModelForm):
18 def __init__(self, *args, **kwargs):
19 super(ImageAddForm, self).__init__(*args, **kwargs)
20 self.fields['file'].required = False
22 def clean_download_url(self):
23 cl = self.cleaned_data['download_url'] or None
26 img = Image.objects.get(download_url=cl)
27 except Image.DoesNotExist:
30 raise forms.ValidationError(mark_safe(
31 ugettext('Image <a href="%(url)s">already in repository</a>.'
32 ) % {'url': img.get_absolute_url()}))
36 cleaned_data = super(ImageAddForm, self).clean()
37 if not cleaned_data.get('download_url', None) and not cleaned_data.get('file', None):
38 raise forms.ValidationError('No image specified')
41 class ImageEditForm(forms.ModelForm):
42 """Form used for editing a Book."""
45 exclude = ['download_url']
48 class ReadonlyImageEditForm(ImageEditForm):
49 """Form used for not editing an Image."""
51 def __init__(self, *args, **kwargs):
52 ret = super(ReadonlyImageEditForm, self).__init__(*args, **kwargs)
53 for field in self.fields.values():
54 field.widget.attrs.update({"readonly": True})
57 def save(self, *args, **kwargs):
58 raise AssertionError, "ReadonlyImageEditForm should not be saved."
61 class FlickrForm(forms.Form):
62 source_url = forms.URLField(label=_('Flickr URL'))
64 def clean_source_url(self):
65 def normalize_html(html):
67 return re.sub('[\t\n]', '', html)
69 url = self.cleaned_data['source_url']
70 m = re.match(r'(https?://)?(www\.|secure\.)?flickr\.com/photos/(?P<author>[^/]+)/(?P<img>\d+)/?', url)
72 raise forms.ValidationError("It doesn't look like Flickr URL.")
73 author_slug, img_id = m.group('author'), m.group('img')
74 base_url = "https://www.flickr.com/photos/%s/%s/" % (author_slug, img_id)
77 html = normalize_html(urlopen(url).read().decode('utf-8'))
79 raise forms.ValidationError('Error reading page.')
80 match = re.search(r'<a href="([^"]*)"[^>]* rel="license ', html)
83 license_url = match.group(1)
84 self.cleaned_data['license_url'] = license_url
85 re_license = re.compile(r'https?://creativecommons.org/licenses/([^/]*)/([^/]*)/.*')
86 m = re_license.match(license_url)
88 self.cleaned_data['license_name'] = 'CC %s %s' % (m.group(1).upper(), m.group(2))
89 except AssertionError:
90 raise forms.ValidationError('Error reading license name.')
92 m = re.search(r'<a[^>]* class="owner-name [^>]*>([^<]*)<', html)
94 self.cleaned_data['author'] = "%s@Flickr" % m.group(1)
96 raise forms.ValidationError('Error reading author name.')
98 m = re.search(r'<h1[^>]*>(.*?)</h1>', html, re.S)
100 raise forms.ValidationError('Error reading image title.')
101 self.cleaned_data['title'] = m.group(1).strip()
103 m = re.search(r'modelExport: (\{.*\})', html)
106 self.cleaned_data['download_url'] = 'https:' + json.loads(m.group(1))['photo-models'][0]['sizes']['o']['url']
107 except (AssertionError, ValueError, IndexError, KeyError):
108 raise forms.ValidationError('Error reading image URL.')