fix
[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 build_opener, install_opener, urlopen
9 from django.conf import settings
10 import requests
11 from wikidata.client import Client
12 from catalogue.constants import WIKIDATA
13
14
15 opener = build_opener()
16 opener.addheaders = [("User-Agent", "WolneLektury-Redakcja/1.0 (fundacja@wolnelektury.pl)")]
17 install_opener(opener)
18
19
20 class FlickrError(Exception):
21     pass
22
23
24 def get_flickr_data(url):
25     m = re.match(r'(https?://)?(www\.|secure\.)?flickr\.com/photos/(?P<author>[^/]+)/(?P<img>\d+)/?', url)
26     if not m:
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)
30     try:
31         html = urlopen(url).read().decode('utf-8')
32     except IOError:
33         raise FlickrError('Error reading page')
34     match = re.search(r'<a href="([^"]*)"[^>]* rel="license ', html)
35     if not match:
36         raise FlickrError('License not found.')
37     else:
38         license_url = match.group(1)
39         re_license = re.compile(r'https?://creativecommons.org/licenses/([^/]*)/([^/]*)/.*')
40         m = re_license.match(license_url)
41         if not m:
42             re_pd = re.compile(r'https?://creativecommons.org/publicdomain/([^/]*)/([^/]*)/.*')
43             m = re_pd.match(license_url)
44             if not m:
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)
48             else:
49                 license_name = 'Public domain'
50         else:
51             license_name = 'CC %s %s' % (m.group(1).upper(), m.group(2))
52     m = re.search(r'<a[^>]* class="owner-name [^>]*>([^<]*)<', html)
53     if m:
54         author = "%s@Flickr" % m.group(1)
55     else:
56         raise FlickrError('Error reading author name.')
57     m = re.search(r'<h1[^>]*>(.*?)</h1>', html, re.S)
58     if not m:
59         raise FlickrError('Error reading image title.')
60     title = m.group(1).strip()
61     m = re.search(r'modelExport: (\{.*\})', html)
62     try:
63         assert m
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.')
67     return {
68         'source_url': base_url,
69         'license_url': license_url,
70         'license_name': license_name,
71         'author': author,
72         'title': title,
73         'download_url': download_url,
74     }
75
76
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'))
80
81     d = list(d['query']['pages'].values())[0]['imageinfo'][0]
82     ext = d['extmetadata']
83
84     meta = {
85         'title': ext['ObjectName']['value'],
86         'author': d['user'],
87         'source_url': d['descriptionurl'],
88         'download_url': d['url'],
89         'license_url': ext.get('LicenseUrl', {}).get('value', ''),
90         'license_name': ext['LicenseShortName']['value'],
91     }
92
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)
97         client = Client()
98         client.opener.addheaders = [(
99             'User-Agent', 'Wolne Lektury Redakcja / Python-wikidata'
100         )]
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))
106         else:
107             meta['author'] = ''
108
109     if meta['license_name'] == 'Public domain':
110         meta['license_name'] = 'domena publiczna'
111         meta['license_url'] = 'https://pl.wikipedia.org/wiki/Domena_publiczna'
112
113
114     return meta
115
116
117 def get_mnw_data(url):
118     nr = url.rsplit('/', 1)[-1]
119     d = list(
120         csv.DictReader(
121             StringIO(
122                 urlopen(
123                     'https://cyfrowe-api.mnw.art.pl/api/object/{}/csv'.format(nr)
124                 ).read().decode('utf-8')
125             )
126         )
127     )[0]
128
129     authors = []
130     i = 1
131     while f'twórca/wytwórnia {i}' in d:
132         authors.append(d[f'twórca/wytwórnia {i}'])
133         i += 1
134
135     license_url = ''
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'
140         
141     return {
142         'title': d['nazwa/tytuł'],
143         'author': ', '.join(authors),
144         'source_url': url,
145         'download_url': 'https://cyfrowe-cdn.mnw.art.pl/upload/multimedia/{}.{}'.format(
146             d['ścieżka wizerunku'],
147             d['rozszerzenie pliku wizerunku'],
148         ),
149         'license_url': license_url,
150         'license_name': license_name,
151     }
152
153 def get_rawpixel_data(url):
154     photo_id = re.search(r'/(\d+)/', url).group(1)
155
156     s = requests.Session()
157     cookies = settings.RAWPIXEL_SESSION
158
159     token = s.post(
160             'https://www.rawpixel.com/api/v1/user/session',
161             cookies=cookies
162             ).json()['token']
163
164     h = {'X-CSRF-Token': token, 'Accept': 'application/json'}
165
166     data = s.get(
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']
173
174     title = data['metadata']['title'].rsplit('|', 1)[0].strip()
175
176     return {
177         'title': title,
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'],
183     }
184
185
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)