Advertisement
Guest User

Untitled

a guest
Apr 4th, 2020
244
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.84 KB | None | 0 0
  1. import boto3
  2. import subprocess
  3. import os
  4. from django.db.models.signals import post_save
  5. from django.dispatch import receiver
  6. from django.core.files import File
  7. from pathlib import Path
  8. from decouple import config
  9. from .models import Lecture
  10.  
  11. AWS_STORAGE_BUCKET_NAME = config("AWS_STORAGE_BUCKET_NAME")
  12.  
  13. s3 = boto3.resource("s3")
  14. bucket = s3.Bucket(AWS_STORAGE_BUCKET_NAME)
  15.  
  16.  
  17. @receiver(post_save, sender=Lecture)
  18. def handle_video_upload(sender, instance, created, **kwargs):
  19.     """
  20.    Variables names:
  21.        - file_absolute_path: absolute path of the saved instance
  22.        - file_suffix: file suffix to check if the video is a new
  23.            .mkv video being uploaded, to check if the conversion
  24.            is needed
  25.        - file_absolute_path_m3u8: a string with absolute path to save
  26.            the new .m3u8 file
  27.        - file_name_m3u8: the name of the file with .m3u8 suffix
  28.    """
  29.     file_absolute_path = Path(instance.file.path)
  30.     file_suffix = file_absolute_path.suffix
  31.  
  32.     if not file_suffix == '.m3u8' and instance.file_type == "V":
  33.         file_absolute_path_m3u8 = file_absolute_path.with_suffix(".m3u8")
  34.         file_name_m3u8 = file_absolute_path_m3u8.name
  35.  
  36.         # use shell commands to create HLS .m3u8 file
  37.         # and delete the original video file
  38.         subprocess.run([
  39.             "ffmpeg",
  40.             "-i",
  41.             file_absolute_path,
  42.             "-f",
  43.             "hls",
  44.             file_absolute_path_m3u8
  45.         ])
  46.         subprocess.run(["rm", file_absolute_path])
  47.  
  48.         # update the file with the new .m3u8 file
  49.         with open(file_absolute_path_m3u8, "r") as file_object:
  50.             file_m3u8 = File(name=file_absolute_path_m3u8, file=file_object)
  51.             subprocess.run(["rm", file_absolute_path_m3u8])
  52.             instance.file.save(file_name_m3u8, file_m3u8)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement