e4c949c86d21e43502a2b22bae12726136aed092
[redakcja.git] / apps / cover / forms.py
1 # -*- coding: utf-8 -*-
2 #
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.
5 #
6 import json
7 import re
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
13
14 class ImageAddForm(forms.ModelForm):
15     class Meta:
16         model = Image
17
18     def __init__(self, *args, **kwargs):
19         super(ImageAddForm, self).__init__(*args, **kwargs)
20         self.fields['file'].required = False
21
22     def clean_download_url(self):
23         cl = self.cleaned_data['download_url'] or None
24         if cl is not None:
25             try:
26                 img = Image.objects.get(download_url=cl)
27             except Image.DoesNotExist:
28                 pass
29             else:
30                 raise forms.ValidationError(mark_safe(
31                     ugettext('Image <a href="%(url)s">already in repository</a>.'
32                         ) % {'url': img.get_absolute_url()}))
33         return cl
34
35     def clean(self):
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')
39         return cleaned_data
40
41 class ImageEditForm(forms.ModelForm):
42     """Form used for editing a Book."""
43     class Meta:
44         model = Image
45         exclude = ['download_url']
46
47
48 class ReadonlyImageEditForm(ImageEditForm):
49     """Form used for not editing an Image."""
50
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})
55         return ret
56
57     def save(self, *args, **kwargs):
58         raise AssertionError, "ReadonlyImageEditForm should not be saved."
59
60
61 class FlickrForm(forms.Form):
62     source_url = forms.URLField(label=_('Flickr URL'))
63
64     def clean_source_url(self):
65         def normalize_html(html):
66             return html
67             return re.sub('[\t\n]', '', html)
68     
69         url = self.cleaned_data['source_url']
70         m = re.match(r'(https?://)?(www\.|secure\.)?flickr\.com/photos/(?P<author>[^/]+)/(?P<img>\d+)/?', url)
71         if not m:
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)
75
76         try:
77             html = normalize_html(urlopen(url).read().decode('utf-8'))
78         except:
79             raise forms.ValidationError('Error reading page.')
80         match = re.search(r'<a href="([^"]*)"[^>]* rel="license ', html)
81         try:
82             assert match
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)
87             assert m
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.')
91
92         m = re.search(r'<a[^>]* class="owner-name [^>]*>([^<]*)<', html)
93         if m:
94             self.cleaned_data['author'] = "%s@Flickr" % m.group(1)
95         else:
96             raise forms.ValidationError('Error reading author name.')
97
98         m = re.search(r'<h1[^>]*>(.*?)</h1>', html, re.S)
99         if not m:
100             raise forms.ValidationError('Error reading image title.')
101         self.cleaned_data['title'] = m.group(1).strip()
102
103         m = re.search(r'modelExport: (\{.*\})', html)
104         try:
105             assert m
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.')
109         return base_url