Quotes API
[wolnelektury.git] / src / references / models.py
index d4733ff..fb249e1 100644 (file)
@@ -31,10 +31,13 @@ class Entity(models.Model):
 
     def populate_from_wikidata(self, wikidata_id):
         client = Client()
+        client.opener.addheaders = [(
+            'User-Agent', 'Wolne Lektury / https://wolnelektury.pl / Python-wikidata'
+        )]
         entity = client.get(wikidata_id)
 
-        self.label = entity.label.get('pl', entity.label) or ''
-        self.description = entity.description.get('pl', entity.description) or ''
+        self.label = entity.label.get('pl', entity.label.get('mul', entity.label)) or ''
+        self.description = entity.description.get('pl', entity.description.get('mul', entity.description)) or ''
         sitelinks = entity.attributes.get('sitelinks', {})
         self.wikipedia_link = sitelinks.get('plwiki', sitelinks.get('enwiki', {})).get('url') or ''
 
@@ -72,6 +75,51 @@ class Entity(models.Model):
 
         self.images = json.dumps(image_data_list)
 
+    def get_images(self):
+        return json.loads(self.images)
+
+    def get_pretty_coords(self):
+        def to_minutes(n):
+            coo = []
+            coo.append(int(n))
+            n -= coo[-1]
+            n *= 60
+            coo.append(int(n))
+            n -= coo[-1]
+            n *= 60
+            coo.append(n)
+            return coo
+
+        if not self.lat or not self.lon:
+            return ''
+
+        lat, latm, lon, lonm = self.lat, 'N', self.lon, 'E'
+        if lat < 0:
+            latm = 'S'
+            lat = -lat
+        if lon < 0:
+            lonm = 'W'
+            lon = -lon
+        
+        return '%d°%d\'%d"%s %d°%d\'%d"%s' % (
+            *to_minutes(lat),
+            latm,
+            *to_minutes(lon),
+            lonm,
+        )
+
+    def get_json(self):
+        data = {
+            "id": self.id,
+            "images": self.get_images(),
+            "label": self.label,
+            "description": self.description,
+            "wikipedia_link": self.wikipedia_link,
+        }
+        if self.lat and self.lon:
+            data['location'] = [self.lat, self.lon]
+        return json.dumps(data)
+    
 
 class Reference(models.Model):
     book = models.ForeignKey('catalogue.Book', models.CASCADE)