update
[redakcja.git] / src / catalogue / wikidata.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 from datetime import date
5 from django.db import models
6 from django.db.models.signals import m2m_changed
7 from django.utils.html import format_html
8 from django.utils.translation import gettext_lazy as _
9 from django.dispatch import receiver
10 from wikidata.client import Client
11 from wikidata.datavalue import DatavalueError
12
13
14 class WikidataMixin(models.Model):
15     wikidata = models.CharField(
16         max_length=255,
17         blank=True,
18         help_text=_('If you have a Wikidata ID, like "Q1337", enter it and save.'),
19     )
20
21     class Meta:
22         abstract = True
23
24     def save(self, **kwargs):
25         super().save()
26         if self.wikidata and hasattr(self, "Wikidata"):
27             Wikidata = type(self).Wikidata
28             client = Client()
29             # Probably should getlist
30             entity = client.get(self.wikidata)
31             for attname in dir(Wikidata):
32                 if attname.startswith("_"):
33                     continue
34                 wd = getattr(Wikidata, attname)
35
36                 model_field = self._meta.get_field(attname)
37                 if isinstance(model_field, models.ManyToManyField):
38                     if getattr(self, attname).all().exists():
39                         continue
40                 else:
41                     if getattr(self, attname):
42                         continue
43
44                 wdvalue = None
45                 if wd == "description":
46                     wdvalue = entity.description.get("pl", str(entity.description))
47                 elif wd == "label":
48                     wdvalue = entity.label.get("pl", str(entity.label))
49                 else:
50                     try:
51                         wdvalue = entity.get(client.get(wd))
52                     except DatavalueError:
53                         pass
54
55                 self.set_field_from_wikidata(attname, wdvalue)
56
57         kwargs.update(force_insert=False, force_update=True)
58         super().save(**kwargs)
59
60     def set_field_from_wikidata(self, attname, wdvalue):
61         if not wdvalue:
62             return
63         # Find out what this model field is
64         model_field = self._meta.get_field(attname)
65         if isinstance(model_field, models.ForeignKey):
66             rel_model = model_field.related_model
67             if issubclass(rel_model, WikidataMixin):
68                 # welp, we can try and find by WD identifier.
69                 wdvalue, created = rel_model.objects.get_or_create(wikidata=wdvalue.id)
70                 setattr(self, attname, wdvalue)
71         elif isinstance(model_field, models.ManyToManyField):
72             rel_model = model_field.related_model
73             if issubclass(rel_model, WikidataMixin):
74                 wdvalue, created = rel_model.objects.get_or_create(wikidata=wdvalue.id)
75                 getattr(self, attname).set([wdvalue])
76         else:
77             # How to get original title?
78             if isinstance(wdvalue, date):
79                 if isinstance(model_field, models.IntegerField):
80                     wdvalue = wdvalue.year
81             elif not isinstance(wdvalue, str):
82                 wdvalue = wdvalue.label.get("pl", str(wdvalue.label))
83             setattr(self, attname, wdvalue)
84
85     def wikidata_link(self):
86         if self.wikidata:
87             return format_html(
88                 '<a href="https://www.wikidata.org/wiki/{wd}" target="_blank">{wd}</a>',
89                 wd=self.wikidata,
90             )
91         else:
92             return ""
93
94     wikidata_link.admin_order_field = "wikidata"
95
96
97 class WikidataAdminMixin:
98     def save_related(self, request, form, formsets, change):
99         super().save_related(request, form, formsets, change)
100         form.instance.save()