f49f4f54c0db4fadd3189cf03dff2ec8a4ddc39c
[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 re
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
12
13 class ImageAddForm(forms.ModelForm):
14     class Meta:
15         model = Image
16
17     def __init__(self, *args, **kwargs):
18         super(ImageAddForm, self).__init__(*args, **kwargs)
19         self.fields['file'].required = False
20
21     def clean_download_url(self):
22         cl = self.cleaned_data['download_url'] or None
23         if cl is not None:
24             try:
25                 img = Image.objects.get(download_url=cl)
26             except Image.DoesNotExist:
27                 pass
28             else:
29                 raise forms.ValidationError(mark_safe(
30                     ugettext('Image <a href="%(url)s">already in repository</a>.'
31                         ) % {'url': img.get_absolute_url()}))
32         return cl
33
34     def clean(self):
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')
38         return cleaned_data
39
40 class ImageEditForm(forms.ModelForm):
41     """Form used for editing a Book."""
42     class Meta:
43         model = Image
44         exclude = ['download_url']
45
46
47 class ReadonlyImageEditForm(ImageEditForm):
48     """Form used for not editing an Image."""
49
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})
54         return ret
55
56     def save(self, *args, **kwargs):
57         raise AssertionError, "ReadonlyImageEditForm should not be saved."
58
59
60 class FlickrForm(forms.Form):
61     source_url = forms.URLField(label=_('Flickr URL'))
62
63     def clean_source_url(self):
64         def normalize_html(html):
65             return re.sub('[\t\n]', '', html)
66     
67         url = self.cleaned_data['source_url']
68         m = re.match(r'(https?://)?(www\.|secure\.)?flickr\.com/photos/(?P<author>[^/]+)/(?P<img>\d+)/?', url)
69         if not m:
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)
73
74         try:
75             html = normalize_html(urlopen(url).read().decode('utf-8'))
76         except:
77             raise forms.ValidationError('Error reading page.')
78         match = re.search(r'<a href="([^"]*)" rel="license cc:license">Some rights reserved</a>', html)
79         try:
80             assert match
81             license_url = match.group(1)
82             self.cleaned_data['license_url'] = license_url
83             re_license = re.compile(r'http://creativecommons.org/licenses/([^/]*)/([^/]*)/.*')
84             m = re_license.match(license_url)
85             assert m
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.')
89
90         m = re.search(r'"ownername":"([^"]*)', html)
91         if m:
92             self.cleaned_data['author'] = "%s@Flickr" % m.group(1)
93         else:
94             raise forms.ValidationError('Error reading author name.')
95
96         m = re.search(r'<h1[^>]*>(.*?)</h1>', html)
97         if not m:
98             raise forms.ValidationError('Error reading image title.')
99         self.cleaned_data['title'] = m.group(1)
100
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)
104         if m:
105             self.cleaned_data['download_url'] = m.group(1)
106         else:
107             raise forms.ValidationError('Error reading image URL.')
108         return base_url