specific thumbnail generation view + manual refresh thumbnail generation, progress bar with error handling and thumbnail deletion

This commit is contained in:
Xevion
2020-10-31 23:01:59 -05:00
parent 176b3273ce
commit 041e2a6e42
4 changed files with 76 additions and 3 deletions

View File

@@ -7,6 +7,8 @@ from django.db import models
from django.urls import reverse
from easy_thumbnails.alias import aliases
from viewer import helpers
if not aliases.get('small'):
aliases.set('small', {'size': (150, 80), 'crop': True})
@@ -34,16 +36,22 @@ class ServedDirectory(models.Model):
# TODO: Implement separate recursive file matching implementation
# TODO: Implement RegEx filtering step
directories = []
for file in os.listdir(self.path):
files = os.listdir(self.path)
for i, file in enumerate(files):
print(f'{i} / {len(files)}')
file_path = os.path.join(self.path, file)
if os.path.isfile(file_path):
# Check if the file has been entered before
entry: File
entry = self.files.filter(filename__exact=file).first()
if entry is None:
# create the file entry
entry = File.create(full_path=file_path, parent=self)
entry.save()
else:
if entry.thumbnail is None:
entry.generate_thumbnail()
else:
# directory found, remember it
directories.append(file_path)
@@ -60,6 +68,7 @@ class File(models.Model):
filename = models.CharField('Filename', max_length=160)
mediatype = models.CharField('Mediatype', max_length=30)
directory = models.ForeignKey(ServedDirectory, on_delete=models.CASCADE, related_name='files')
thumbnail = models.CharField('Thumbnail Filename', max_length=160, null=True, default=None)
@classmethod
def create(cls, full_path: str, parent: ServedDirectory) -> 'File':
@@ -75,6 +84,42 @@ class File(models.Model):
"""Retrieve the direct URL for a given file."""
return reverse('file', args=(directory.id, self.filename))
def delete_thumbnail(self) -> None:
if self.thumbnail:
try:
os.remove(os.path.join(self.thumbs_dir, self.thumbnail))
self.thumbnail = None
self.save()
except FileNotFoundError:
pass
@property
def thumbnail_url(self):
if self.thumbnail:
return f'/thumbnails/{self.thumbnail}'
return ''
@property
def thumbs_dir(self):
return os.path.join(os.path.dirname(os.path.abspath(__file__)), 'static', 'thumbnails')
def generate_thumbnail(self) -> None:
# TODO: Add django-background-task scheduling
self.delete_thumbnail()
thumb_file = f'{uuid.uuid4()}.jpeg'
self.thumbnail = thumb_file
# Generate thumbnail
try:
helpers.generate_thumbnail(self.path, os.path.join(self.thumbs_dir, self.thumbnail))
except Exception:
print(f'Could not thumbnail: {self.filename}')
self.delete_thumbnail()
self.save()
@staticmethod
def get_mediatype(path) -> str:
"""Simple media type categorization based on the given path."""