diff --git a/api/migrations/0010_item_file_thumbnail.py b/api/migrations/0010_item_file_thumbnail.py new file mode 100644 index 0000000..c005d2e --- /dev/null +++ b/api/migrations/0010_item_file_thumbnail.py @@ -0,0 +1,20 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.10.5 on 2017-11-15 17:33 +from __future__ import unicode_literals + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('api', '0009_auto_20171107_2250'), + ] + + operations = [ + migrations.AddField( + model_name='item', + name='file_thumbnail', + field=models.ImageField(blank=True, null=True, upload_to='thumbnails'), + ), + ] diff --git a/api/models.py b/api/models.py index 94e094f..1a6ab96 100644 --- a/api/models.py +++ b/api/models.py @@ -6,11 +6,17 @@ ) from django.contrib.postgres.fields import JSONField from guardian.mixins import GuardianUserMixin - from tests import resources - +import pypandoc +from pdf2image import convert_from_path import datetime - +import tempfile +import requests +import os +from io import BytesIO +import copy +from PIL import Image +from django.core.files.base import ContentFile ITEM_KINDS = [ ('none', 'none'), @@ -208,7 +214,7 @@ class Item(models.Model): end_time = models.DateTimeField(null=True, blank=True, default=None) file_link = models.CharField(null=True, blank=True, max_length=1000) file_name = models.CharField(null=True, blank=True, max_length=1000) - + file_thumbnail = models.ImageField(upload_to='thumbnails', null=True, blank=True) collection = models.ForeignKey('Collection', related_name='items') created_by = models.ForeignKey(User) @@ -218,3 +224,20 @@ class Meta: ("view", "View this item"), ("approve", "Approve this item") ) + + def save(self, *args, **kwargs): + if not self.pk: + # download file (get link from file_link) + input_filename = "test.docx" + midput_filename = "tmp.pdf" + with tempfile.TemporaryDirectory() as path: + midput_filepath = os.path.join(path, midput_filename) + pypandoc.convert_file(input_filename, 'pdf', outputfile=midput_filepath) + image = convert_from_path(midput_filepath)[0] + image.thumbnail((500, 500)) + thumb = image.crop((0, 0, image.width, 250)) + thumb.load() + thumb_io = BytesIO() + thumb.save(thumb_io, format='PNG') + self.file_thumbnail.save(self.title + '.png', ContentFile(thumb_io.getvalue()), save=False) + super(Item, self).save(*args, **kwargs) diff --git a/service/settings/base.py b/service/settings/base.py index bf20fbc..61cbaaa 100644 --- a/service/settings/base.py +++ b/service/settings/base.py @@ -191,3 +191,6 @@ STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static') STATIC_URL = '/static/' + +MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media') +MEDIA_URL = '/media/'