diff --git a/backend/videoflix/content/models.py b/backend/videoflix/content/models.py index 633fa76..90749aa 100644 --- a/backend/videoflix/content/models.py +++ b/backend/videoflix/content/models.py @@ -6,6 +6,7 @@ class Video(models.Model): title = models.CharField(max_length=80) description = models.CharField(max_length=500) video_file = models.FileField(upload_to='videos', blank=True, null=True) + thumbnail = models.FileField(upload_to='thumbnails/', null=True, blank=True) def __str__(self): return self.title \ No newline at end of file diff --git a/backend/videoflix/content/signals.py b/backend/videoflix/content/signals.py index 6684ead..c803b39 100644 --- a/backend/videoflix/content/signals.py +++ b/backend/videoflix/content/signals.py @@ -1,8 +1,35 @@ from .models import Video from django.dispatch import receiver -from django.db.models.signals import post_delete +from django.conf import settings +from django.db.models.signals import post_save, post_delete +import ffmpeg import os +@receiver(post_save, sender=Video) +def video_post_save(sender, instance, created, **kwargs): + """ + Generates a thumbnail for a newly created `Video` instance. + """ + if created: + video_file_path = instance.video_file.path + thumbnail_dir = settings.THUMBNAIL_DIR + + thumbnail_filename = os.path.splitext(os.path.basename(video_file_path))[0] + '.jpg' + thumbnail_path = os.path.join(thumbnail_dir, thumbnail_filename) + absolute_thumbnail_path = os.path.abspath(thumbnail_path) + + if not os.path.exists(thumbnail_dir): + os.makedirs(thumbnail_dir) + + try: + ffmpeg.input(video_file_path, ss=1).output(absolute_thumbnail_path, vframes=1).run(overwrite_output=True) + instance.thumbnail = os.path.relpath(thumbnail_path, start=settings.MEDIA_ROOT) + instance.save() + + print("New video and thumbnail generated") + except ffmpeg._run.Error as e: + print(f"An error occurred: {e.stderr.decode()}") + @receiver(post_delete, sender=Video) def auto_delete_file_on_delete(sender, instance, **kwargs): """ diff --git a/backend/videoflix/videoflix/settings.py b/backend/videoflix/videoflix/settings.py index 68c7c86..9f68b5f 100644 --- a/backend/videoflix/videoflix/settings.py +++ b/backend/videoflix/videoflix/settings.py @@ -85,6 +85,7 @@ TEMPLATES = [ ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') +THUMBNAIL_DIR = os.path.join(BASE_DIR, 'media/img') MEDIA_URL = '/media/' WSGI_APPLICATION = 'videoflix.wsgi.application'