static files too

This commit is contained in:
Markos Gogoulos 2025-05-21 16:03:09 +03:00
parent 378e10d1f2
commit f5176d12d7
23 changed files with 67 additions and 37 deletions

View File

@ -2,13 +2,11 @@
# related content # related content
import itertools import itertools
import json
import logging import logging
import os
import random import random
import re import re
import tempfile
from datetime import datetime from datetime import datetime
import subprocess
from django.conf import settings from django.conf import settings
from django.core.cache import cache from django.core.cache import cache
@ -17,7 +15,6 @@ from django.core.mail import EmailMessage
from django.db.models import Q from django.db.models import Q
from django.utils import timezone from django.utils import timezone
from contextlib import contextmanager from contextlib import contextmanager
from django.db.models.signals import post_save
from cms import celery_app from cms import celery_app
@ -414,6 +411,25 @@ def clean_comment(raw_comment):
return cleaned_comment return cleaned_comment
def kill_ffmpeg_process(filepath):
"""Kill ffmpeg process that is processing a specific file
Args:
filepath: Path to the file being processed by ffmpeg
Returns:
subprocess.CompletedProcess: Result of the kill command
"""
cmd = "ps aux|grep 'ffmpeg'|grep %s|grep -v grep |awk '{print $2}'" % filepath
result = subprocess.run(cmd, stdout=subprocess.PIPE, shell=True)
pid = result.stdout.decode("utf-8").strip()
if pid:
logger.info("Killing ffmpeg process with PID: %s", pid)
cmd = "kill -9 %s" % pid
result = subprocess.run(cmd, stdout=subprocess.PIPE, shell=True)
return result
def copy_video(original_media, copy_encodings=True, title_suffix="(Trimmed)"): def copy_video(original_media, copy_encodings=True, title_suffix="(Trimmed)"):
"""Create a copy of a media object """Create a copy of a media object
@ -446,7 +462,7 @@ def copy_video(original_media, copy_encodings=True, title_suffix="(Trimmed)"):
if copy_encodings: if copy_encodings:
for encoding in original_media.encodings.filter(status="success", chunk=False): for encoding in original_media.encodings.filter(chunk=False):
if encoding.media_file: if encoding.media_file:
with open(encoding.media_file.path, "rb") as f: with open(encoding.media_file.path, "rb") as f:
myfile = File(f) myfile = File(f)
@ -454,7 +470,7 @@ def copy_video(original_media, copy_encodings=True, title_suffix="(Trimmed)"):
media_file=myfile, media_file=myfile,
media=new_media, media=new_media,
profile=encoding.profile, profile=encoding.profile,
status="success", status=encoding.status,
progress=100, progress=100,
chunk=False, chunk=False,
logs=f"Copied from encoding {encoding.id}" logs=f"Copied from encoding {encoding.id}"

View File

@ -319,7 +319,6 @@ class Media(models.Model):
self.__original_uploaded_poster = self.uploaded_poster self.__original_uploaded_poster = self.uploaded_poster
def save(self, *args, **kwargs): def save(self, *args, **kwargs):
print(f"SAVE called for {self.friendly_token}")
if not self.title: if not self.title:
self.title = self.media_file.path.split("/")[-1] self.title = self.media_file.path.split("/")[-1]
@ -680,7 +679,8 @@ class Media(models.Model):
if ret: if ret:
return helpers.url_from_path(ret.media_file.path) return helpers.url_from_path(ret.media_file.path)
return None # showing the original file
return helpers.url_from_path(self.media_file.path)
@property @property
@ -688,7 +688,7 @@ class Media(models.Model):
if self.media_type not in ["video"]: if self.media_type not in ["video"]:
return None return None
ret = self.encodings.filter(status="success", profile__extension='mp4').order_by("-profile__resolution").first() ret = self.encodings.filter(status="success", profile__extension='mp4', chunk=False).order_by("-profile__resolution").first()
if ret: if ret:
return ret.media_file.path return ret.media_file.path
@ -705,12 +705,17 @@ class Media(models.Model):
for key in ENCODE_RESOLUTIONS_KEYS: for key in ENCODE_RESOLUTIONS_KEYS:
ret[key] = {} ret[key] = {}
# if this is enabled, return original file on a way # if DO_NOT_TRANSCODE_VIDEO enabled, return original file on a way
# that video.js can consume # that video.js can consume. Or also if encoding_status is running, do the
# same so that the video appears on the player
if settings.DO_NOT_TRANSCODE_VIDEO: if settings.DO_NOT_TRANSCODE_VIDEO:
ret['0-original'] = {"h264": {"url": helpers.url_from_path(self.media_file.path), "status": "success", "progress": 100}} ret['0-original'] = {"h264": {"url": helpers.url_from_path(self.media_file.path), "status": "success", "progress": 100}}
return ret return ret
if self.encoding_status in ["running", "pending"]:
ret['0-original'] = {"h264": {"url": helpers.url_from_path(self.media_file.path), "status": "success", "progress": 100}}
return ret
for encoding in self.encodings.select_related("profile").filter(chunk=False): for encoding in self.encodings.select_related("profile").filter(chunk=False):
if encoding.profile.extension == "gif": if encoding.profile.extension == "gif":
continue continue
@ -1577,7 +1582,6 @@ def media_save(sender, instance, created, **kwargs):
# once model is saved # once model is saved
# SOS: do not put anything here, as if more logic is added, # SOS: do not put anything here, as if more logic is added,
# we have to disconnect signal to avoid infinite recursion # we have to disconnect signal to avoid infinite recursion
print(f'mpainei media_save gia {instance.friendly_token}')
if not instance.friendly_token: if not instance.friendly_token:
return False return False
@ -1599,7 +1603,6 @@ def media_save(sender, instance, created, **kwargs):
tag.update_tag_media() tag.update_tag_media()
instance.update_search_vector() instance.update_search_vector()
print(f'EXIT media_save gia {instance.friendly_token}')
@receiver(pre_delete, sender=Media) @receiver(pre_delete, sender=Media)

View File

@ -606,6 +606,17 @@ def view_media(request):
context["CAN_DELETE_MEDIA"] = True context["CAN_DELETE_MEDIA"] = True
context["CAN_EDIT_MEDIA"] = True context["CAN_EDIT_MEDIA"] = True
context["CAN_DELETE_COMMENTS"] = True context["CAN_DELETE_COMMENTS"] = True
# TODO: explaim
if media.media_type == 'video':
video_msg = None
if media.encoding_status == "pending":
video_msg = "Media encoding hasn't started yet. Attempting to show the original video file"
if media.encoding_status == "running":
video_msg = "Media encoding is under processing. Attempting to show the original video file"
if video_msg:
messages.add_message(request, messages.INFO, video_msg)
return render(request, "cms/media.html", context) return render(request, "cms/media.html", context)

View File

@ -16,11 +16,11 @@ import '../VideoViewer.scss';
function filterVideoEncoding(encoding_status) { function filterVideoEncoding(encoding_status) {
switch (encoding_status) { switch (encoding_status) {
case 'running': case 'running_X':
MediaPageStore.set('media-load-error-type', 'encodingRunning'); MediaPageStore.set('media-load-error-type', 'encodingRunning');
MediaPageStore.set('media-load-error-message', 'Media encoding is currently running. Try again in few minutes.'); MediaPageStore.set('media-load-error-message', 'Media encoding is currently running. Try again in few minutes.');
break; break;
case 'pending': case 'pending_X':
MediaPageStore.set('media-load-error-type', 'encodingPending'); MediaPageStore.set('media-load-error-type', 'encodingPending');
MediaPageStore.set('media-load-error-message', 'Media encoding is pending'); MediaPageStore.set('media-load-error-message', 'Media encoding is pending');
break; break;
@ -590,7 +590,7 @@ function findGetParameter(parameterName) {
} }
function handleCanvas(videoElem) { // Make sure it's a video element function handleCanvas(videoElem) { // Make sure it's a video element
if (!videoElem || !videoElem.tagName || videoElem.tagName.toLowerCase() !== 'video') { if (!videoElem || !videoElem.tagName || videoElem.tagName.toLowerCase() !== 'video') {
console.error('Invalid video element:', videoElem); console.error('Invalid video element:', videoElem);
return; return;
@ -603,7 +603,7 @@ function findGetParameter(parameterName) {
const muted = parseInt(findGetParameter('muted')); const muted = parseInt(findGetParameter('muted'));
const autoplay = parseInt(findGetParameter('autoplay')); const autoplay = parseInt(findGetParameter('autoplay'));
const timestamp = parseInt(findGetParameter('t')); const timestamp = parseInt(findGetParameter('t'));
// Handle timestamp clicks // Handle timestamp clicks
document.addEventListener('click', function (e) { document.addEventListener('click', function (e) {
if (e.target.classList.contains('video-timestamp')) { if (e.target.classList.contains('video-timestamp')) {
@ -621,7 +621,7 @@ function findGetParameter(parameterName) {
if (muted == 1) { if (muted == 1) {
Player.muted(true); Player.muted(true);
} }
if (timestamp >= 0 && timestamp < Player.duration()) { if (timestamp >= 0 && timestamp < Player.duration()) {
// Start the video from the given time // Start the video from the given time
Player.currentTime(timestamp); Player.currentTime(timestamp);

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long