1 # -*- coding: utf-8 -*-
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.
8 from urllib import FancyURLopener
10 from django.contrib.sites.models import Site
13 class URLOpener(FancyURLopener):
16 return 'FNP Redakcja (http://%s)' % Site.objects.get_current()
19 class FlickrError(Exception):
23 def get_flickr_data(url):
24 m = re.match(r'(https?://)?(www\.|secure\.)?flickr\.com/photos/(?P<author>[^/]+)/(?P<img>\d+)/?', url)
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)
30 html = URLOpener().open(url).read().decode('utf-8')
32 raise FlickrError('Error reading page')
33 match = re.search(r'<a href="([^"]*)"[^>]* rel="license ', html)
35 raise FlickrError('License not found.')
37 license_url = match.group(1)
38 re_license = re.compile(r'https?://creativecommons.org/licenses/([^/]*)/([^/]*)/.*')
39 m = re_license.match(license_url)
41 re_pd = re.compile(r'https?://creativecommons.org/publicdomain/([^/]*)/([^/]*)/.*')
42 m = re_pd.match(license_url)
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)
48 license_name = 'Public domain'
50 license_name = 'CC %s %s' % (m.group(1).upper(), m.group(2))
51 m = re.search(r'<a[^>]* class="owner-name [^>]*>([^<]*)<', html)
53 author = "%s@Flickr" % m.group(1)
55 raise FlickrError('Error reading author name.')
56 m = re.search(r'<h1[^>]*>(.*?)</h1>', html, re.S)
58 raise FlickrError('Error reading image title.')
59 title = m.group(1).strip()
60 m = re.search(r'modelExport: (\{.*\})', html)
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.')
67 'source_url': base_url,
68 'license_url': license_url,
69 'license_name': license_name,
72 'download_url': download_url,