Covers from MPW, Rawpixel.
[redakcja.git] / src / cover / utils.py
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.
3 #
4 import csv
5 from io import StringIO
6 import json
7 import re
8 from urllib.request import FancyURLopener
9 from django.conf import settings
10 import requests
11 from wikidata.client import Client
12 from catalogue.constants import WIKIDATA
13
14
15 class URLOpener(FancyURLopener):
16     @property
17     def version(self):
18         return 'FNP Redakcja'
19
20
21 class FlickrError(Exception):
22     pass
23
24
25 def get_flickr_data(url):
26     m = re.match(r'(https?://)?(www\.|secure\.)?flickr\.com/photos/(?P<author>[^/]+)/(?P<img>\d+)/?', url)
27     if not m:
28         raise FlickrError("It doesn't look like Flickr URL.")
29     author_slug, img_id = m.group('author'), m.group('img')
30     base_url = "https://www.flickr.com/photos/%s/%s/" % (author_slug, img_id)
31     try:
32         html = URLOpener().open(url).read().decode('utf-8')
33     except IOError:
34         raise FlickrError('Error reading page')
35     match = re.search(r'<a href="([^"]*)"[^>]* rel="license ', html)
36     if not match:
37         raise FlickrError('License not found.')
38     else:
39         license_url = match.group(1)
40         re_license = re.compile(r'https?://creativecommons.org/licenses/([^/]*)/([^/]*)/.*')
41         m = re_license.match(license_url)
42         if not m:
43             re_pd = re.compile(r'https?://creativecommons.org/publicdomain/([^/]*)/([^/]*)/.*')
44             m = re_pd.match(license_url)
45             if not m:
46                 raise FlickrError('License does not look like CC: %s' % license_url)
47             if m.group(1).lower() == 'zero':
48                 license_name = 'Public domain (CC0 %s)' % m.group(2)
49             else:
50                 license_name = 'Public domain'
51         else:
52             license_name = 'CC %s %s' % (m.group(1).upper(), m.group(2))
53     m = re.search(r'<a[^>]* class="owner-name [^>]*>([^<]*)<', html)
54     if m:
55         author = "%s@Flickr" % m.group(1)
56     else:
57         raise FlickrError('Error reading author name.')
58     m = re.search(r'<h1[^>]*>(.*?)</h1>', html, re.S)
59     if not m:
60         raise FlickrError('Error reading image title.')
61     title = m.group(1).strip()
62     m = re.search(r'modelExport: (\{.*\})', html)
63     try:
64         assert m
65         download_url = 'https:' + json.loads(m.group(1))['main']['photo-models'][0]['sizes']['o']['url']
66     except (AssertionError, ValueError, IndexError, KeyError):
67         raise FlickrError('Error reading image URL.')
68     return {
69         'source_url': base_url,
70         'license_url': license_url,
71         'license_name': license_name,
72         'author': author,
73         'title': title,
74         'download_url': download_url,
75     }
76
77
78 def get_wikimedia_data(url):
79     """
80     >>> get_wikimedia_data('https://commons.wikimedia.org/wiki/File:Valdai_IverskyMon_asv2018_img47.jpg')
81     {'title': 'Valdai IverskyMon asv2018 img47', 'author': 'A.Savin', 'source_url': 'https://commons.wikimedia.org/wiki/File:Valdai_IverskyMon_asv2018_img47.jpg', 'download_url': 'https://upload.wikimedia.org/wikipedia/commons/4/43/Valdai_IverskyMon_asv2018_img47.jpg', 'license_url': 'http://artlibre.org/licence/lal/en', 'license_name': 'FAL'}
82
83     >>> get_wikimedia_data('https://commons.wikimedia.org/wiki/File:Pymonenko_A_boy_in_a_straw_hat.jpg')
84     {'title': 'Chłopiec w słomkowym kapeluszu', 'author': 'Mykola Pymonenko', 'source_url': 'https://commons.wikimedia.org/wiki/File:Pymonenko_A_boy_in_a_straw_hat.jpg', 'download_url': 'https://upload.wikimedia.org/wikipedia/commons/9/9b/Pymonenko_A_boy_in_a_straw_hat.jpg', 'license_url': 'https://pl.wikipedia.org/wiki/Domena_publiczna', 'license_name': 'domena publiczna'}
85
86     """
87     file_name = url.rsplit('/', 1)[-1].rsplit(':', 1)[-1]
88     d = json.loads(URLOpener().open('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'))
89
90     d = list(d['query']['pages'].values())[0]['imageinfo'][0]
91     ext = d['extmetadata']
92
93     meta = {
94         'title': ext['ObjectName']['value'],
95         'author': d['user'],
96         'source_url': d['descriptionurl'],
97         'download_url': d['url'],
98         'license_url': ext.get('LicenseUrl', {}).get('value', ''),
99         'license_name': ext['LicenseShortName']['value'],
100     }
101
102     # There are Wikidata links in ObjectName sametimes. Let's use it.
103     wikidata_match = re.search(r'wikidata\.org/wiki/(Q\d+)', meta['title'])
104     if wikidata_match is not None:
105         qitem = wikidata_match.group(1)
106         client = Client()
107         entity = client.get(qitem)
108         meta['title'] = entity.label.get('pl', str(entity.label))
109         author = entity.get(client.get(WIKIDATA.CREATOR))
110         meta['author'] = author.label.get('pl', str(author.label))
111
112     if meta['license_name'] == 'Public domain':
113         meta['license_name'] = 'domena publiczna'
114         meta['license_url'] = 'https://pl.wikipedia.org/wiki/Domena_publiczna'
115
116
117     return meta
118
119
120 def get_mnw_data(url):
121     """
122     >>> get_mnw_data('https://cyfrowe.mnw.art.pl/pl/katalog/511078')
123     {'title': 'Chłopka (Baba ukraińska)', 'author': 'Krzyżanowski, Konrad (1872-1922)', 'source_url': 'https://cyfrowe.mnw.art.pl/pl/katalog/511078', 'download_url': 'https://cyfrowe-cdn.mnw.art.pl/upload/multimedia/a0/68/a0681c60f203d907d9c45050d245c921.jpg', 'license_url': 'https://pl.wikipedia.org/wiki/Domena_publiczna', 'license_name': 'domena publiczna'}
124     """
125     nr = url.rsplit('/', 1)[-1]
126     d = list(
127         csv.DictReader(
128             StringIO(
129                 URLOpener().open(
130                     'https://cyfrowe-api.mnw.art.pl/api/object/{}/csv'.format(nr)
131                 ).read().decode('utf-8')
132             )
133         )
134     )[0]
135
136     authors = []
137     i = 1
138     while f'twórca/wytwórnia {i}' in d:
139         authors.append(d[f'twórca/wytwórnia {i}'])
140         i += 1
141
142     license_url = ''
143     license_name = d['klasyfikacja praw autorskich 1']
144     if license_name == 'DOMENA PUBLICZNA':
145         license_name = 'domena publiczna'
146         license_url = 'https://pl.wikipedia.org/wiki/Domena_publiczna'
147         
148     return {
149         'title': d['nazwa/tytuł'],
150         'author': ', '.join(authors),
151         'source_url': url,
152         'download_url': 'https://cyfrowe-cdn.mnw.art.pl/upload/multimedia/{}.{}'.format(
153             d['ścieżka wizerunku'],
154             d['rozszerzenie pliku wizerunku'],
155         ),
156         'license_url': license_url,
157         'license_name': license_name,
158     }
159
160 def get_rawpixel_data(url):
161     photo_id = re.search(r'/(\d+)/', url).group(1)
162
163     s = requests.Session()
164     cookies = settings.RAWPIXEL_SESSION
165
166     token = s.post(
167             'https://www.rawpixel.com/api/v1/user/session',
168             cookies=cookies
169             ).json()['token']
170
171     h = {'X-CSRF-Token': token, 'Accept': 'application/json'}
172
173     data = s.get(
174         f'https://www.rawpixel.com/api/v1/image/data/{photo_id}',
175         headers=h, cookies=cookies).json()
176     download_url = s.post(
177         f'https://www.rawpixel.com/api/v1/image/download/{photo_id}/original',
178         headers=h, cookies=cookies
179     ).json()['downloadUrl']
180
181     title = data['metadata']['title'].rsplit('|', 1)[0].strip()
182
183     return {
184         'title': title,
185         'author': ', '.join(data['metadata']['artist_names']),
186         'source_url': data['url'],
187         'download_url': download_url,
188         'license_url': data['metadata']['licenseUrl'],
189         'license_name': data['metadata']['license'],
190     }
191
192
193 def get_import_data(url):
194     if re.match(r'(https?://)?(www\.|secure\.)?flickr\.com/', url):
195         return get_flickr_data(url)
196     if re.match(r'(https?://)?(commons|upload)\.wikimedia\.org/', url):
197         return get_wikimedia_data(url)
198     if re.match(r'(https?://)?cyfrowe\.mnw\.art\.pl/', url):
199         return get_mnw_data(url)
200     if re.match(r'(https?://)?www\.rawpixel\.com/', url):
201         return get_rawpixel_data(url)