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