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.
 
   6 from urllib.request import FancyURLopener
 
   8 from django.contrib.sites.models import Site
 
  11 class URLOpener(FancyURLopener):
 
  14         return 'FNP Redakcja (http://%s)' % Site.objects.get_current()
 
  17 class FlickrError(Exception):
 
  21 def get_flickr_data(url):
 
  22     m = re.match(r'(https?://)?(www\.|secure\.)?flickr\.com/photos/(?P<author>[^/]+)/(?P<img>\d+)/?', url)
 
  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)
 
  28         html = URLOpener().open(url).read().decode('utf-8')
 
  30         raise FlickrError('Error reading page')
 
  31     match = re.search(r'<a href="([^"]*)"[^>]* rel="license ', html)
 
  33         raise FlickrError('License not found.')
 
  35         license_url = match.group(1)
 
  36         re_license = re.compile(r'https?://creativecommons.org/licenses/([^/]*)/([^/]*)/.*')
 
  37         m = re_license.match(license_url)
 
  39             re_pd = re.compile(r'https?://creativecommons.org/publicdomain/([^/]*)/([^/]*)/.*')
 
  40             m = re_pd.match(license_url)
 
  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)
 
  46                 license_name = 'Public domain'
 
  48             license_name = 'CC %s %s' % (m.group(1).upper(), m.group(2))
 
  49     m = re.search(r'<a[^>]* class="owner-name [^>]*>([^<]*)<', html)
 
  51         author = "%s@Flickr" % m.group(1)
 
  53         raise FlickrError('Error reading author name.')
 
  54     m = re.search(r'<h1[^>]*>(.*?)</h1>', html, re.S)
 
  56         raise FlickrError('Error reading image title.')
 
  57     title = m.group(1).strip()
 
  58     m = re.search(r'modelExport: (\{.*\})', html)
 
  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.')
 
  65         'source_url': base_url,
 
  66         'license_url': license_url,
 
  67         'license_name': license_name,
 
  70         'download_url': download_url,