15 KiB
Sanctuary Commander
Sanctuary Commander will be the successor to Video Commander. With built in functionality for preparing dynamically submitted content, rather than working from a static configuration file.
The end goal is to have web based control of TV power, volume, input, and displayed content from a single location, while having the ability to pre-download Youtube video content, upload videos and pictures for display later, and keep the interface as simple as possible for the less technically adept.
Simple Goal List
- HomeAssistant Integration for TV Power, Volume, and Input Control
- FFPlay based playback of video and audio
- Ahead of time downloading of Youtube video content
- 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:
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:
- The lowest-ID row with
media_active = 1. - If none is active, the lowest-ID row with
media_default = 1. - 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.
Use Play Media from the home page to select an item in the unified library. Alternatively, set selection flags directly in SQLite. For example, select media ID 3 without temporarily leaving several active rows:
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.
Media library and playback selection
Open Play Media from the homepage, or visit /media. All media types share
one page, with a Play button per item and image/video/stream icons. Clicking
Play clears the previous active selection and activates the new item in a single
database transaction; default flags are preserved. The separate player picks up
the change on its next two-second check.
A green border and Selected badge show the item selected for playback, including the default when no active item exists. The selection banner and badges refresh every two seconds. These indicators reflect the database's requested selection, not proof that FFplay is running or that a stream is healthy. Refresh the page to load newly added media or edited names/sources. Empty sources cannot be selected using the Play button.
Local images and videos receive lazy-loaded, cached PNG thumbnails generated by
FFmpeg (the first video frame, scaled to at most 240×135). Cache files live in
.thumbnails/ beside config.json and are excluded from Git. Source path, size,
and modification time determine the cache key; deleting this folder is safe and
causes previews to regenerate. Streams use an icon without opening a network
connection. Missing FFmpeg, unsupported files, or generation failures also fall
back to the type icon. Thumbnail generation has a ten-second timeout.
Previews are restricted to files inside configured image, video, and legacy upload storage folders, including custom storage locations. Symlinks outside those folders are rejected, and FFmpeg's preview input is restricted to local file/pipe protocols. A local file outside those folders can still be selected for playback but has no preview. Media types are inferred from local filename extensions or URL schemes; no schema changes are required.
As with uploads, keep this interface on a trusted network until authentication and broader access controls are implemented.
Deleting media
Choose Delete beneath an item in /media. A separate confirmation page names
the item and explains whether its stored file will be deleted or retained.
Nothing is deleted by opening that page; use Cancel to go back or Yes,
delete media to confirm. If the record or file changed since the prompt, it
must be reviewed and confirmed again. This works without JavaScript.
Confirmed deletion removes the media row and its playback options. Local files
inside the configured image, video, and legacy upload folders are removed to
free storage, including files downloaded from YouTube. A file used by another
media row is retained until its last reference is deleted. Streams, missing
files, paths outside managed storage, directories, and symbolic links only lose
their database record; no remote source, outside file, or directory tree is
deleted. YouTube job history remains unchanged.
Deleting active/default media lets the player choose the next active/default item or black on its next check. An open player process can retain the deleted file's disk space until it releases that file. Cached thumbnails for the item are also removed (including the current legacy-format thumbnail, if present).
A local file is temporarily renamed in place before the database transaction
commits. Database errors restore it rather than destroying it. If final file
cleanup fails after commit, the page explicitly reports that storage was not
freed; the server log identifies the retained .deleting-* file for an
administrator to remove. A forced shutdown during deletion can also leave a
.deleting-* file: check the database before restoring its original filename
(if the record remains) or removing it (if the deletion committed).
Submission validation
All new image, video, stream, and YouTube submissions require a nonblank media name of at most 120 characters, without control characters. Surrounding spaces are removed. Names must be unique across the media catalog and pending or currently downloading YouTube jobs, compared case-insensitively after Unicode normalization and trimming. Failed jobs do not reserve names; completed jobs normally have a catalog entry that does. Existing records are not renamed or removed. This rule is enforced by the app and worker when writing under SQLite transactions, not by a database constraint; direct SQL can bypass it.
Stream registration accepts HTTP, HTTPS, RTSP, RTMP, RTMPS, UDP, and TCP network URLs, including local-network hosts. YouTube requests require a supported individual video URL. Validation checks syntax, not network reachability.
Image and video uploads require FFprobe and FFmpeg on PATH for local-only, time-limited content validation. Extensions and client MIME types alone are not trusted; a video stream and a decodable first frame are required. Full files are not decoded or scanned for malware. Missing validation tools, storage issues, database failures, and invalid fields produce user-facing errors without saving an incomplete media entry. Retrying a failed upload starts it from the beginning.
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. Before saving, FFprobe checks for a
video stream and FFmpeg decodes its first frame; the upload does not transcode the
file or guarantee the rest of the video is valid.
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 checked against their extensions and decoded for validation. Images may be
animated, but only the first frame is checked; dimensions are limited to 50
megapixels. 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
for downloads that need video/audio merging or other postprocessing. The worker
uses Python's standard library; it does not need Flask.
From the project directory, initialize or upgrade the database, then start the worker:
python3 sc_database_generator.py
python3 youtube_downloader.py
The initializer requires Python 3.12 or newer (the SQLite wrapper uses
Connection.autocommit). It preserves existing jobs when adding the media-name
and retry-count columns and upgrading the allowed statuses. Existing jobs start
with a retry count of zero. Stop running workers before upgrading the database.
The worker polls every five seconds when idle or after a failed attempt;
use --poll-interval 10 to change that delay, or --config /path/to/config.json
to select another configuration file.
config.json includes "youtube_download_location": "Videos". The folder is
created automatically. The worker resolves relative storage and database paths
against the configuration file's directory. Downloaded files are named
job-<id>.<extension> to avoid collisions and keep display names out of file paths.
The default Videos/ folder is excluded from Git.
Web interface
Start the Flask app with python3 sc_webserver.py and use the home page's
Get Video from YouTube link, or visit /youtube/download. Enter a media name
and a YouTube video URL to queue a job. Invalid submissions show an error without
creating a job; successful submissions redirect to /youtube/jobs.
The jobs page shows pending, downloading, and failed jobs by default, including each job's name, URL, status, and failed-attempt count. Check Include completed jobs and click Update List to also show downloaded jobs. Refresh the page to see worker updates. Both pages are linked from the home screen.
The download worker must run separately from Flask to process requests; submitting a form only adds a pending job. As with the existing upload endpoints, keep this interface on a trusted network until access controls are implemented.
Alternatively, queue a job using SQL against scdb.db:
INSERT INTO youtube_download_job (
youtube_download_job_url,
youtube_download_job_media_name
) VALUES (
'https://www.youtube.com/watch?v=VIDEO_ID',
'Desired button name'
);
Jobs default to pending. The worker claims the oldest pending job by ID and
marks it downloading before invoking yt-dlp without a shell interpreter.
After a successful download and postprocessing, it checks that the reported file
exists inside storage, then atomically inserts a media record and marks the job
downloaded. The media record contains the requested display name and the final
absolute file path. For older jobs or blank names, the video's title is used.
No playback-option records are created automatically.
config.json sets "youtube_download_max_retries": 3. This must be a
non-negative integer; zero allows only the initial attempt. Each failed worker
attempt increments the job's persistent youtube_download_job_retry_count.
While the count is at or below the limit, the job returns to pending for retry
after the polling delay. When the count exceeds the limit, its status becomes
failed and the worker ignores it, allowing later jobs to run. With the default
limit, this allows one initial attempt plus three retries (four failed attempts
total). These are worker attempts; yt-dlp may also retry network requests
internally. Successful downloads and Ctrl+C interruptions do not increment the
counter.
To manually retry a failed job with a fresh budget:
UPDATE youtube_download_job
SET youtube_download_job_status = 'pending', youtube_download_job_retry_count = 0
WHERE youtube_download_job_id = 123
AND youtube_download_job_status = 'failed';
Ctrl+C releases an in-flight job, but a forced termination or power loss can leave
it downloading. Once you have confirmed no worker is still handling that job,
reset it manually (this preserves its retry count):
UPDATE youtube_download_job
SET youtube_download_job_status = 'pending'
WHERE youtube_download_job_id = 123
AND youtube_download_job_status = 'downloading';
Run the database and worker tests without downloading any videos:
python3 -m unittest test.youtube_download_job_test test.youtube_download_web_test test.upload_video_test test.upload_photo_test test.player_test test.media_library_test test.submission_validation_test test.media_deletion_test -v