2020-07-18 22:21:57 +02:00
|
|
|
from urllib.parse import unquote
|
|
|
|
|
2020-07-28 18:25:56 +02:00
|
|
|
from django.core.exceptions import ValidationError
|
2020-06-01 11:03:21 +02:00
|
|
|
from django.db import models
|
|
|
|
from simple_history.models import HistoricalRecords
|
|
|
|
|
2020-07-18 21:59:42 +02:00
|
|
|
from acros.models import Acronym, WikipediaImage
|
2020-07-28 18:25:56 +02:00
|
|
|
from acros.utils.apis import WikipediaAPISummary, NotFoundError
|
2020-06-01 11:03:21 +02:00
|
|
|
|
|
|
|
|
|
|
|
class WikipediaLink(models.Model):
|
|
|
|
acronym = models.ForeignKey(Acronym, on_delete=models.CASCADE, related_name="wiki_articles")
|
|
|
|
title = models.CharField(max_length=200)
|
|
|
|
extract = models.TextField(blank=True)
|
|
|
|
extract_html = models.TextField(blank=True)
|
2020-07-27 21:01:40 +02:00
|
|
|
description = models.TextField(blank=True, null=True)
|
2020-07-18 21:59:42 +02:00
|
|
|
thumbnail = models.ForeignKey(WikipediaImage, on_delete=models.CASCADE, related_name="wiki_articles",
|
|
|
|
blank=True, null=True)
|
2020-06-01 11:03:21 +02:00
|
|
|
timestamp = models.DateTimeField(blank=True)
|
|
|
|
fetched = models.BooleanField(default=False)
|
|
|
|
history = HistoricalRecords()
|
|
|
|
|
2020-07-28 18:25:56 +02:00
|
|
|
def clean(self):
|
2020-06-01 11:03:21 +02:00
|
|
|
if not self.fetched:
|
2020-07-28 18:25:56 +02:00
|
|
|
try:
|
|
|
|
summary = WikipediaAPISummary(self.title)
|
|
|
|
except NotFoundError as e:
|
|
|
|
raise ValidationError(str(e))
|
2020-07-18 21:59:42 +02:00
|
|
|
self.extract = summary.extract
|
|
|
|
self.extract_html = summary.extract_html
|
2020-07-27 20:59:44 +02:00
|
|
|
self.description = summary.description
|
2020-07-18 21:59:42 +02:00
|
|
|
self.timestamp = summary.timestamp
|
|
|
|
self.title = summary.title
|
|
|
|
if summary.image:
|
2020-07-18 22:21:57 +02:00
|
|
|
filename = unquote(summary.image.split("/")[-1])
|
2020-07-18 21:59:42 +02:00
|
|
|
try:
|
|
|
|
thumbnail = WikipediaImage.objects.get(filename=filename)
|
|
|
|
except WikipediaImage.DoesNotExist:
|
|
|
|
thumbnail = WikipediaImage.objects.create(filename=filename)
|
2020-07-28 18:15:14 +02:00
|
|
|
success = thumbnail.save()
|
|
|
|
if success:
|
|
|
|
self.thumbnail = thumbnail
|
2020-06-01 11:03:21 +02:00
|
|
|
self.fetched = True
|
|
|
|
|
|
|
|
@property
|
|
|
|
def url(self):
|
2020-07-30 22:04:06 +02:00
|
|
|
return f"https://en.wikipedia.org/wiki/{self.title.replace(' ', '_')}"
|
2020-06-01 11:03:21 +02:00
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
return self.title
|