fix
[redakcja.git] / src / catalogue / wikimedia.py
1 from urllib.parse import unquote
2 from urllib.request import urlopen
3 from django.core.files.base import ContentFile
4 from cover.utils import get_wikimedia_data
5
6
7 class WikiMedia:
8     def get_description_url(imgdata):
9         if imgdata is None:
10             return None
11         return imgdata.attributes['imageinfo'][0]['descriptionurl']
12
13     @classmethod
14     def descriptionurl(cls, arg):
15         def transform(get_value):
16             value = get_value(arg)
17             if value is None:
18                 return None
19             return cls.get_description_url(value)
20         return transform
21
22     @classmethod
23     def attribution(cls, arg):
24         def transform(get_value):
25             value = get_value(arg)
26             if value is None:
27                 return None
28             media_data = get_wikimedia_data(
29                 cls.get_description_url(value)
30             )
31             parts = [
32                 media_data['title'],
33                 media_data['author'],
34                 media_data['license_name'],
35             ]
36             parts = [p for p in parts if p]
37             attribution = ', '.join(parts)
38             return attribution
39         return transform
40
41     @classmethod
42     def download(cls, arg):
43         def transform(get_value):
44             value = get_value(arg)
45             if value is None:
46                 return None
47             media_data = get_wikimedia_data(
48                 cls.get_description_url(value)
49             )
50             download_url = media_data['download_url']
51             return Downloadable(download_url)
52         return transform
53
54     @classmethod
55     def append(cls, arg):
56         def transform(get_value):
57             value = get_value(arg)
58             return Appendable(value)
59         return transform
60
61
62 class Appendable(str):
63     def as_hint_json(self):
64         return {
65             'value': self,
66             'action': 'append',
67         }
68     
69 class Downloadable:
70     def __init__(self, url):
71         self.url = url
72
73     def apply_to_field(self, obj, attname):
74         t = urlopen(self.url).read()
75         getattr(obj, attname).save(
76             unquote(self.url.rsplit('/', 1)[-1]),
77             ContentFile(t),
78             save=False
79         )
80
81     def as_hint_json(self):
82         return {
83             'download': self.url,
84             'img': self.url,
85         }