Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import subprocess
- import os
- from django.db.models.signals import post_save
- from django.dispatch import receiver
- from django.core.files import File
- from pathlib import Path
- from .models import Lecture
- @receiver(post_save, sender=Lecture)
- def handle_video_upload(sender, instance, created, **kwargs):
- """
- Variables:
- - file_relative_path:
- path relative to the project directory
- ex: media/lectures/first_video_2/2020-04-04_16-11-20.mkv
- - file_suffix:
- suffix | file extension
- ex: .mkv
- - file_relative_dir:
- project-related directory, without the file name included
- ex: media/lectures/first_video_2
- - file_name_m3u8:
- name of the file containing the .m3u8 extension
- ex: 2020-04-04_16-11-20.m3u8
- - file_tmp_local_dir:
- temporary directory to store files
- ex: /tmp/media/lectures/first_video_2
- - file_tmp_local_output:
- temporary path of the .m3u8 file, where also
- will have the .ts files
- ex: /tmp/media/lectures/first_video_2/2020-04-04_16-11-20.m3u8
- - file_cloudfront_url:
- url of the file uploaded to the cloudfront
- ex: https://d4fmj82j2soe4.cloudfront.net/media/lectures/first_video_2/2020-04-04_16-11-20.mkv
- """
- file_relative_path = Path(instance.file.name)
- file_suffix = file_relative_path.suffix
- if not file_suffix == '.m3u8' and instance.file_type == "V":
- file_relative_dir = os.path.dirname(instance.file.name)
- file_relative_path_m3u8 = file_relative_path.with_suffix(".m3u8")
- file_name_m3u8 = file_relative_path_m3u8.name
- file_tmp_local_dir = f"/tmp/{file_relative_dir}"
- file_tmp_local_output = f"{file_tmp_local_dir}/{file_name_m3u8}"
- file_cloudfront_url = instance.file.url
- # create the local dir for the files
- subprocess.run(['mkdir', '-p', file_tmp_local_dir])
- # convert a video in HLS (.m3u8 and .ts files)
- subprocess.run([
- "ffmpeg",
- "-i",
- file_cloudfront_url,
- "-f",
- "hls",
- file_tmp_local_output
- ])
- # update the instance file field with the new .m3u8 file
- with open(file_tmp_local_output, "r") as file_object:
- print(file_tmp_local_output)
- print(file_name_m3u8)
- file_m3u8 = File(
- name=file_relative_path_m3u8,
- file=file_object)
- instance.file.save(file_name_m3u8, file_m3u8)
- subprocess.run(["rm", "-r", file_tmp_local_dir])
- print("file_relative_path: ", file_relative_path)
- print("file_suffix: ", file_suffix)
- print("file_relative_dir: ", file_relative_dir)
- print("file_name_m3u8: ", file_name_m3u8)
- print("file_relative_path_m3u8: ", file_relative_path_m3u8)
- print("file_tmp_local_dir:", file_tmp_local_dir)
- print("file_tmp_local_output", file_tmp_local_output)
- print("file_cloudfront_url: ", file_cloudfront_url)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement