1
0
Fork 0
mirror of https://github.com/Findus23/acronomy.git synced 2024-09-19 15:33:45 +02:00
acronomy/acros/models/WikipediaImage.py

64 lines
2.5 KiB
Python
Raw Normal View History

2020-07-18 21:59:42 +02:00
from tempfile import TemporaryFile
from django.core.files import File
from django.db import models
2020-08-07 17:50:51 +02:00
from acros.utils.apis import WikipediaImageAPIObject, NotFoundError, requests_session
2020-07-18 21:59:42 +02:00
class WikipediaImage(models.Model):
filename = models.CharField(max_length=200)
pageid = models.IntegerField(editable=False)
thumbnail = models.ImageField(upload_to="wikipedia_images/", blank=True, null=True, editable=False)
2020-07-18 21:59:42 +02:00
thumb_width = models.IntegerField(blank=True, editable=False, null=True)
thumb_height = models.IntegerField(blank=True, editable=False, null=True)
imageurl = models.URLField(editable=False)
2020-07-18 21:59:42 +02:00
caption = models.CharField(max_length=1000, null=True, blank=True)
credit = models.TextField(null=True, blank=True, editable=False)
artist = models.TextField(null=True, blank=True, editable=False)
license_short_name = models.TextField(editable=False)
attribution = models.TextField(null=True, blank=True, editable=False)
license_url = models.URLField(null=True, blank=True, editable=False)
attribution_required = models.BooleanField(editable=False)
copyrighted = models.BooleanField(editable=False)
timestamp = models.DateTimeField(blank=True, editable=False)
2020-07-18 21:59:42 +02:00
def save(self, *args, **kwargs):
try:
img = WikipediaImageAPIObject(self.filename)
except NotFoundError:
2020-07-28 18:15:14 +02:00
return False
2020-07-18 22:10:27 +02:00
if self.thumbnail:
self.thumbnail.delete(save=False)
2020-07-18 22:09:35 +02:00
print("saving")
2020-07-19 22:14:11 +02:00
filename = self.filename
if filename.endswith(".svg"):
filename += ".png"
2020-07-18 21:59:42 +02:00
with TemporaryFile("rb+") as fd:
2020-08-07 17:50:51 +02:00
r = requests_session.get(img.thumburl)
2020-07-18 21:59:42 +02:00
for chunk in r.iter_content(chunk_size=128):
fd.write(chunk)
image_file = File(fd)
2020-07-19 22:15:42 +02:00
self.thumbnail.save(filename, image_file, save=False)
2020-07-18 21:59:42 +02:00
self.thumb_width, self.thumb_height = img.thumb_size
self.pageid = img.pageid
self.imageurl = img.url
self.credit = img.credit
self.artist = img.artist
self.license_short_name = img.license_short_name
self.attribution = img.attribution
self.license_url = img.license_url
self.attribution_required = img.attribution_required
self.copyrighted = img.copyrighted
self.timestamp = img.timestamp
super(WikipediaImage, self).save(*args, **kwargs)
2020-07-28 18:34:39 +02:00
return True
2020-07-18 21:59:42 +02:00
@property
def commons_url(self):
return f"https://commons.wikimedia.org/wiki/File:{self.filename}"
def __str__(self):
return self.filename