Work to add Youtube downloads, video and image uploads, and the player script

This commit is contained in:
Bradley committed 2026-11-13 17:37:31 -05:00
1 parent a3f55a8c35
commit 92d6473e1d
15 files changed
+1047 -79

No files matched your search

+1 -1
View File
@@ -31,7 +31,7 @@
<a class="col-sm-4 btn btn-secondary p-3 my-1" href="/configure/stream">Configure a Stream</a>
</div>
<div class="row">
<button class="col-sm-4 btn btn-secondary p-3 my-1">Upload a Video</button>
<a class="col-sm-4 btn btn-secondary p-3 my-1" href="{{ url_for('upload_video.get_page') }}">Upload a Video</a>
<a class="col-sm-4 btn btn-secondary p-3 my-1" href="{{ url_for('youtube_download.request_download') }}">Get Video from YouTube</a>
<a class="col-sm-4 btn btn-secondary p-3 my-1" href="{{ url_for('youtube_download.list_jobs') }}">YouTube Download Jobs</a>
</div>
+33 -30
View File
@@ -1,42 +1,45 @@
<!DOCTYPE html>
<html>
<html lang="en">
<head>
<title>Video Commander</title>
<title>Upload a Static Image - Sanctuary Commander</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<link rel="stylesheet" type="text/css" href="../static/style.css">
<script src="../static/script.js"></script>
<script>
function prepUpload() {
uploadFiles('submit', 'fileToUpload', 'progressContainer', 'progress', '/upload/photo', {
'name': document.getElementById('buttonName').value
})
}
</script>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
<script src="{{ url_for('static', filename='upload_media.js') }}" defer></script>
</head>
<body>
<div class="container">
<h1 class="text-center">Upload a Static Photo</h1>
<h1 class="text-center">Upload a Static Image</h1>
<hr>
<div class="alert alert-info text-center" role="alert">
Upload a single static photo, single photos are good if you want something that doesn't distract during services.
<a class="btn btn-secondary mb-3" href="{{ url_for('home.root_route') }}">Home</a>
<div class="alert alert-warning" role="note">
Do not leave this page, refresh, or close the browser until the upload is complete.
You will automatically return to the homepage when the image has been saved.
</div>
<form>
<div id="progressContainer" class="progress" role="progressbar", aria-label="Upload Progress" aria-valuemin="0"
aria-valuemin="0", aria-valuemax="100" >
<div id="progress" class="progress-bar" style="width: 0%;">0%</div>
</div>
<div class="form-group">
<label for="fileToUpload">File to Upload</label>
<input type="file" class="form-control" name="file" id="fileToUpload" />
</div>
<div class="form-group">
<label for="buttonName">Button Name</label>
<input type="text" class="form-control" name="buttonName" id="buttonName" />
</div>
<button id="submit" class="btn btn-primary form-control" onclick="prepUpload()">Submit</button>
<p>Upload one image, up to 100MB ({{ max_image_size }} bytes).</p>
<noscript><div class="alert alert-danger">JavaScript must be enabled to upload images and show progress.</div></noscript>
<div id="uploadError" class="alert alert-danger" role="alert" hidden></div>
<form id="imageUploadForm" action="{{ url_for('upload_photo.get_page') }}" method="POST" enctype="multipart/form-data"
data-media-upload data-media-kind="image" data-limit-label="100MB"
data-max-size="{{ max_image_size }}" data-home-url="{{ url_for('home.root_route') }}">
<fieldset id="uploadFields">
<div class="mb-3">
<label class="form-label" for="imageName">Image Name</label>
<input class="form-control" type="text" id="imageName" name="name" required>
</div>
<div class="mb-3">
<label class="form-label" for="imageFile">Image File</label>
<input class="form-control" type="file" id="imageFile" name="files[]"
accept=".jpg,.jpeg,.png,.webp,.bmp,.tif,.tiff,.gif" required>
</div>
<button class="btn btn-primary mb-3" type="submit">Upload Image</button>
</fieldset>
</form>
<div id="uploadProgress" class="progress mb-2" role="progressbar" aria-label="Image upload progress"
aria-valuemin="0" aria-valuemax="100" aria-valuenow="0">
<div id="uploadProgressBar" class="progress-bar" style="width: 0%">0%</div>
</div>
<p id="uploadStatus" role="status" aria-live="polite">Ready to upload.</p>
</div>
</body>
</html>
</html>
+67 -38
View File
@@ -1,48 +1,77 @@
from pathlib import Path
import sqlite3
from uuid import uuid4
from flask import Blueprint, request, render_template, jsonify, current_app
from werkzeug.exceptions import RequestEntityTooLarge
from utilities.tools import get_db
from werkzeug.utils import secure_filename
import os
MAX_IMAGE_SIZE = 100 * (1024 ** 2)
MULTIPART_OVERHEAD = 1024 ** 2
IMAGE_EXTENSIONS = {'.jpg', '.jpeg', '.png', '.webp', '.bmp', '.tif', '.tiff', '.gif'}
upload_photo_bp = Blueprint('upload_photo', __name__, url_prefix='/upload', template_folder='.')
@upload_photo_bp.before_request
def set_upload_limit():
if request.method == 'POST':
request.max_content_length = MAX_IMAGE_SIZE + MULTIPART_OVERHEAD
@upload_photo_bp.errorhandler(RequestEntityTooLarge)
def upload_too_large(error):
return jsonify(status='FAILED', error='The image must be no larger than 100MB.'), 413
@upload_photo_bp.route('/photo', methods=['GET', 'POST'])
def get_page():
if request.method == "GET":
return render_get(), 200
elif request.method == "POST":
return upload()
def render_get():
return render_template('upload_photo.html')
if request.method == 'GET':
return render_template('upload_photo.html', max_image_size=MAX_IMAGE_SIZE)
return upload()
def upload():
if not request.files['files[]']:
return jsonify({
'status': 'FAILED',
'error': '/upload/photo requires 1 photo'
}), 400
# TODO Button name data exists
# TODO Button name already exists validation
# TODO File input validation
print(request.files['files[]'])
name = request.form.get('name', '').strip()
if not name:
return jsonify(status='FAILED', error='Please enter a name for the image.'), 400
files = request.files.getlist('files[]')
if len(files) != 1 or not files[0].filename:
return jsonify(status='FAILED', error='Please select exactly one image file.'), 400
image = files[0]
extension = Path(image.filename).suffix.lower()
if extension not in IMAGE_EXTENSIONS:
return jsonify(status='FAILED', error='Please select a supported image file.'), 400
file = request.files['files[]']
if file:
folder_path = os.path.join(current_app.config["config"]["upload_location"], request.form["name"])
if not os.path.exists(folder_path):
os.makedirs(folder_path)
filename = secure_filename(file.filename)
file.save(os.path.join(folder_path, filename))
get_db().insert(
"media",
["media_name", "media_uri"],
[request.form["name"], os.path.join(folder_path, filename)]
)
return jsonify({
'status': 'SUCCESS'
}), 200
storage = (Path(current_app.config['CONFIG_DIRECTORY']) /
current_app.config['config'].get('image_upload_location', 'Images')).resolve()
# Names are display metadata, never user-controlled storage paths.
token = uuid4().hex
destination = storage / f'upload-{token}{extension}'
partial = storage / f'upload-{token}.part'
saved = False
try:
storage.mkdir(parents=True, exist_ok=True)
size = 0
with partial.open('xb') as output:
while chunk := image.stream.read(1024 ** 2):
size += len(chunk)
if size > MAX_IMAGE_SIZE:
raise RequestEntityTooLarge()
output.write(chunk)
if size == 0:
return jsonify(status='FAILED', error='The image file is empty.'), 400
partial.rename(destination)
get_db().insert('media', ['media_name', 'media_uri'], [name, str(destination)])
saved = True
return jsonify(status='SUCCESS'), 200
except (OSError, sqlite3.Error):
current_app.logger.exception('Unable to save uploaded image')
return jsonify(status='FAILED', error='Unable to save the image. Please try again.'), 500
finally:
for path in ([partial] if saved else [partial, destination]):
try:
path.unlink(missing_ok=True)
except OSError:
current_app.logger.exception('Unable to clean up upload file %s', path)
+45
View File
@@ -0,0 +1,45 @@
<!DOCTYPE html>
<html lang="en">
<head>
<title>Upload a Video - Sanctuary Commander</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
<script src="{{ url_for('static', filename='upload_media.js') }}" defer></script>
</head>
<body>
<div class="container">
<h1 class="text-center">Upload a Video</h1>
<hr>
<a class="btn btn-secondary mb-3" href="{{ url_for('home.root_route') }}">Home</a>
<div class="alert alert-warning" role="note">
Do not leave this page, refresh, or close the browser until the upload is complete.
You will automatically return to the homepage when the video has been saved.
</div>
<p>Upload one video, up to 5GB ({{ max_video_size }} bytes). Large uploads may take several minutes.</p>
<noscript><div class="alert alert-danger">JavaScript must be enabled to upload videos and show progress.</div></noscript>
<div id="uploadError" class="alert alert-danger" role="alert" hidden></div>
<form id="videoUploadForm" action="{{ url_for('upload_video.get_page') }}" method="POST" enctype="multipart/form-data"
data-media-upload data-media-kind="video" data-limit-label="5GB"
data-max-size="{{ max_video_size }}" data-home-url="{{ url_for('home.root_route') }}">
<fieldset id="uploadFields">
<div class="mb-3">
<label class="form-label" for="videoName">Video Name</label>
<input class="form-control" type="text" id="videoName" name="name" required>
</div>
<div class="mb-3">
<label class="form-label" for="videoFile">Video File</label>
<input class="form-control" type="file" id="videoFile" name="files[]"
accept=".mp4,.m4v,.mkv,.mov,.webm,.avi,.wmv,.mpeg,.mpg,.ts,.mts,.m2ts,.3gp,.ogv" required>
</div>
<button class="btn btn-primary mb-3" type="submit">Upload Video</button>
</fieldset>
</form>
<div id="uploadProgress" class="progress mb-2" role="progressbar" aria-label="Video upload progress"
aria-valuemin="0" aria-valuemax="100" aria-valuenow="0">
<div id="uploadProgressBar" class="progress-bar" style="width: 0%">0%</div>
</div>
<p id="uploadStatus" role="status" aria-live="polite">Ready to upload.</p>
</div>
</body>
</html>
+81
View File
@@ -0,0 +1,81 @@
from pathlib import Path
import sqlite3
from uuid import uuid4
from flask import Blueprint, request, render_template, jsonify, current_app
from werkzeug.exceptions import RequestEntityTooLarge
from utilities.tools import get_db
MAX_VIDEO_SIZE = 5 * (1024 ** 3)
# Multipart boundaries and the name field are not part of the video file's size.
MULTIPART_OVERHEAD = 1024 ** 2
VIDEO_EXTENSIONS = {'.mp4', '.m4v', '.mkv', '.mov', '.webm', '.avi', '.wmv',
'.mpeg', '.mpg', '.ts', '.mts', '.m2ts', '.3gp', '.ogv'}
upload_video_bp = Blueprint('upload_video', __name__, url_prefix='/upload', template_folder='.')
@upload_video_bp.before_request
def set_upload_limit():
if request.method == 'POST':
# Flask 3.1 supports a per-request limit, leaving other uploads unchanged.
request.max_content_length = MAX_VIDEO_SIZE + MULTIPART_OVERHEAD
@upload_video_bp.errorhandler(RequestEntityTooLarge)
def upload_too_large(error):
return jsonify(status='FAILED', error='The video must be no larger than 5GB.'), 413
@upload_video_bp.route('/video', methods=['GET', 'POST'])
def get_page():
if request.method == 'GET':
return render_template('upload_video.html', max_video_size=MAX_VIDEO_SIZE)
return upload()
def upload():
name = request.form.get('name', '').strip()
if not name:
return jsonify(status='FAILED', error='Please enter a name for the video.'), 400
files = request.files.getlist('files[]')
if len(files) != 1 or not files[0].filename:
return jsonify(status='FAILED', error='Please select exactly one video file.'), 400
video = files[0]
extension = Path(video.filename).suffix.lower()
if extension not in VIDEO_EXTENSIONS:
return jsonify(status='FAILED', error='Please select a supported video file.'), 400
storage = (Path(current_app.config['CONFIG_DIRECTORY']) /
current_app.config['config'].get('youtube_download_location', 'Videos')).resolve()
# Never use the media name or client filename as a storage path.
token = uuid4().hex
destination = storage / f'upload-{token}{extension}'
partial = storage / f'upload-{token}.part'
saved = False
try:
storage.mkdir(parents=True, exist_ok=True)
size = 0
with partial.open('xb') as output:
while chunk := video.stream.read(1024 ** 2):
size += len(chunk)
if size > MAX_VIDEO_SIZE:
raise RequestEntityTooLarge()
output.write(chunk)
if size == 0:
return jsonify(status='FAILED', error='The video file is empty.'), 400
partial.rename(destination)
get_db().insert('media', ['media_name', 'media_uri'], [name, str(destination)])
saved = True
return jsonify(status='SUCCESS'), 200
except (OSError, sqlite3.Error):
current_app.logger.exception('Unable to save uploaded video')
return jsonify(status='FAILED', error='Unable to save the video. Please try again.'), 500
finally:
# Rejected/failed uploads must not leave partial files or uncatalogued videos.
for path in ([partial] if saved else [partial, destination]):
try:
path.unlink(missing_ok=True)
except OSError:
current_app.logger.exception('Unable to clean up upload file %s', path)