Advertisement
Guest User

Untitled

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