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.
5 from io import StringIO
8 from urllib.request import build_opener, install_opener, urlopen
9 from django.conf import settings
11 from wikidata.client import Client
12 from catalogue.constants import WIKIDATA
15 opener = build_opener()
16 opener.addheaders = [("User-Agent", "WolneLektury-Redakcja/1.0 (fundacja@wolnelektury.pl)")]
17 install_opener(opener)
20 class FlickrError(Exception):
24 def get_flickr_data(url):
25 m = re.match(r'(https?://)?(www\.|secure\.)?flickr\.com/photos/(?P<author>[^/]+)/(?P<img>\d+)/?', url)
27 raise FlickrError("It doesn't look like Flickr URL.")
28 author_slug, img_id = m.group('author'), m.group('img')
29 base_url = "https://www.flickr.com/photos/%s/%s/" % (author_slug, img_id)
31 html = urlopen(url).read().decode('utf-8')
33 raise FlickrError('Error reading page')
34 match = re.search(r'<a href="([^"]*)"[^>]* rel="license ', html)
36 raise FlickrError('License not found.')
38 license_url = match.group(1)
39 re_license = re.compile(r'https?://creativecommons.org/licenses/([^/]*)/([^/]*)/.*')
40 m = re_license.match(license_url)
42 re_pd = re.compile(r'https?://creativecommons.org/publicdomain/([^/]*)/([^/]*)/.*')
43 m = re_pd.match(license_url)
45 raise FlickrError('License does not look like CC: %s' % license_url)
46 if m.group(1).lower() == 'zero':
47 license_name = 'Public domain (CC0 %s)' % m.group(2)
49 license_name = 'Public domain'
51 license_name = 'CC %s %s' % (m.group(1).upper(), m.group(2))
52 m = re.search(r'<a[^>]* class="owner-name [^>]*>([^<]*)<', html)
54 author = "%s@Flickr" % m.group(1)
56 raise FlickrError('Error reading author name.')
57 m = re.search(r'<h1[^>]*>(.*?)</h1>', html, re.S)
59 raise FlickrError('Error reading image title.')
60 title = m.group(1).strip()
61 m = re.search(r'modelExport: (\{.*\})', html)
64 download_url = 'https:' + json.loads(m.group(1))['main']['photo-models'][0]['data']['sizes']['data']['o']['data']['url']
65 except (AssertionError, ValueError, IndexError, KeyError):
66 raise FlickrError('Error reading image URL.')
68 'source_url': base_url,
69 'license_url': license_url,
70 'license_name': license_name,
73 'download_url': download_url,
77 def get_wikimedia_data(url):
78 file_name = url.rsplit('/', 1)[-1].rsplit(':', 1)[-1]
79 d = json.loads(urlopen('https://commons.wikimedia.org/w/api.php?action=query&titles=File:{}&prop=imageinfo&iiprop=url|user|extmetadata&iimetadataversion=latest&format=json'.format(file_name)).read().decode('utf-8'))
81 d = list(d['query']['pages'].values())[0]['imageinfo'][0]
82 ext = d['extmetadata']
85 'title': ext['ObjectName']['value'],
87 'source_url': d['descriptionurl'],
88 'download_url': d['url'],
89 'license_url': ext.get('LicenseUrl', {}).get('value', ''),
90 'license_name': ext['LicenseShortName']['value'],
93 # There are Wikidata links in ObjectName sametimes. Let's use it.
94 wikidata_match = re.search(r'wikidata\.org/wiki/(Q\d+)', meta['title'])
95 if wikidata_match is not None:
96 qitem = wikidata_match.group(1)
98 client.opener.addheaders = [(
99 'User-Agent', 'Wolne Lektury Redakcja / Python-wikidata'
101 entity = client.get(qitem)
102 meta['title'] = entity.label.get('pl', str(entity.label))
103 author = entity.get(client.get(WIKIDATA.CREATOR))
104 if author is not None:
105 meta['author'] = author.label.get('pl', str(author.label))
109 if meta['license_name'] == 'Public domain':
110 meta['license_name'] = 'domena publiczna'
111 meta['license_url'] = 'https://pl.wikipedia.org/wiki/Domena_publiczna'
117 def get_mnw_data(url):
118 nr = url.rsplit('/', 1)[-1]
123 'https://cyfrowe-api.mnw.art.pl/api/object/{}/csv'.format(nr)
124 ).read().decode('utf-8')
131 while f'twórca/wytwórnia {i}' in d:
132 authors.append(d[f'twórca/wytwórnia {i}'])
136 license_name = d['klasyfikacja praw autorskich 1']
137 if license_name == 'DOMENA PUBLICZNA':
138 license_name = 'domena publiczna'
139 license_url = 'https://pl.wikipedia.org/wiki/Domena_publiczna'
142 'title': d['nazwa/tytuł'],
143 'author': ', '.join(authors),
145 'download_url': 'https://cyfrowe-cdn.mnw.art.pl/upload/multimedia/{}.{}'.format(
146 d['ścieżka wizerunku'],
147 d['rozszerzenie pliku wizerunku'],
149 'license_url': license_url,
150 'license_name': license_name,
153 def get_rawpixel_data(url):
154 photo_id = re.search(r'/(\d+)/', url).group(1)
156 s = requests.Session()
157 cookies = settings.RAWPIXEL_SESSION
160 'https://www.rawpixel.com/api/v1/user/session',
164 h = {'X-CSRF-Token': token, 'Accept': 'application/json'}
167 f'https://www.rawpixel.com/api/v1/image/data/{photo_id}',
168 headers=h, cookies=cookies).json()
169 download_url = s.post(
170 f'https://www.rawpixel.com/api/v1/image/download/{photo_id}/original',
171 headers=h, cookies=cookies
172 ).json()['downloadUrl']
174 title = data['metadata']['title'].rsplit('|', 1)[0].strip()
178 'author': ', '.join(data['metadata']['artist_names']),
179 'source_url': data['url'],
180 'download_url': download_url,
181 'license_url': data['metadata']['licenseUrl'],
182 'license_name': data['metadata']['license'],
186 def get_import_data(url):
187 if re.match(r'(https?://)?(www\.|secure\.)?flickr\.com/', url):
188 return get_flickr_data(url)
189 if re.match(r'(https?://)?(commons|upload)\.wikimedia\.org/', url):
190 return get_wikimedia_data(url)
191 if re.match(r'(https?://)?cyfrowe\.mnw\.art\.pl/', url):
192 return get_mnw_data(url)
193 if re.match(r'(https?://)?www\.rawpixel\.com/', url):
194 return get_rawpixel_data(url)