diff --git a/.gitignore b/.gitignore index fd7a08d..778fa3e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,4 @@ *__pycache__* -/Videos/ \ No newline at end of file +/Videos/ +/Images/ +/ffplay.log \ No newline at end of file diff --git a/README.md b/README.md index d7c083f..b0a87ef 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,101 @@ Simple Goal List - Ahead of time uploading of pictures and videos from external devices - USB media awareness/playback +## Fullscreen player + +Install FFplay (usually provided by FFmpeg), then run the player in the graphical +session connected to the display: + +```sh +python3 player.py +``` + +The player reads `config.json` beside the script and checks the database every +two seconds. Use `--config /path/to/config.json` for another configuration. +Relative database paths and local media paths are resolved against the config +file's directory; stream URLs are passed through unchanged. + +Selection priority is: + +1. The lowest-ID row with `media_active = 1`. +2. If none is active, the lowest-ID row with `media_default = 1`. +3. If neither exists, a fullscreen black screen generated by FFplay. + +A selected row with a missing or blank URI also displays black. Changes to the +effective selected row or its URI stop the old FFplay process before starting +its replacement. Changes to other rows do not interrupt playback. Unexpected +FFplay exits are retried on the next poll. A finite video holds its last frame +at the end rather than clearing its active flag or automatically selecting +another item. Static images remain displayed until selection changes. + +FFplay always starts fullscreen with its banner and progress output disabled. +Only FFplay errors are appended to `ffplay.log` beside `config.json`; stdout is +discarded. Use `--log-file /path/to/errors.log` to choose another log. The player +itself reports selection changes and database/process errors to the console. +Ctrl+C or SIGTERM stops the child process; a child that ignores termination is +killed after two seconds. The player does not modify the database and currently +does not apply `media_playback_option` records. + +Until playback buttons are wired up, set selection flags directly in SQLite. +For example, select media ID 3 without temporarily leaving several active rows: + +```sql +BEGIN; +UPDATE media SET media_active = 0; +UPDATE media SET media_active = 1 WHERE media_id = 3; +COMMIT; +``` + +Clear active flags to return to the default. Clear default flags too for black. +Flask and the player run separately; starting the web app alone does not start +playback. The player requires a working graphical display/audio session, not +just an SSH shell without display access. + +## Uploading local videos + +Use **Upload a Video** on the home page, or visit `/upload/video`. Enter a display +name and select one video. The limit is 5GB (5 × 1024³ bytes), checked both in the +browser and on the server. Common formats including MP4, MKV, MOV, WebM, AVI, +MPEG, and WMV are accepted by extension; the upload does not transcode or inspect +video codecs. + +The page displays transfer progress and warns against navigating away. At 100%, +wait for the server to finish saving; only then will the page automatically +return home. Errors remain on the page so the user can retry. JavaScript is +required for this workflow. + +Videos use the same `youtube_download_location` configuration as YouTube downloads +(default `Videos`, relative to `config.json`). Files receive unique generated +names, while the entered display name and absolute file path are saved to +`media`. Failed uploads are cleaned up. The separate player can display the +video when its media record is marked active or default. + +This route requires Flask 3.1+ for its per-request size limit. Its request limit +includes a small allowance for multipart form overhead without raising other +routes' existing limits. If deploying behind a proxy, configure its request-size +limit and timeouts to permit 5GB uploads plus form overhead. Allow sufficient +space for both Flask's temporary upload and the final video file. + +## Uploading static images + +Use **Upload a Static Image** on the home page, or visit `/upload/photo`. Enter +an image name and choose one JPG/JPEG, PNG, WebP, BMP, TIFF, or GIF file. Files +are accepted by extension; this workflow does not decode the image or check for +animation. SVG and other active-content formats are not accepted. + +Image uploads now use `"image_upload_location": "Images"` in `config.json`, +relative to that file. The folder is created automatically when saving an upload +and excluded from Git. Existing images in the older `uploads` location and their +media records are left unchanged. + +The image page has a 100MB (100 × 1024² bytes) file limit in both the browser +and server. Like video uploads, it provides progress feedback, a warning not to +navigate away, and an automatic return home only after saving succeeds. Both pages share the same +upload JavaScript. Errors stay on the page for retry. Files have unique storage +names; the requested display name and absolute path are stored in `media`. +Failed uploads are cleaned up. JavaScript and Flask 3.1+ are required, and proxy +limits, timeouts, and temporary disk space must accommodate large uploads. + ## YouTube download worker Install `yt-dlp` and make sure its command is on `PATH`. Install FFmpeg as well @@ -109,5 +204,5 @@ WHERE youtube_download_job_id = 123 Run the database and worker tests without downloading any videos: ```sh -python3 -m unittest test.youtube_download_job_test test.youtube_download_web_test -v +python3 -m unittest test.youtube_download_job_test test.youtube_download_web_test test.upload_video_test test.upload_photo_test test.player_test -v ``` \ No newline at end of file diff --git a/TODO.md b/TODO.md index 367dbb3..77f99aa 100644 --- a/TODO.md +++ b/TODO.md @@ -2,8 +2,8 @@ Sanctuary Commander is the planned successor to Video Commander: a simple, web-based interface for managing sanctuary TVs and displaying dynamically added -media. The current implementation provides the web interface and media-storage -foundation; playback and device control are still future work. +media. The current implementation provides the web interface, media storage, and +an FFplay-based player; playback UI controls and device control are still future work. ## Completed foundations @@ -12,7 +12,9 @@ foundation; playback and device control are still future work. - [x] Build a Bootstrap-based home page with controls grouped into common tools, playback, and media submission. - [x] Create the configured upload directory automatically when the server starts. -- [x] Implement static-image uploads that save a file and create a media record. +- [x] Upload named static images (up to 100MB) to the configurable `Images` folder, + show progress and navigation warnings, and return home after saving the file + and media record. - [x] Add browser-side upload progress reporting and basic upload error feedback. - [x] Implement stream registration with a display name and URL. - [x] Provide a SQLite database wrapper and a database initialization script. @@ -36,10 +38,13 @@ foundation; playback and device control are still future work. ## Playback and media preparation -- [ ] Implement FFPlay-based video and audio playback. -- [ ] Display uploaded static images. -- [ ] Play registered streams and apply stored playback options. -- [ ] Support uploading and playing local video files. +- [x] Implement fullscreen FFPlay-based playback with error-only FFplay logging. +- [x] Display uploaded static images when selected as active or default media. +- [x] Play registered stream URIs using the player. +- [ ] Apply compatible stored playback options without overriding fullscreen or logging rules. +- [x] Upload named local video files (up to 5GB) to the shared video storage folder, + show upload progress and navigation warnings, and return home after saving. +- [x] Play uploaded local video files when selected as active or default media. - [x] Download YouTube videos ahead of time for later playback using queued jobs. - [x] Implement a download worker that updates job status from `pending` to `downloading` to `downloaded` after the file is saved successfully. @@ -58,7 +63,9 @@ foundation; playback and device control are still future work. the existing `media_preparing` flag; do not restore the old preparation table. - [ ] Implement background media preparation using the new tracking approach. - [ ] Surface preparation status in the web interface. -- [ ] Track active and default media and implement their intended behavior. +- [x] Poll active/default media every two seconds, prioritizing active media and + falling back to default media or a fullscreen black screen. +- [ ] Add web controls for changing active and default media. - [ ] Implement the Disable Video and Blackout Screen controls. - [ ] Detect USB media and make it available for playback. diff --git a/blueprints/home/home.html b/blueprints/home/home.html index b5b124d..18a9f61 100644 --- a/blueprints/home/home.html +++ b/blueprints/home/home.html @@ -31,7 +31,7 @@ Configure a Stream
- + Upload a Video Get Video from YouTube YouTube Download Jobs
diff --git a/blueprints/upload_photo/upload_photo.html b/blueprints/upload_photo/upload_photo.html index 38f7778..bcf3a26 100644 --- a/blueprints/upload_photo/upload_photo.html +++ b/blueprints/upload_photo/upload_photo.html @@ -1,42 +1,45 @@ - + - Video Commander + Upload a Static Image - Sanctuary Commander - - - - + +
-

Upload a Static Photo

+

Upload a Static Image


- - \ No newline at end of file + diff --git a/blueprints/upload_photo/upload_photo.py b/blueprints/upload_photo/upload_photo.py index 7972e7e..7ee2105 100644 --- a/blueprints/upload_photo/upload_photo.py +++ b/blueprints/upload_photo/upload_photo.py @@ -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 \ No newline at end of file + 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) diff --git a/blueprints/upload_video/upload_video.html b/blueprints/upload_video/upload_video.html new file mode 100644 index 0000000..3e8a60c --- /dev/null +++ b/blueprints/upload_video/upload_video.html @@ -0,0 +1,45 @@ + + + + Upload a Video - Sanctuary Commander + + + + + + +
+

Upload a Video

+
+ Home +
+ 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. +
+

Upload one video, up to 5GB ({{ max_video_size }} bytes). Large uploads may take several minutes.

+ + +
+
+
+ + +
+
+ + +
+ +
+
+
+
0%
+
+

Ready to upload.

+
+ + diff --git a/blueprints/upload_video/upload_video.py b/blueprints/upload_video/upload_video.py new file mode 100644 index 0000000..22a7f31 --- /dev/null +++ b/blueprints/upload_video/upload_video.py @@ -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) diff --git a/config.json b/config.json index d9d1547..4953d46 100644 --- a/config.json +++ b/config.json @@ -4,6 +4,7 @@ "name": "scdb.db" }, "upload_location": "uploads", + "image_upload_location": "Images", "youtube_download_location": "Videos", "youtube_download_max_retries": 3 } \ No newline at end of file diff --git a/player.py b/player.py new file mode 100644 index 0000000..4d0f0e0 --- /dev/null +++ b/player.py @@ -0,0 +1,130 @@ +"""Keep the selected database media on screen using a fullscreen FFplay process.""" + +import argparse +import json +import logging +import os +from pathlib import Path +import shutil +import signal +import sqlite3 +import subprocess +import time +from urllib.parse import urlsplit + + +LOGGER = logging.getLogger(__name__) +POLL_INTERVAL = 2 + + +def select_media(db): + """Return (ID, URI), preferring active rows and using the lowest ID to break ties.""" + return db.execute(""" + SELECT media_id, media_uri + FROM media + WHERE media_active = 1 OR media_default = 1 + ORDER BY CASE WHEN media_active = 1 THEN 0 ELSE 1 END, media_id + LIMIT 1 + """).fetchone() + + +def resolve_media_uri(uri, directory): + if not uri or not uri.strip(): + return None + # Preserve network/FFmpeg protocol URLs; anchor legacy relative file paths to config.json. + if urlsplit(uri).scheme: + return uri + return str((Path(directory) / uri).resolve()) + + +class Player: + def __init__(self, directory, error_log, executable='ffplay'): + self.directory = Path(directory) + self.error_log = error_log + self.executable = executable + self.process = None + self.selection = object() # Distinct from the initial blank-screen selection. + + def update(self, media): + uri = resolve_media_uri(media[1], self.directory) if media else None + selection = (media[0], uri) if media else None + if selection == self.selection and self.process is not None and self.process.poll() is None: + return + self.stop() + command = [self.executable, '-hide_banner', '-loglevel', 'error', '-nostats', '-fs'] + if uri is None: + # Keep a real fullscreen black window open instead of exposing the desktop. + command += ['-f', 'lavfi', '-i', 'color=c=black:s=1920x1080:r=1'] + else: + command += ['-i', uri] + self.process = subprocess.Popen( + command, + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=self.error_log, + env={**os.environ, 'AV_LOG_FORCE_NOCOLOR': '1'} + ) + self.selection = selection + LOGGER.info('Displaying %s', uri if uri is not None else 'a blank screen') + + def stop(self): + if self.process is None: + return + if self.process.poll() is None: + self.process.terminate() + try: + self.process.wait(timeout=2) + except subprocess.TimeoutExpired: + self.process.kill() + self.process.wait() + else: + self.process.wait() + self.process = None + + +def request_shutdown(signum, frame): + raise KeyboardInterrupt + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--config', type=Path, default=Path(__file__).with_name('config.json')) + parser.add_argument('--log-file', type=Path, help='FFplay error log (default: ffplay.log beside config.json)') + args = parser.parse_args() + config_path = args.config.resolve() + with config_path.open() as config_file: + config = json.load(config_file) + if config['database']['type'].casefold() != 'sqlite': + parser.error('The player currently supports only SQLite') + database = (config_path.parent / config['database']['name']).resolve() + if not database.is_file(): + parser.error('Database does not exist; run sc_database_generator.py first') + executable = shutil.which('ffplay') + if executable is None: + parser.error('ffplay must be installed and available on PATH') + log_path = args.log_file or config_path.parent / 'ffplay.log' + logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s') + # Read-only mode prevents accidentally modifying the catalog or creating an empty DB. + db = sqlite3.connect(database.as_uri() + '?mode=ro', uri=True, timeout=1) + previous_handler = signal.signal(signal.SIGTERM, request_shutdown) + try: + with log_path.open('ab') as error_log: + player = Player(config_path.parent, error_log, executable) + try: + while True: + try: + player.update(select_media(db)) + except (sqlite3.Error, OSError, ValueError): + LOGGER.exception('Unable to update playback; retrying in two seconds') + time.sleep(POLL_INTERVAL) + finally: + player.stop() + except KeyboardInterrupt: + LOGGER.info('Player stopped') + finally: + db.close() + signal.signal(signal.SIGTERM, previous_handler) + + +if __name__ == '__main__': + main() diff --git a/sc_webserver.py b/sc_webserver.py index 8d56527..d78123f 100644 --- a/sc_webserver.py +++ b/sc_webserver.py @@ -1,6 +1,7 @@ from flask import Flask, g from blueprints.home.home import home_bp from blueprints.upload_photo.upload_photo import upload_photo_bp +from blueprints.upload_video.upload_video import upload_video_bp from blueprints.configure_stream.configure_stream import configure_stream_bp from blueprints.youtube_download.youtube_download import youtube_download_bp import os @@ -15,8 +16,10 @@ if not os.path.exists(config_json["upload_location"]): app = Flask(__name__) app.config["MAX_CONTENT_LENGTH"] = 3 * (1024 ** 3) app.config["config"] = config_json +app.config["CONFIG_DIRECTORY"] = os.path.dirname(os.path.abspath("config.json")) app.register_blueprint(home_bp) app.register_blueprint(upload_photo_bp) +app.register_blueprint(upload_video_bp) app.register_blueprint(configure_stream_bp) app.register_blueprint(youtube_download_bp) diff --git a/static/upload_media.js b/static/upload_media.js new file mode 100644 index 0000000..449cf32 --- /dev/null +++ b/static/upload_media.js @@ -0,0 +1,97 @@ +const form = document.querySelector('form[data-media-upload]') +const fields = document.getElementById('uploadFields') +const fileInput = form.elements.namedItem('files[]') +const nameInput = form.elements.namedItem('name') +const kind = form.dataset.mediaKind +const sizeError = `The ${kind} must be no larger than ${form.dataset.limitLabel}.` +const progress = document.getElementById('uploadProgress') +const bar = document.getElementById('uploadProgressBar') +const statusText = document.getElementById('uploadStatus') +const errorBox = document.getElementById('uploadError') +let uploading = false + +function warnBeforeLeaving(event) { + event.preventDefault() + event.returnValue = '' +} + +function setProgress(percent) { + bar.style.width = `${percent}%` + bar.textContent = `${percent}%` + progress.setAttribute('aria-valuenow', percent) +} + +function failUpload(message) { + uploading = false + fields.disabled = false + window.removeEventListener('beforeunload', warnBeforeLeaving) + errorBox.textContent = message + errorBox.hidden = false + statusText.textContent = 'Upload not completed. Please try again.' +} + +form.addEventListener('submit', function(event) { + event.preventDefault() + if (uploading) return + errorBox.hidden = true + const file = fileInput.files[0] + if (!nameInput.value.trim()) { + failUpload(`Please enter a name for the ${kind}.`) + return + } + if (!file || file.size === 0) { + failUpload(`Please select a non-empty ${kind} file.`) + return + } + if (file.size > Number(form.dataset.maxSize)) { + failUpload(sizeError) + return + } + + const data = new FormData(form) + data.set('name', nameInput.value.trim()) + uploading = true + fields.disabled = true + setProgress(0) + statusText.textContent = 'Uploading… Do not leave this page.' + window.addEventListener('beforeunload', warnBeforeLeaving) + + const xhr = new XMLHttpRequest() + xhr.open('POST', form.action) + xhr.responseType = 'json' + xhr.upload.onprogress = function(event) { + if (event.lengthComputable) { + setProgress(Math.min(100, Math.floor(event.loaded / event.total * 100))) + } else { + statusText.textContent = 'Uploading… Please wait and do not leave this page.' + } + } + xhr.upload.onload = function() { + setProgress(100) + statusText.textContent = `Transfer complete. Waiting for the server to save the ${kind}…` + } + xhr.onload = function() { + if (xhr.status === 200 && xhr.response && xhr.response.status === 'SUCCESS') { + uploading = false + window.removeEventListener('beforeunload', warnBeforeLeaving) + statusText.textContent = 'Saved. Returning to the homepage…' + window.location.href = form.dataset.homeUrl + } else { + const message = xhr.response && xhr.response.error + failUpload(message || (xhr.status === 413 + ? sizeError + : 'The server could not save the upload. Please try again.')) + } + } + xhr.onerror = function() { + failUpload('The upload connection failed. Check your connection before trying again.') + } + xhr.onabort = function() { + failUpload('The upload was cancelled.') + } + try { + xhr.send(data) + } catch (error) { + failUpload('Unable to start the upload. Please try again.') + } +}) diff --git a/test/player_test.py b/test/player_test.py new file mode 100644 index 0000000..d55bc74 --- /dev/null +++ b/test/player_test.py @@ -0,0 +1,194 @@ +from contextlib import closing +from io import BytesIO +import json +from pathlib import Path +import signal +import sqlite3 +import subprocess +import tempfile +import unittest +from unittest.mock import Mock, patch + +from player import Player, main, resolve_media_uri, select_media + + +class MediaSelectionTest(unittest.TestCase): + def setUp(self): + self.db = sqlite3.connect(':memory:') + self.addCleanup(self.db.close) + self.db.execute(''' + CREATE TABLE media ( + media_id INTEGER PRIMARY KEY, media_uri TEXT, + media_active INTEGER DEFAULT 0, media_default INTEGER DEFAULT 0 + ) + ''') + + def add_media(self, uri, active=0, default=0): + return self.db.execute( + 'INSERT INTO media (media_uri, media_active, media_default) VALUES (?, ?, ?)', + [uri, active, default] + ).lastrowid + + def test_no_selection_when_table_empty_or_only_unmarked_rows(self): + self.assertIsNone(select_media(self.db)) + self.add_media('unselected.mp4') + self.assertIsNone(select_media(self.db)) + + def test_active_takes_precedence_over_default(self): + self.add_media('default.mp4', default=1) + active = self.add_media('active.mp4', active=1) + self.assertEqual(select_media(self.db), (active, 'active.mp4')) + + def test_lowest_id_wins_for_multiple_active_or_default_rows(self): + first = self.add_media('first.mp4', default=1) + self.add_media('second.mp4', default=1) + self.assertEqual(select_media(self.db), (first, 'first.mp4')) + self.db.execute('UPDATE media SET media_active = 1') + self.assertEqual(select_media(self.db), (first, 'first.mp4')) + + def test_selection_tracks_external_database_changes(self): + with tempfile.TemporaryDirectory() as directory: + database = Path(directory) / 'media.db' + with closing(sqlite3.connect(database)) as writer: + self.db.backup(writer) + writer.execute("INSERT INTO media VALUES (1, 'default.mp4', 0, 1)") + writer.commit() + with closing(sqlite3.connect(database.as_uri() + '?mode=ro', uri=True)) as reader: + self.assertEqual(select_media(reader), (1, 'default.mp4')) + writer.execute("INSERT INTO media VALUES (2, 'active.mp4', 1, 0)") + writer.commit() + self.assertEqual(select_media(reader), (2, 'active.mp4')) + writer.execute('UPDATE media SET media_active = 0') + writer.commit() + self.assertEqual(select_media(reader), (1, 'default.mp4')) + writer.execute('UPDATE media SET media_default = 0') + writer.commit() + self.assertIsNone(select_media(reader)) + + def test_null_active_flag_does_not_change_default_order(self): + first = self.add_media('first.mp4', active=None, default=1) + self.add_media('second.mp4', default=1) + self.assertEqual(select_media(self.db), (first, 'first.mp4')) + + +class PlayerProcessTest(unittest.TestCase): + def setUp(self): + self.error_log = BytesIO() + self.processes = [] + self.spawn = patch('player.subprocess.Popen', side_effect=self.make_process).start() + self.addCleanup(patch.stopall) + self.player = Player('/project', self.error_log) + self.addCleanup(self.player.stop) + + def make_process(self, *args, **kwargs): + process = Mock() + process.poll.return_value = None + self.processes.append(process) + return process + + def test_media_is_fullscreen_and_only_errors_go_to_log(self): + self.player.update((1, 'Videos/local video.mp4')) + command = self.spawn.call_args.args[0] + self.assertEqual(command, ['ffplay', '-hide_banner', '-loglevel', 'error', + '-nostats', '-fs', '-i', '/project/Videos/local video.mp4']) + self.assertIs(self.spawn.call_args.kwargs['stderr'], self.error_log) + self.assertEqual(self.spawn.call_args.kwargs['stdout'], subprocess.DEVNULL) + self.assertEqual(self.spawn.call_args.kwargs['stdin'], subprocess.DEVNULL) + self.assertNotIn('shell', self.spawn.call_args.kwargs) + + def test_blank_screen_is_a_live_fullscreen_black_source(self): + self.player.update(None) + command = self.spawn.call_args.args[0] + self.assertIn('-fs', command) + self.assertEqual(command[-4:], ['-f', 'lavfi', '-i', 'color=c=black:s=1920x1080:r=1']) + self.player.update(None) + self.assertEqual(self.spawn.call_count, 1) + + def test_unchanged_media_does_not_restart(self): + self.player.update((1, 'https://example.com/stream')) + self.player.update((1, 'https://example.com/stream')) + self.assertEqual(self.spawn.call_count, 1) + self.processes[0].terminate.assert_not_called() + + def test_media_or_uri_change_stops_old_process_before_starting_new(self): + self.player.update((1, 'first.mp4')) + old_process = self.processes[0] + def start_after_stop(*args, **kwargs): + old_process.terminate.assert_called_once() + old_process.wait.assert_called_once_with(timeout=2) + return self.make_process(*args, **kwargs) + self.spawn.side_effect = start_after_stop + self.player.update((2, 'second.mp4')) + self.assertEqual(self.spawn.call_count, 2) + self.spawn.side_effect = self.make_process + self.player.update((2, 'replacement.mp4')) + self.assertEqual(self.spawn.call_count, 3) + self.assertEqual(self.spawn.call_args.args[0][-1], '/project/replacement.mp4') + + def test_clearing_selection_switches_to_black(self): + self.player.update((1, 'video.mp4')) + self.player.update(None) + self.processes[0].terminate.assert_called_once() + self.assertIn('lavfi', self.spawn.call_args.args[0]) + + def test_missing_uri_displays_black(self): + for uri in (None, '', ' '): + self.player.update((1, uri)) + self.assertIn('lavfi', self.spawn.call_args.args[0]) + + def test_unexpected_exit_restarts_selected_media(self): + self.player.update((1, 'video.mp4')) + self.processes[0].poll.return_value = 1 + self.player.update((1, 'video.mp4')) + self.assertEqual(self.spawn.call_count, 2) + self.processes[0].wait.assert_called_once() + self.processes[0].terminate.assert_not_called() + + def test_stop_escalates_to_kill_if_ffplay_does_not_exit(self): + self.player.update(None) + process = self.processes[0] + process.wait.side_effect = [subprocess.TimeoutExpired('ffplay', 2), 0] + self.player.stop() + process.terminate.assert_called_once() + process.kill.assert_called_once() + self.assertEqual(process.wait.call_count, 2) + self.assertIsNone(self.player.process) + + def test_protocol_uris_are_preserved(self): + self.assertEqual(resolve_media_uri('https://example.com/video?a=1&b=2', '/project'), + 'https://example.com/video?a=1&b=2') + self.assertEqual(resolve_media_uri('/storage/video.mp4', '/project'), '/storage/video.mp4') + + +class PlayerMainTest(unittest.TestCase): + @patch('player.logging.basicConfig') + def test_main_polls_every_two_seconds_and_closes_on_shutdown(self, configure_logging): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + with closing(sqlite3.connect(root / 'media.db')) as db: + db.execute('CREATE TABLE media (media_id INTEGER, media_uri TEXT, media_active INTEGER, media_default INTEGER)') + (root / 'config.json').write_text(json.dumps({ + 'database': {'type': 'SQLite', 'name': 'media.db'} + })) + with patch('sys.argv', ['player.py', '--config', str(root / 'config.json')]), \ + patch('player.shutil.which', return_value='/usr/bin/ffplay'), \ + patch('player.Player') as player_class, \ + patch('player.signal.signal') as handler, \ + patch('player.time.sleep', side_effect=[None, KeyboardInterrupt]) as sleep: + with self.assertLogs('player', level='INFO'): + main() + instance = player_class.return_value + self.assertEqual(instance.update.call_count, 2) + instance.update.assert_called_with(None) + self.assertEqual(sleep.call_args_list[0].args, (2,)) + self.assertEqual(sleep.call_args_list[1].args, (2,)) + instance.stop.assert_called_once() + self.assertEqual(player_class.call_args.args[0], root) + self.assertTrue(player_class.call_args.args[1].closed) + self.assertTrue((root / 'ffplay.log').is_file()) + self.assertEqual(handler.call_args_list[0].args[0], signal.SIGTERM) + self.assertEqual(handler.call_count, 2) + + +if __name__ == '__main__': + unittest.main() diff --git a/test/upload_photo_test.py b/test/upload_photo_test.py new file mode 100644 index 0000000..0e24e48 --- /dev/null +++ b/test/upload_photo_test.py @@ -0,0 +1,146 @@ +from contextlib import closing +from io import BytesIO +import base64 +import json +import os +from pathlib import Path +import runpy +import sqlite3 +import subprocess +import sys +import tempfile +import unittest +from unittest.mock import patch + +from blueprints.upload_photo.upload_photo import MAX_IMAGE_SIZE + + +ROOT = Path(__file__).resolve().parents[1] +PNG = base64.b64decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aK1cAAAAASUVORK5CYII=') + + +class UploadPhotoTest(unittest.TestCase): + def setUp(self): + self.directory = tempfile.TemporaryDirectory() + self.addCleanup(self.directory.cleanup) + self.workdir = Path(self.directory.name) + self.database = self.workdir / 'test.db' + self.storage = self.workdir / 'Images' + (self.workdir / 'config.json').write_text(json.dumps({ + 'database': {'type': 'SQLite', 'name': str(self.database)}, + 'upload_location': str(self.workdir / 'uploads') + })) + subprocess.run([sys.executable, str(ROOT / 'sc_database_generator.py')], + cwd=self.workdir, check=True, capture_output=True) + original = Path.cwd() + try: + os.chdir(self.workdir) + self.app = runpy.run_path(str(ROOT / 'sc_webserver.py'))['app'] + finally: + os.chdir(original) + self.app.config['TESTING'] = True + self.client = self.app.test_client() + + def post_image(self, content=PNG, name='Image', filename='photo.png'): + return self.client.post('/upload/photo', data={ + 'name': name, 'files[]': (BytesIO(content), filename) + }) + + def assert_no_files_or_records(self): + self.assertEqual(list(self.storage.glob('*')), []) + with closing(sqlite3.connect(self.database)) as db: + self.assertEqual(db.execute('SELECT COUNT(*) FROM media').fetchone(), (0,)) + + def test_page_and_navigation(self): + self.assertIn(b'/upload/photo', self.client.get('/').data) + response = self.client.get('/upload/photo') + self.assertEqual(response.status_code, 200) + self.assertEqual(MAX_IMAGE_SIZE, 100 * 1024 ** 2) + for text in (str(MAX_IMAGE_SIZE).encode(), b'Do not leave this page', + b'role="progressbar"', b'upload_media.js', b'data-media-kind="image"', + b'data-limit-label="100MB"'): + self.assertIn(text, response.data) + + def test_upload_saves_image_and_display_name(self): + response = self.post_image(name=' Welcome image ', filename='PHOTO.PNG') + self.assertEqual(response.status_code, 200) + self.assertEqual(response.json['status'], 'SUCCESS') + with closing(sqlite3.connect(self.database)) as db: + name, uri = db.execute('SELECT media_name, media_uri FROM media').fetchone() + self.assertEqual(name, 'Welcome image') + self.assertEqual(Path(uri).parent, self.storage) + self.assertEqual(Path(uri).read_bytes(), PNG) + self.assertEqual(Path(uri).suffix, '.png') + self.assertEqual(len(list(self.storage.iterdir())), 1) + self.assertFalse((self.workdir / 'Videos').exists()) + + def test_configurable_folder(self): + self.app.config['config']['image_upload_location'] = 'CustomImages' + self.assertEqual(self.post_image().status_code, 200) + self.assertEqual(len(list((self.workdir / 'CustomImages').iterdir())), 1) + self.assertFalse(self.storage.exists()) + + def test_invalid_submissions(self): + cases = [({}, 400), ({'name': 'Image'}, 400), + ({'name': ' ', 'files[]': (BytesIO(PNG), 'photo.png')}, 400), + ({'name': 'Image', 'files[]': (BytesIO(b''), 'photo.png')}, 400), + ({'name': 'Image', 'files[]': (BytesIO(b'code'), 'script.svg')}, 400), + ({'name': 'Image', 'files[]': (BytesIO(b'video'), 'clip.mp4')}, 400), + ({'name': 'Image', 'files[]': [(BytesIO(PNG), 'a.png'), (BytesIO(PNG), 'b.png')]}, 400)] + for data, status in cases: + with self.subTest(data=data): + response = self.client.post('/upload/photo', data=data) + self.assertEqual(response.status_code, status) + self.assertEqual(response.json['status'], 'FAILED') + self.assert_no_files_or_records() + + def test_file_limit_exact_boundary_and_one_byte_over(self): + with patch('blueprints.upload_photo.upload_photo.MAX_IMAGE_SIZE', len(PNG)): + self.assertEqual(self.post_image(content=PNG + b'x').status_code, 413) + self.assert_no_files_or_records() + self.assertEqual(self.post_image().status_code, 200) + + def test_request_limit_rejects_oversized_body_with_json(self): + with patch('blueprints.upload_photo.upload_photo.MAX_IMAGE_SIZE', 16): + with patch('blueprints.upload_photo.upload_photo.MULTIPART_OVERHEAD', 1024): + response = self.post_image(content=b'x' * 2048) + self.assertEqual(response.status_code, 413) + self.assertEqual(response.json['status'], 'FAILED') + self.assertIn('100MB', response.json['error']) + self.assert_no_files_or_records() + + def test_filenames_and_names_cannot_escape_or_overwrite_storage(self): + for _ in range(2): + self.assertEqual(self.post_image(name='../../Display name', filename='../../photo.png').status_code, 200) + paths = list(self.storage.iterdir()) + self.assertEqual(len(paths), 2) + self.assertTrue(all(path.name.startswith('upload-') for path in paths)) + self.assertFalse((self.workdir / 'photo.png').exists()) + + def test_database_failure_removes_saved_file(self): + with patch('utilities.database.database.Database.insert', side_effect=sqlite3.OperationalError('Test failure')): + with self.assertLogs(self.app.logger, level='ERROR'): + response = self.post_image() + self.assertEqual(response.status_code, 500) + self.assert_no_files_or_records() + + def test_storage_failure_returns_useful_error(self): + self.storage.write_text('Not a directory') + with self.assertLogs(self.app.logger, level='ERROR'): + response = self.post_image() + self.assertEqual(response.status_code, 500) + self.assertEqual(response.json['status'], 'FAILED') + + def test_old_media_records_remain_unchanged(self): + with closing(sqlite3.connect(self.database)) as db: + db.execute('INSERT INTO media (media_name, media_uri) VALUES (?, ?)', + ['Old image', 'uploads/Old image/photo.png']) + db.commit() + self.assertEqual(self.post_image().status_code, 200) + with closing(sqlite3.connect(self.database)) as db: + self.assertEqual(db.execute('SELECT media_name, media_uri FROM media WHERE media_id = 1').fetchone(), + ('Old image', 'uploads/Old image/photo.png')) + + +if __name__ == '__main__': + unittest.main() diff --git a/test/upload_video_test.py b/test/upload_video_test.py new file mode 100644 index 0000000..92d9abb --- /dev/null +++ b/test/upload_video_test.py @@ -0,0 +1,135 @@ +from contextlib import closing +from io import BytesIO +import json +import os +from pathlib import Path +import runpy +import sqlite3 +import subprocess +import sys +import tempfile +import unittest +from unittest.mock import patch + +from blueprints.upload_video.upload_video import MAX_VIDEO_SIZE + + +ROOT = Path(__file__).resolve().parents[1] + + +class UploadVideoTest(unittest.TestCase): + def setUp(self): + self.directory = tempfile.TemporaryDirectory() + self.addCleanup(self.directory.cleanup) + self.workdir = Path(self.directory.name) + self.database = self.workdir / 'test.db' + self.storage = self.workdir / 'Videos' + (self.workdir / 'config.json').write_text(json.dumps({ + 'database': {'type': 'SQLite', 'name': str(self.database)}, + 'upload_location': str(self.workdir / 'uploads') + })) + subprocess.run([sys.executable, str(ROOT / 'sc_database_generator.py')], + cwd=self.workdir, check=True, capture_output=True) + original = Path.cwd() + try: + os.chdir(self.workdir) + self.app = runpy.run_path(str(ROOT / 'sc_webserver.py'))['app'] + finally: + os.chdir(original) + self.app.config['TESTING'] = True + self.client = self.app.test_client() + + def post_video(self, content=b'example-video', name='Video', filename='clip.mp4'): + return self.client.post('/upload/video', data={ + 'name': name, 'files[]': (BytesIO(content), filename) + }) + + def assert_no_files_or_records(self): + self.assertEqual(list(self.storage.glob('*')), []) + with closing(sqlite3.connect(self.database)) as db: + self.assertEqual(db.execute('SELECT COUNT(*) FROM media').fetchone(), (0,)) + + def test_page_and_navigation(self): + self.assertIn(b'/upload/video', self.client.get('/').data) + response = self.client.get('/upload/video') + self.assertEqual(response.status_code, 200) + self.assertIn(str(MAX_VIDEO_SIZE).encode(), response.data) + self.assertIn(b'Do not leave this page', response.data) + self.assertIn(b'role="progressbar"', response.data) + self.assertIn(b'upload_media.js', response.data) + + def test_upload_saves_video_and_display_name(self): + response = self.post_video(name=' Sunday video ') + self.assertEqual(response.status_code, 200) + self.assertEqual(response.json['status'], 'SUCCESS') + with closing(sqlite3.connect(self.database)) as db: + name, uri = db.execute('SELECT media_name, media_uri FROM media').fetchone() + self.assertEqual(name, 'Sunday video') + self.assertEqual(Path(uri).parent, self.storage) + self.assertEqual(Path(uri).read_bytes(), b'example-video') + self.assertEqual(Path(uri).suffix, '.mp4') + self.assertEqual(len(list(self.storage.iterdir())), 1) + + def test_uses_same_configured_folder_as_worker(self): + self.app.config['config']['youtube_download_location'] = 'CustomVideos' + self.assertEqual(self.post_video().status_code, 200) + self.assertEqual(len(list((self.workdir / 'CustomVideos').iterdir())), 1) + self.assertFalse(self.storage.exists()) + + def test_invalid_submissions(self): + cases = [({}, 400), ({'name': 'Video'}, 400), + ({'name': ' ', 'files[]': (BytesIO(b'video'), 'clip.mp4')}, 400), + ({'name': 'Video', 'files[]': (BytesIO(b''), 'clip.mp4')}, 400), + ({'name': 'Video', 'files[]': (BytesIO(b'code'), 'script.py')}, 400), + ({'name': 'Video', 'files[]': [(BytesIO(b'a'), 'a.mp4'), (BytesIO(b'b'), 'b.mp4')]}, 400)] + for data, status in cases: + with self.subTest(data=data): + response = self.client.post('/upload/video', data=data) + self.assertEqual(response.status_code, status) + self.assertEqual(response.json['status'], 'FAILED') + self.assert_no_files_or_records() + + def test_file_limit_exact_boundary_and_one_byte_over(self): + with patch('blueprints.upload_video.upload_video.MAX_VIDEO_SIZE', 16): + response = self.post_video(content=b'x' * 17) + self.assertEqual(response.status_code, 413) + self.assertEqual(response.json['status'], 'FAILED') + self.assert_no_files_or_records() + self.assertEqual(self.post_video(content=b'x' * 16).status_code, 200) + + def test_request_limit_rejects_oversized_body_with_json(self): + with patch('blueprints.upload_video.upload_video.MAX_VIDEO_SIZE', 16): + with patch('blueprints.upload_video.upload_video.MULTIPART_OVERHEAD', 1024): + response = self.post_video(content=b'x' * 2048) + self.assertEqual(response.status_code, 413) + self.assertEqual(response.json['status'], 'FAILED') + self.assert_no_files_or_records() + + def test_video_limit_does_not_change_other_routes(self): + self.assertEqual(self.app.config['MAX_CONTENT_LENGTH'], 3 * 1024 ** 3) + + def test_filenames_and_names_cannot_escape_or_overwrite_storage(self): + for _ in range(2): + self.assertEqual(self.post_video(name='../../Display name', filename='../../clip.mp4').status_code, 200) + paths = list(self.storage.iterdir()) + self.assertEqual(len(paths), 2) + self.assertTrue(all(path.name.startswith('upload-') for path in paths)) + self.assertFalse((self.workdir / 'clip.mp4').exists()) + + def test_database_failure_removes_saved_file(self): + with patch('utilities.database.database.Database.insert', side_effect=sqlite3.OperationalError('Test failure')): + with self.assertLogs(self.app.logger, level='ERROR'): + response = self.post_video() + self.assertEqual(response.status_code, 500) + self.assert_no_files_or_records() + + def test_storage_failure_returns_useful_error(self): + self.storage.write_text('Not a directory') + with self.assertLogs(self.app.logger, level='ERROR'): + response = self.post_video() + self.assertEqual(response.status_code, 500) + self.assertEqual(response.json['status'], 'FAILED') + + +if __name__ == '__main__': + unittest.main()