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 raise FlickrError('License does not look like CC: %s' % license_url)
42 license_name = 'CC %s %s' % (m.group(1).upper(), m.group(2))
43 m = re.search(r'<a[^>]* class="owner-name [^>]*>([^<]*)<', html)
45 author = "%s@Flickr" % m.group(1)
47 raise FlickrError('Error reading author name.')
48 m = re.search(r'<h1[^>]*>(.*?)</h1>', html, re.S)
50 raise FlickrError('Error reading image title.')
51 title = m.group(1).strip()
52 m = re.search(r'modelExport: (\{.*\})', html)
55 download_url = 'https:' + json.loads(m.group(1))['photo-models'][0]['sizes']['o']['url']
56 except (AssertionError, ValueError, IndexError, KeyError):
57 raise FlickrError('Error reading image URL.')
59 'source_url': base_url,
60 'license_url': license_url,
61 'license_name': license_name,
64 'download_url': download_url,