Some housekeeping
[redakcja.git] / src / cover / utils.py
1 # This file is part of FNP-Redakcja, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
3 #
4 import json
5 import re
6 from urllib.request import FancyURLopener
7
8 from django.contrib.sites.models import Site
9
10
11 class URLOpener(FancyURLopener):
12     @property
13     def version(self):
14         return 'FNP Redakcja (http://%s)' % Site.objects.get_current()
15
16
17 class FlickrError(Exception):
18     pass
19
20
21 def get_flickr_data(url):
22     m = re.match(r'(https?://)?(www\.|secure\.)?flickr\.com/photos/(?P<author>[^/]+)/(?P<img>\d+)/?', url)
23     if not m:
24         raise FlickrError("It doesn't look like Flickr URL.")
25     author_slug, img_id = m.group('author'), m.group('img')
26     base_url = "https://www.flickr.com/photos/%s/%s/" % (author_slug, img_id)
27     try:
28         html = URLOpener().open(url).read().decode('utf-8')
29     except IOError:
30         raise FlickrError('Error reading page')
31     match = re.search(r'<a href="([^"]*)"[^>]* rel="license ', html)
32     if not match:
33         raise FlickrError('License not found.')
34     else:
35         license_url = match.group(1)
36         re_license = re.compile(r'https?://creativecommons.org/licenses/([^/]*)/([^/]*)/.*')
37         m = re_license.match(license_url)
38         if not m:
39             re_pd = re.compile(r'https?://creativecommons.org/publicdomain/([^/]*)/([^/]*)/.*')
40             m = re_pd.match(license_url)
41             if not m:
42                 raise FlickrError('License does not look like CC: %s' % license_url)
43             if m.group(1).lower() == 'zero':
44                 license_name = 'Public domain (CC0 %s)' % m.group(2)
45             else:
46                 license_name = 'Public domain'
47         else:
48             license_name = 'CC %s %s' % (m.group(1).upper(), m.group(2))
49     m = re.search(r'<a[^>]* class="owner-name [^>]*>([^<]*)<', html)
50     if m:
51         author = "%s@Flickr" % m.group(1)
52     else:
53         raise FlickrError('Error reading author name.')
54     m = re.search(r'<h1[^>]*>(.*?)</h1>', html, re.S)
55     if not m:
56         raise FlickrError('Error reading image title.')
57     title = m.group(1).strip()
58     m = re.search(r'modelExport: (\{.*\})', html)
59     try:
60         assert m
61         download_url = 'https:' + json.loads(m.group(1))['main']['photo-models'][0]['sizes']['o']['url']
62     except (AssertionError, ValueError, IndexError, KeyError):
63         raise FlickrError('Error reading image URL.')
64     return {
65         'source_url': base_url,
66         'license_url': license_url,
67         'license_name': license_name,
68         'author': author,
69         'title': title,
70         'download_url': download_url,
71     }