Tests.
[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     file_name = url.rsplit('/', 1)[-1].rsplit(':', 1)[-1]
80     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'))
81
82     d = list(d['query']['pages'].values())[0]['imageinfo'][0]
83     ext = d['extmetadata']
84
85     meta = {
86         'title': ext['ObjectName']['value'],
87         'author': d['user'],
88         'source_url': d['descriptionurl'],
89         'download_url': d['url'],
90         'license_url': ext.get('LicenseUrl', {}).get('value', ''),
91         'license_name': ext['LicenseShortName']['value'],
92     }
93
94     # There are Wikidata links in ObjectName sametimes. Let's use it.
95     wikidata_match = re.search(r'wikidata\.org/wiki/(Q\d+)', meta['title'])
96     if wikidata_match is not None:
97         qitem = wikidata_match.group(1)
98         client = Client()
99         entity = client.get(qitem)
100         meta['title'] = entity.label.get('pl', str(entity.label))
101         author = entity.get(client.get(WIKIDATA.CREATOR))
102         meta['author'] = author.label.get('pl', str(author.label))
103
104     if meta['license_name'] == 'Public domain':
105         meta['license_name'] = 'domena publiczna'
106         meta['license_url'] = 'https://pl.wikipedia.org/wiki/Domena_publiczna'
107
108
109     return meta
110
111
112 def get_mnw_data(url):
113     nr = url.rsplit('/', 1)[-1]
114     d = list(
115         csv.DictReader(
116             StringIO(
117                 URLOpener().open(
118                     'https://cyfrowe-api.mnw.art.pl/api/object/{}/csv'.format(nr)
119                 ).read().decode('utf-8')
120             )
121         )
122     )[0]
123
124     authors = []
125     i = 1
126     while f'twórca/wytwórnia {i}' in d:
127         authors.append(d[f'twórca/wytwórnia {i}'])
128         i += 1
129
130     license_url = ''
131     license_name = d['klasyfikacja praw autorskich 1']
132     if license_name == 'DOMENA PUBLICZNA':
133         license_name = 'domena publiczna'
134         license_url = 'https://pl.wikipedia.org/wiki/Domena_publiczna'
135         
136     return {
137         'title': d['nazwa/tytuł'],
138         'author': ', '.join(authors),
139         'source_url': url,
140         'download_url': 'https://cyfrowe-cdn.mnw.art.pl/upload/multimedia/{}.{}'.format(
141             d['ścieżka wizerunku'],
142             d['rozszerzenie pliku wizerunku'],
143         ),
144         'license_url': license_url,
145         'license_name': license_name,
146     }
147
148 def get_rawpixel_data(url):
149     photo_id = re.search(r'/(\d+)/', url).group(1)
150
151     s = requests.Session()
152     cookies = settings.RAWPIXEL_SESSION
153
154     token = s.post(
155             'https://www.rawpixel.com/api/v1/user/session',
156             cookies=cookies
157             ).json()['token']
158
159     h = {'X-CSRF-Token': token, 'Accept': 'application/json'}
160
161     data = s.get(
162         f'https://www.rawpixel.com/api/v1/image/data/{photo_id}',
163         headers=h, cookies=cookies).json()
164     download_url = s.post(
165         f'https://www.rawpixel.com/api/v1/image/download/{photo_id}/original',
166         headers=h, cookies=cookies
167     ).json()['downloadUrl']
168
169     title = data['metadata']['title'].rsplit('|', 1)[0].strip()
170
171     return {
172         'title': title,
173         'author': ', '.join(data['metadata']['artist_names']),
174         'source_url': data['url'],
175         'download_url': download_url,
176         'license_url': data['metadata']['licenseUrl'],
177         'license_name': data['metadata']['license'],
178     }
179
180
181 def get_import_data(url):
182     if re.match(r'(https?://)?(www\.|secure\.)?flickr\.com/', url):
183         return get_flickr_data(url)
184     if re.match(r'(https?://)?(commons|upload)\.wikimedia\.org/', url):
185         return get_wikimedia_data(url)
186     if re.match(r'(https?://)?cyfrowe\.mnw\.art\.pl/', url):
187         return get_mnw_data(url)
188     if re.match(r'(https?://)?www\.rawpixel\.com/', url):
189         return get_rawpixel_data(url)