cover image repo
[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 cover.models import Image
10
11 class ImageAddForm(forms.ModelForm):
12     class Meta:
13         model = Image
14
15 class ImageEditForm(forms.ModelForm):
16     """Form used for editing a Book."""
17     class Meta:
18         model = Image
19         exclude = ['download_url']
20
21
22 class ReadonlyImageEditForm(ImageEditForm):
23     """Form used for not editing a Book."""
24
25     def __init__(self, *args, **kwargs):
26         ret = super(ReadonlyImageEditForm, self).__init__(*args, **kwargs)
27         for field in self.fields.values():
28             field.widget.attrs.update({"readonly": True})
29         return ret
30
31     def save(self, *args, **kwargs):
32         raise AssertionError, "ReadonlyImageEditForm should not be saved."
33
34
35 class FlickrForm(forms.Form):
36     source_url = forms.URLField()
37
38     def clean_source_url(self):
39         url = self.cleaned_data['source_url']
40         m = re.match(r'(https?://)?(www.)?flickr.com/photos/(?P<author>[^/]+)/(?P<img>\d+)', url)
41         if not m:
42             raise forms.ValidationError("It doesn't look like Flickr URL.")
43         author_slug, img_id = m.group('author'), m.group('img')
44         base_url = "https://www.flickr.com/photos/%s/%s/" % (author_slug, img_id)
45
46         try:
47             html = urlopen(url).read().decode('utf-8')
48         except:
49             raise forms.ValidationError('Error reading page.')
50         match = re.search(r'<a href="([^"]*)" rel="license cc:license">Some rights reserved</a>', html)
51         try:
52             assert match
53             license_url = match.group(1)
54             self.cleaned_data['license_url'] = license_url
55             re_license = re.compile(r'http://creativecommons.org/licenses/([^/]*)/([^/]*)/.*')
56             m = re_license.match(license_url)
57             assert m
58             self.cleaned_data['license_name'] = 'CC %s %s' % (m.group(1).upper(), m.group(2))
59         except AssertionError:
60             raise forms.ValidationError('Error reading license name.')
61
62         m = re.search(r'<strong class="username">By <a href="[^"]*">([^<]*)</a></strong>', html)
63         if m:
64             self.cleaned_data['author'] = "%s@Flickr" % m.group(1)
65         else:
66             raise forms.ValidationError('Error reading author name.')
67
68         m = re.search(r'<h1[^>]*>(.*?)</h1>', html)
69         if not m:
70             raise forms.ValidationError('Error reading image title.')
71         self.cleaned_data['title'] = m.group(1)
72
73         url_size = base_url + "sizes/o/"
74         html = urlopen(url_size).read().decode('utf-8')
75         m = re.search(r'<div id="allsizes-photo">\s*<img src="([^"]*)"', html)
76         if m:
77             self.cleaned_data['download_url'] = m.group(1)
78         else:
79             raise forms.ValidationError('Error reading image URL.')
80         return base_url