diff --git a/.gitignore b/.gitignore index abd32e8..7c8c923 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,5 @@ -*__pycache__* \ No newline at end of file +*__pycache__* +/Videos/ +/Images/ +/ffplay.log +/.thumbnails/ \ No newline at end of file diff --git a/README.md b/README.md index 962e769..0e5ee3a 100644 --- a/README.md +++ b/README.md @@ -10,4 +10,286 @@ Simple Goal List - 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 \ No newline at end of file +- 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. + +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: + +```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. + +## 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: + +```sh +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-.` 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`: + +```sql +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: + +```sql +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): + +```sql +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: + +```sh +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 +``` \ No newline at end of file diff --git a/TODO.md b/TODO.md new file mode 100644 index 0000000..36cab45 --- /dev/null +++ b/TODO.md @@ -0,0 +1,95 @@ +# Sanctuary Commander TODO + +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, media storage, and +an FFplay-based player with unified playback selection; device control is still future work. + +## Completed foundations + +- [x] Set up a Flask web server with configuration loaded from `config.json`. +- [x] Organize implemented pages into Flask blueprints. +- [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] 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. +- [x] Define the media catalog and weighted playback-option tables. +- [x] Add a YouTube download jobs table storing each URL and its status: + `pending`, `downloading`, `downloaded`, or `failed`. +- [x] Store an optional fullscreen playback flag for registered streams. +- [x] Remove the old preparation and component tables and slideshow scaffolding; + retain the media and playback-option tables and their existing records. + +## Finish the current workflows + +- [x] Link the home page to a unified media library with Play buttons, live selection + indicators, media-type icons, and cached local image/video thumbnails. +- [x] Delete media with a confirmation step, removing records/playback options and + unshared files in managed storage while preserving outside/shared sources. +- [ ] Connect the existing placeholder controls to backend actions. +- [x] Add input validation for media names, duplicate names, stream URLs, and + uploaded files. +- [ ] Ensure upload destinations remain inside the configured upload directory. +- [x] Handle missing form fields, missing files, and storage/database failures + with useful error messages. +- [x] Close request-scoped database connections when requests finish. + +## Playback and media preparation + +- [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. +- [x] Store requested media names on jobs and register successful downloads in the + media catalog using the final local file path. +- [x] Configure download storage (default: `Videos`) and return failed attempts to + pending for retry with logged errors. +- [x] Add a web workflow for submitting YouTube URLs and desired media names. +- [x] List pending, downloading, and failed jobs, with an opt-in checkbox to include + completed jobs. +- [x] Persist per-job retry counts and mark jobs failed once they exceed the + configured retry limit (default: three retries after the initial attempt). +- [ ] Add increasing retry backoff and recovery of jobs left downloading after a + forced termination. +- [ ] Design a new approach to media preparation tracking, including the role of + 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. +- [x] Poll active/default media every two seconds, prioritizing active media and + falling back to default media or a fullscreen black screen. +- [x] Add web controls for changing active media atomically, with status matching + the player's active/default priority. +- [ ] Add web controls for changing default media. +- [ ] Implement the Disable Video and Blackout Screen controls. +- [ ] Detect USB media and make it available for playback. + +## TV and device control + +- [ ] Integrate with Home Assistant. +- [ ] Implement TV power controls. +- [ ] Implement TV volume controls. +- [ ] Implement TV input selection. +- [ ] Connect the home-page TV controls to the integration. + +## End goals and readiness + +- [ ] Provide one browser-based location for TV control and media playback. +- [ ] Let users prepare and submit content dynamically rather than maintaining a + static media configuration file. +- [ ] Keep everyday operation simple for less technically experienced users. +- [ ] Document installation, dependencies, configuration, and normal operation. +- [ ] Add automated coverage for upload, stream-registration, preparation, + playback, and device-control workflows as they are implemented. +- [ ] Define appropriate access controls and a production deployment setup before + exposing upload or device-control endpoints beyond a trusted environment. diff --git a/blueprints/configure_stream/configure_stream.html b/blueprints/configure_stream/configure_stream.html index 6dee3b6..45f4841 100644 --- a/blueprints/configure_stream/configure_stream.html +++ b/blueprints/configure_stream/configure_stream.html @@ -14,17 +14,18 @@ -
+ {% if error %}{% endif %} +
- +
- +
- +
diff --git a/blueprints/configure_stream/configure_stream.py b/blueprints/configure_stream/configure_stream.py index dcf842c..1106ba0 100644 --- a/blueprints/configure_stream/configure_stream.py +++ b/blueprints/configure_stream/configure_stream.py @@ -1,33 +1,44 @@ -from flask import Blueprint, request, render_template, redirect +import sqlite3 + +from flask import Blueprint, request, render_template, redirect, url_for, current_app from utilities.tools import get_db +from utilities.validation import (ValidationError, ensure_name_available, + validate_media_name, valid_stream_url, write_transaction) + configure_stream_bp = Blueprint('configure_stream', __name__, url_prefix='/configure', template_folder='.') + @configure_stream_bp.route('/stream', methods=['GET', 'POST']) def get_page(): - if request.method == "GET": - return render_get() - elif request.method == "POST": - return upload() - - -def render_get(): - return render_template('configure_stream.html'), 200 - -def upload(): - # TODO Input Validation - - new_id = get_db().insert( - "media", - ["media_name", "media_uri"], - [request.form["buttonName"], request.form["streamURL"]] - ) - - if request.form.get("fullScreen", False): - get_db().insert( - "media_playback_option", - ["media_id", "media_playback_option", "media_playback_option_weight"], - [new_id, "-fs", 1] - ) - - return redirect("/") + name = '' + stream_url = '' + fullscreen = True + error = None + status = 200 + if request.method == 'POST': + name = request.form.get('buttonName', '') + stream_url = request.form.get('streamURL', '').strip(' ') + fullscreen = request.form.get('fullScreen') in ('on', '1', 'true') + try: + name = validate_media_name(name) + if not valid_stream_url(stream_url): + raise ValidationError('Enter a valid network stream URL (HTTP, HTTPS, RTSP, RTMP, RTMPS, UDP, or TCP).') + db = get_db() + with write_transaction(db): + ensure_name_available(db.db, name) + new_id = db.insert('media', ['media_name', 'media_uri'], [name, stream_url]) + if fullscreen: + db.insert('media_playback_option', + ['media_id', 'media_playback_option', 'media_playback_option_weight'], + [new_id, '-fs', 1]) + return redirect(url_for('home.root_route'), code=303) + except ValidationError as exception: + error = str(exception) + status = 400 + except sqlite3.Error: + current_app.logger.exception('Unable to save stream') + error = 'Unable to save the stream due to a database error. Please try again.' + status = 503 + return render_template('configure_stream.html', name=name, stream_url=stream_url, + fullscreen=fullscreen, error=error), status diff --git a/blueprints/home/home.html b/blueprints/home/home.html index 05d1193..8cdcd3f 100644 --- a/blueprints/home/home.html +++ b/blueprints/home/home.html @@ -20,20 +20,18 @@

Play Something

- - - + Play Media

Add Something

Upload a Static Image Configure a Stream -
- - + Upload a Video + Get Video from YouTube + YouTube Download Jobs
diff --git a/blueprints/media_library/media_delete.html b/blueprints/media_library/media_delete.html new file mode 100644 index 0000000..780f499 --- /dev/null +++ b/blueprints/media_library/media_delete.html @@ -0,0 +1,34 @@ + + + + Delete Media - Sanctuary Commander + + + + + +
+

Delete Media

+ {% if error %} + + {% endif %} + {% if media is defined %} +

Are you sure you want to delete {{ media[1] }}?

+
+

{{ plan.message }}

+

The media record and its playback options will be permanently removed. This cannot be undone.

+
+ {% if media[3] == 1 or media[4] == 1 %} +

This item is active or marked as default. The player will select another active/default item, or a blank screen, on its next check.

+ {% endif %} + + + Cancel + + + {% else %} + Return to media library + {% endif %} +
+ + diff --git a/blueprints/media_library/media_library.html b/blueprints/media_library/media_library.html new file mode 100644 index 0000000..e0b5a14 --- /dev/null +++ b/blueprints/media_library/media_library.html @@ -0,0 +1,71 @@ +{% macro media_icon(kind) -%} + +{%- endmacro %} + + + + Play Media - Sanctuary Commander + + + + + + +
+

Play Media

+
+ Home +
+ {% if state.blank %}Blank screen selected{% else %}Selected for playback: {{ state.selected_name }}{% if state.using_default %} (default){% endif %}{% endif %} +

This shows the database selection, not player health. Run player.py on the display computer; it picks up changes within about two seconds.

+
+ + {% if items %} +
+ {% for item in items %} +
+
+
+ {{ media_icon(item.kind) }} + {% if item.preview %} + Preview of {{ item.media_name }} + {% endif %} +
+
+

{{ item.media_name }}

+

{{ media_icon(item.kind) }} {{ item.kind }}

+
+ Selected + Default +
+
+ +
+ + Delete {{ item.media_name }} + +
+
+
+ {% endfor %} +
+ {% else %} +

No media yet. Upload an image or video, configure a stream, or download a YouTube video from the home page.

+ {% endif %} +
+ + diff --git a/blueprints/media_library/media_library.py b/blueprints/media_library/media_library.py new file mode 100644 index 0000000..aa425b7 --- /dev/null +++ b/blueprints/media_library/media_library.py @@ -0,0 +1,236 @@ +import hashlib +from pathlib import Path +import subprocess +from tempfile import NamedTemporaryFile +from urllib.parse import urlsplit +from uuid import uuid4 + +from flask import Blueprint, abort, current_app, jsonify, redirect, render_template, request, send_file, url_for + +from utilities.tools import get_db +from utilities.media_deletion import confirmation_version, deletion_plan +from utilities.validation import write_transaction + + +media_library_bp = Blueprint('media_library', __name__, url_prefix='/media', template_folder='.') +IMAGE_EXTENSIONS = {'.jpg', '.jpeg', '.png', '.webp', '.bmp', '.tif', '.tiff', '.gif'} +VIDEO_EXTENSIONS = {'.mp4', '.m4v', '.mkv', '.mov', '.webm', '.avi', '.wmv', + '.mpeg', '.mpg', '.ts', '.mts', '.m2ts', '.3gp', '.ogv'} + + +def media_kind(uri): + if not uri: + return 'unknown' + try: + if urlsplit(uri).scheme: + return 'stream' + except ValueError: + return 'unknown' + extension = Path(uri).suffix.lower() + if extension in IMAGE_EXTENSIONS: + return 'image' + if extension in VIDEO_EXTENSIONS: + return 'video' + return 'unknown' + + +def library_state(): + columns = ['media_id', 'media_name', 'media_uri', 'media_active', 'media_default'] + rows = get_db().query('SELECT ' + ', '.join(columns) + ' FROM media ORDER BY media_id')[1] + items = [dict(zip(columns, row)) for row in rows] + # Match player.select_media: active wins, then default, then lowest ID. + selected = next((item for item in items if item['media_active'] == 1), None) + if selected is None: + selected = next((item for item in items if item['media_default'] == 1), None) + state = { + 'selected_id': selected['media_id'] if selected else None, + 'selected_name': selected['media_name'] if selected else None, + 'using_default': bool(selected and selected['media_active'] != 1), + 'blank': not selected or not (selected['media_uri'] or '').strip(), + 'default_ids': [item['media_id'] for item in items if item['media_default'] == 1] + } + return items, state + + +def local_preview_source(uri): + if media_kind(uri) not in ('image', 'video'): + return None + base = Path(current_app.config['CONFIG_DIRECTORY']) + path = (base / uri).resolve() + config = current_app.config['config'] + roots = [(base / config.get(key, default)).resolve() for key, default in ( + ('image_upload_location', 'Images'), ('youtube_download_location', 'Videos'), + ('upload_location', 'uploads') + )] + # Never expose arbitrary paths or follow a symlink out of configured media storage. + if not any(path.is_relative_to(root) for root in roots) or not path.is_file(): + return None + return path + + +@media_library_bp.route('') +def media_list(): + items, state = library_state() + for item in items: + item['kind'] = media_kind(item['media_uri']) + item['preview'] = local_preview_source(item['media_uri']) is not None + return render_template('media_library.html', items=items, state=state) + + +@media_library_bp.route('/status') +def playback_status(): + _, state = library_state() + response = jsonify(state) + response.headers['Cache-Control'] = 'no-store' + return response + + +@media_library_bp.route('//play', methods=['POST']) +def play_media(media_id): + db = get_db() + db.query('BEGIN IMMEDIATE') + try: + rows = db.query('SELECT media_uri FROM media WHERE media_id = ?', [media_id])[1] + if not rows: + abort(404) + if not (rows[0][0] or '').strip(): + abort(400, description='This media item has no source URI.') + # Clearing and setting flags in one transaction avoids flashing the default. + db.query('UPDATE media SET media_active = 0 WHERE media_active = 1') + db.query('UPDATE media SET media_active = 1 WHERE media_id = ?', [media_id]) + db.query('COMMIT') + except Exception: + db.query('ROLLBACK') + raise + return redirect(url_for('media_library.media_list'), code=303) + + +def deletion_media(db, media_id): + rows = db.query('SELECT media_id, media_name, media_uri, media_active, media_default ' + 'FROM media WHERE media_id = ?', [media_id])[1] + if not rows: + abort(404) + return rows[0] + + +def restore_staged_file(staged, source): + try: + if staged is not None and staged.exists(): + if source.exists() or source.is_symlink(): + raise OSError('Original file location is occupied; recovery file retained') + staged.rename(source) + except OSError: + current_app.logger.exception('Restore media manually from %s to %s', staged, source) + + +@media_library_bp.route('//delete', methods=['GET', 'POST']) +def delete_media(media_id): + db = get_db() + directory = current_app.config['CONFIG_DIRECTORY'] + config = current_app.config['config'] + staged = None + source = None + legacy_thumbnail = None + try: + if request.method == 'GET': + media = deletion_media(db, media_id) + plan = deletion_plan(db, media, directory, config) + return render_template('media_delete.html', media=media, plan=plan, + version=confirmation_version(media, plan)) + # Reject cross-site browser submissions to this destructive endpoint. + origin = request.headers.get('Origin') + if (request.headers.get('Sec-Fetch-Site') == 'cross-site' + or (origin and origin.rstrip('/') != request.host_url.rstrip('/'))): + abort(403) + with write_transaction(db): + media = deletion_media(db, media_id) + plan = deletion_plan(db, media, directory, config) + version = confirmation_version(media, plan) + if request.form.get('confirm') != 'yes': + return render_template('media_delete.html', media=media, plan=plan, version=version, + error='Please confirm the deletion using the button below.'), 400 + if request.form.get('version') != version: + return render_template('media_delete.html', media=media, plan=plan, version=version, + error='This media or its storage has changed. Please review and confirm again.'), 409 + preview = local_preview_source(media[2]) + if preview is not None: + stat = preview.stat() + legacy_thumbnail = hashlib.sha256( + f'{media_id}:{preview}:{stat.st_mtime_ns}:{stat.st_size}'.encode() + ).hexdigest() + '.png' + source = plan['path'] + if source is not None: + # Rename within the same directory so a database failure can be undone. + staged = source.with_name(f'.deleting-{uuid4().hex}-{source.name}') + source.rename(staged) + db.query('DELETE FROM media_playback_option WHERE media_id = ?', [media_id]) + db.query('DELETE FROM media WHERE media_id = ?', [media_id]) + except (OSError, RuntimeError): + restore_staged_file(staged, source) + current_app.logger.exception('Unable to prepare deletion of media %s', media_id) + return render_template('media_delete.html', error='Unable to access or remove the stored file. ' + 'The media record was not deleted. Please try again or contact the administrator.'), 500 + except BaseException: + restore_staged_file(staged, source) + raise + + # Only destroy the staged file after the database transaction has committed. + if staged is not None: + try: + staged.unlink() + except OSError: + current_app.logger.exception('Media record %s deleted, but storage cleanup is needed at %s', media_id, staged) + return render_template('media_delete.html', error='The database record was deleted, but its file ' + 'could not be removed. Storage has not been freed; contact the administrator ' + 'to clean up the retained file (details are in the server log).'), 500 + cache = Path(directory) / '.thumbnails' + try: + if not cache.is_symlink(): + thumbnails = list(cache.glob(f'{media_id}-*.png')) + if legacy_thumbnail: + thumbnails.append(cache / legacy_thumbnail) + for path in thumbnails: + path.unlink(missing_ok=True) + except OSError: + current_app.logger.warning('Could not clean cached thumbnails for deleted media %s', media_id) + return redirect(url_for('media_library.media_list'), code=303) + + +@media_library_bp.route('//thumbnail') +def thumbnail(media_id): + rows = get_db().query('SELECT media_uri FROM media WHERE media_id = ?', [media_id])[1] + if not rows: + abort(404) + try: + source = local_preview_source(rows[0][0]) + if source is None: + abort(404) + stat = source.stat() + key = hashlib.sha256(f'{media_id}:{source}:{stat.st_mtime_ns}:{stat.st_size}'.encode()).hexdigest() + cache = Path(current_app.config['CONFIG_DIRECTORY']) / '.thumbnails' + cache.mkdir(parents=True, exist_ok=True) + destination = cache / f'{media_id}-{key}.png' + if not destination.is_file(): + temporary = None + try: + with NamedTemporaryFile(dir=cache, suffix='.png', delete=False) as output: + temporary = Path(output.name) + # Read only local media. FFmpeg may not open network protocols referenced by a file. + subprocess.run([ + 'ffmpeg', '-hide_banner', '-loglevel', 'error', '-nostdin', '-y', + '-protocol_whitelist', 'file,pipe', '-i', str(source), + '-frames:v', '1', '-an', '-vf', 'scale=240:135:force_original_aspect_ratio=decrease', + '-threads', '1', str(temporary) + ], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=10) + if temporary.stat().st_size == 0: + abort(404) + temporary.replace(destination) + finally: + if temporary is not None: + temporary.unlink(missing_ok=True) + response = send_file(destination, mimetype='image/png', conditional=True, max_age=0) + response.headers['Cache-Control'] = 'no-cache' + return response + except (OSError, subprocess.SubprocessError): + current_app.logger.warning('Thumbnail unavailable for media %s', media_id) + abort(404) diff --git a/blueprints/upload_photo/upload_photo.html b/blueprints/upload_photo/upload_photo.html index 38f7778..4be9704 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..d373cfc 100644 --- a/blueprints/upload_photo/upload_photo.py +++ b/blueprints/upload_photo/upload_photo.py @@ -1,48 +1,93 @@ +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 +from utilities.validation import (ValidationError, ValidationUnavailable, ensure_name_available, + validate_media_name, validate_upload_content, write_transaction) + + +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[]']) + try: + name = validate_media_name(request.form.get('name', '')) + except ValidationError as error: + return jsonify(status='FAILED', error=str(error)), 400 + files = request.files.getlist('files[]') + if len(files) != 1 or len(list(request.files.items(multi=True))) != 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 + try: + storage = (Path(current_app.config['CONFIG_DIRECTORY']) / + current_app.config['config'].get('image_upload_location', 'Images')).resolve() + except (OSError, RuntimeError): + current_app.logger.exception('Unable to resolve image storage location') + return jsonify(status='FAILED', error='Unable to access image storage. Please contact the administrator.'), 500 + # 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 + validate_upload_content(partial, 'image', extension) + db = get_db() + with write_transaction(db): + ensure_name_available(db.db, name) + partial.rename(destination) + db.insert('media', ['media_name', 'media_uri'], [name, str(destination)]) + saved = True + return jsonify(status='SUCCESS'), 200 + except ValidationError as error: + return jsonify(status='FAILED', error=str(error)), 400 + except ValidationUnavailable as error: + current_app.logger.warning('Image validation unavailable: %s', error) + return jsonify(status='FAILED', error=str(error)), 503 + 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_slideshow/upload_slideshow.html b/blueprints/upload_slideshow/upload_slideshow.html deleted file mode 100644 index ad913d6..0000000 --- a/blueprints/upload_slideshow/upload_slideshow.html +++ /dev/null @@ -1,46 +0,0 @@ - - - - Video Commander - - - - - - - - -
-

Upload a Slideshow of Photos

-
- -
-
-
0%
-
-
- - -
-
- - -
-
- - -
- -
-
- - \ No newline at end of file diff --git a/blueprints/upload_slideshow/upload_slideshow.py b/blueprints/upload_slideshow/upload_slideshow.py deleted file mode 100644 index c334c2c..0000000 --- a/blueprints/upload_slideshow/upload_slideshow.py +++ /dev/null @@ -1,48 +0,0 @@ -from flask import Blueprint, request, render_template, jsonify, current_app -from utilities.tools import get_db -from werkzeug.utils import secure_filename -import os - -upload_photo_bp = Blueprint('upload_slideshow', __name__, url_prefix='/upload', template_folder='.') - -@upload_photo_bp.route('/slideshow', 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_slideshow.html') - -def upload(): - if not request.files['files[]']: - return jsonify({ - 'status': 'FAILED', - 'error': '/upload/slideshow requires 1 or more photos' - }), 400 - - # TODO Button name data exists - # TODO Button name already exists validation - # TODO File input validation - print(request.files['files[]']) - - 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 diff --git a/blueprints/upload_video/upload_video.html b/blueprints/upload_video/upload_video.html new file mode 100644 index 0000000..f0cdbb8 --- /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..d9c3512 --- /dev/null +++ b/blueprints/upload_video/upload_video.py @@ -0,0 +1,97 @@ +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 utilities.validation import (ValidationError, ValidationUnavailable, ensure_name_available, + validate_media_name, validate_upload_content, write_transaction) + + +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(): + try: + name = validate_media_name(request.form.get('name', '')) + except ValidationError as error: + return jsonify(status='FAILED', error=str(error)), 400 + files = request.files.getlist('files[]') + if len(files) != 1 or len(list(request.files.items(multi=True))) != 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 + + try: + storage = (Path(current_app.config['CONFIG_DIRECTORY']) / + current_app.config['config'].get('youtube_download_location', 'Videos')).resolve() + except (OSError, RuntimeError): + current_app.logger.exception('Unable to resolve video storage location') + return jsonify(status='FAILED', error='Unable to access video storage. Please contact the administrator.'), 500 + # 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 + validate_upload_content(partial, 'video', extension) + db = get_db() + with write_transaction(db): + ensure_name_available(db.db, name) + partial.rename(destination) + db.insert('media', ['media_name', 'media_uri'], [name, str(destination)]) + saved = True + return jsonify(status='SUCCESS'), 200 + except ValidationError as error: + return jsonify(status='FAILED', error=str(error)), 400 + except ValidationUnavailable as error: + current_app.logger.warning('Video validation unavailable: %s', error) + return jsonify(status='FAILED', error=str(error)), 503 + 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/blueprints/youtube_download/youtube_download.py b/blueprints/youtube_download/youtube_download.py new file mode 100644 index 0000000..b76a062 --- /dev/null +++ b/blueprints/youtube_download/youtube_download.py @@ -0,0 +1,88 @@ +import re +import sqlite3 +from urllib.parse import parse_qs, urlsplit + +from flask import Blueprint, request, render_template, redirect, url_for, current_app +from utilities.tools import get_db +from utilities.validation import (ValidationError, ensure_name_available, validate_media_name, + valid_stream_url, write_transaction) + + +youtube_download_bp = Blueprint('youtube_download', __name__, url_prefix='/youtube', template_folder='.') + + +@youtube_download_bp.route('/download', methods=['GET', 'POST']) +def request_download(): + media_name = '' + youtube_url = '' + error = None + if request.method == 'POST': + media_name = request.form.get('media_name', '') + youtube_url = request.form.get('youtube_url', '').strip(' ') + try: + media_name = validate_media_name(media_name) + if not valid_youtube_url(youtube_url): + raise ValidationError('Please enter a valid YouTube video URL (youtube.com or youtu.be).') + db = get_db() + with write_transaction(db): + ensure_name_available(db.db, media_name) + db.insert('youtube_download_job', + ['youtube_download_job_url', 'youtube_download_job_media_name'], + [youtube_url, media_name]) + return redirect(url_for('youtube_download.list_jobs'), code=303) + except ValidationError as exception: + error = str(exception) + except sqlite3.Error: + current_app.logger.exception('Unable to queue YouTube download') + return render_template('youtube_request.html', media_name=media_name, + youtube_url=youtube_url, + error='Unable to queue the download due to a database error. Please try again.'), 503 + + return render_template( + 'youtube_request.html', media_name=media_name, youtube_url=youtube_url, error=error + ), 400 if error else 200 + + +def valid_youtube_url(value): + if not valid_stream_url(value): + return False + try: + parsed = urlsplit(value) + if parsed.scheme not in ('http', 'https') or parsed.username or parsed.password or parsed.port not in (None, 80, 443): + return False + host = parsed.hostname + path = parsed.path.strip('/').split('/') + if host in ('youtu.be', 'www.youtu.be') and len(path) == 1: + video_id = path[0] + elif host in ('youtube.com', 'www.youtube.com', 'm.youtube.com', 'music.youtube.com'): + if path == ['watch']: + ids = parse_qs(parsed.query).get('v', []) + video_id = ids[0] if len(ids) == 1 else '' + elif len(path) == 2 and path[0] in ('shorts', 'live', 'embed'): + video_id = path[1] + else: + return False + else: + return False + return bool(re.fullmatch(r'[A-Za-z0-9_-]{1,128}', video_id)) + except ValueError: + return False + + +@youtube_download_bp.route('/jobs') +def list_jobs(): + show_completed = request.args.get('show_completed') == '1' + columns = [ + 'youtube_download_job_id', 'youtube_download_job_media_name', + 'youtube_download_job_url', 'youtube_download_job_status', + 'youtube_download_job_retry_count' + ] + query = 'SELECT ' + ', '.join(columns) + ' FROM youtube_download_job' + parameters = [] + if not show_completed: + query += ' WHERE youtube_download_job_status != ?' + parameters.append('downloaded') + query += ' ORDER BY youtube_download_job_id' + rows = get_db().query(query, parameters)[1] + jobs = [dict(zip(columns, row)) for row in rows] + return render_template('youtube_jobs.html', jobs=jobs, show_completed=show_completed) diff --git a/blueprints/youtube_download/youtube_jobs.html b/blueprints/youtube_download/youtube_jobs.html new file mode 100644 index 0000000..64b8c10 --- /dev/null +++ b/blueprints/youtube_download/youtube_jobs.html @@ -0,0 +1,49 @@ + + + + YouTube Download Jobs - Sanctuary Commander + + + + + +
+

YouTube Download Jobs

+
+ +

Pending, downloading, and failed jobs are always shown. Refresh this page to see updated statuses.

+
+
+ + +
+ +
+ {% if jobs %} +
+ + + + + + {% for job in jobs %} + + + + + + + + {% endfor %} + +
JobMedia NameYouTube URLStatusFailed Attempts
{{ job.youtube_download_job_id }}{{ job.youtube_download_job_media_name or '(Video title will be used)' }}{{ job.youtube_download_job_url }}{{ job.youtube_download_job_status }}{{ job.youtube_download_job_retry_count }}
+
+ {% else %} +

No download jobs to show.

+ {% endif %} +
+ + diff --git a/blueprints/youtube_download/youtube_request.html b/blueprints/youtube_download/youtube_request.html new file mode 100644 index 0000000..c2ee9ef --- /dev/null +++ b/blueprints/youtube_download/youtube_request.html @@ -0,0 +1,37 @@ + + + + Request a YouTube Video - Sanctuary Commander + + + + + +
+

Request a YouTube Video

+
+ +
+ Queue a video for download to local storage. Downloads are processed by the separate YouTube worker. +
+ {% if error %} + + {% endif %} +
+
+ + +
The name to display when the downloaded video is ready to play.
+
+
+ + +
+ +
+
+ + diff --git a/config.json b/config.json index 5e02f7c..4953d46 100644 --- a/config.json +++ b/config.json @@ -3,5 +3,8 @@ "type": "SQLite", "name": "scdb.db" }, - "upload_location": "uploads" + "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_database_generator.py b/sc_database_generator.py index f169f79..6a90059 100644 --- a/sc_database_generator.py +++ b/sc_database_generator.py @@ -17,27 +17,6 @@ my_db.query(""" ) """) -my_db.query(""" - CREATE TABLE IF NOT EXISTS media_preparation ( - media_preparation_id INTEGER PRIMARY KEY AUTOINCREMENT, - media_id INTEGER NOT NULL, - media_preparation_started INTEGER DEFAULT 0 CHECK(media_preparation_started IN (0, 1)), - media_preparation_progress INTEGER, - media_preparation_finished INTEGER DEFAULT 0 CHECK(media_preparation_finished IN (0, 1)), - media_preparation_time_between_components INTEGER - ) -""") - -my_db.query(""" - CREATE TABLE IF NOT EXISTS media_component ( - media_component_id INTEGER PRIMARY KEY AUTOINCREMENT, - media_id INTEGER NOT NULL, - media_component_uri NOT NULL, - media_component_index INTEGER CHECK(media_component_index >= 1), - media_component_deleted INTEGER DEFAULT 0 CHECK(media_component_deleted IN (0, 1)) - ) -""") - my_db.query(""" CREATE TABLE IF NOT EXISTS media_playback_option ( media_playback_option_id INTEGER PRIMARY KEY AUTOINCREMENT, @@ -47,4 +26,57 @@ my_db.query(""" ) """) -my_db.close() \ No newline at end of file +job_schema = """ + CREATE TABLE IF NOT EXISTS youtube_download_job ( + youtube_download_job_id INTEGER PRIMARY KEY AUTOINCREMENT, + youtube_download_job_url TEXT NOT NULL, + youtube_download_job_media_name TEXT NOT NULL DEFAULT '', + youtube_download_job_status TEXT NOT NULL DEFAULT 'pending' + CHECK(youtube_download_job_status IN ('pending', 'downloading', 'downloaded', 'failed')), + youtube_download_job_retry_count INTEGER NOT NULL DEFAULT 0 + CHECK(typeof(youtube_download_job_retry_count) = 'integer' AND youtube_download_job_retry_count >= 0) + ) +""" +my_db.query(job_schema) + +# Preserve existing jobs when adding the media-name column to older databases. +job_columns = my_db.query("SELECT name FROM pragma_table_info('youtube_download_job')")[1] +if ("youtube_download_job_media_name",) not in job_columns: + my_db.query(""" + ALTER TABLE youtube_download_job + ADD COLUMN youtube_download_job_media_name TEXT NOT NULL DEFAULT '' + """) + +# SQLite requires rebuilding the old table to expand its status CHECK constraint. +if ("youtube_download_job_retry_count",) not in job_columns: + my_db.query("BEGIN IMMEDIATE") + try: + sequence = my_db.query( + "SELECT seq FROM sqlite_sequence WHERE name = 'youtube_download_job'" + )[1] + my_db.query(job_schema.replace( + "IF NOT EXISTS youtube_download_job", "youtube_download_job_new" + )) + my_db.query(""" + INSERT INTO youtube_download_job_new ( + youtube_download_job_id, youtube_download_job_url, + youtube_download_job_media_name, youtube_download_job_status + ) + SELECT youtube_download_job_id, youtube_download_job_url, + youtube_download_job_media_name, youtube_download_job_status + FROM youtube_download_job + """) + my_db.query("DROP TABLE youtube_download_job") + my_db.query("ALTER TABLE youtube_download_job_new RENAME TO youtube_download_job") + if sequence: + my_db.query("DELETE FROM sqlite_sequence WHERE name = 'youtube_download_job'") + my_db.query( + "INSERT INTO sqlite_sequence (name, seq) VALUES ('youtube_download_job', ?)", + [sequence[0][0]] + ) + my_db.query("COMMIT") + except Exception: + my_db.query("ROLLBACK") + raise + +my_db.close() diff --git a/sc_webserver.py b/sc_webserver.py index 5d7e6c2..cd9502c 100644 --- a/sc_webserver.py +++ b/sc_webserver.py @@ -1,9 +1,13 @@ -from flask import Flask +from flask import Flask, g, jsonify, render_template, request 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 +from blueprints.media_library.media_library import media_library_bp import os import json +import sqlite3 with open("config.json", 'r') as config_file: config_json = json.loads(config_file.read()) @@ -14,9 +18,30 @@ 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) +app.register_blueprint(media_library_bp) + + +@app.errorhandler(sqlite3.Error) +def database_error(error): + app.logger.exception('Database request failed') + message = 'The database is unavailable. Please try again or contact the administrator.' + if request.path.startswith('/upload/') or request.path == '/media/status': + return jsonify(status='FAILED', error=message), 503 + return render_template('database_error.html', message=message), 503 + + +@app.teardown_appcontext +def close_database(error): + db = g.pop('_database', None) + if db is not None: + db.close() + if __name__ == '__main__': app.run(debug=True, host="0.0.0.0", port=2025) \ No newline at end of file diff --git a/scdb.db b/scdb.db index 1bf26f1..0924d75 100644 Binary files a/scdb.db and b/scdb.db differ diff --git a/static/media_library.js b/static/media_library.js new file mode 100644 index 0000000..22781df --- /dev/null +++ b/static/media_library.js @@ -0,0 +1,33 @@ +const library = document.getElementById('mediaLibrary') +const selection = document.getElementById('playbackSelection') +const statusError = document.getElementById('statusError') + +for (const image of document.querySelectorAll('.media-thumbnail')) { + image.addEventListener('error', () => { image.hidden = true }) + if (image.complete && image.naturalWidth === 0) image.hidden = true +} + +async function refreshSelection() { + try { + const response = await fetch(library.dataset.statusUrl, {cache: 'no-store'}) + if (!response.ok) throw new Error('Status request failed') + const state = await response.json() + selection.textContent = state.blank ? 'Blank screen selected' + : `Selected for playback: ${state.selected_name}${state.using_default ? ' (default)' : ''}` + for (const card of library.querySelectorAll('[data-media-id]')) { + const selected = Number(card.dataset.mediaId) === state.selected_id + card.classList.toggle('border-success', selected) + card.classList.toggle('border-3', selected) + card.querySelector('[data-selected-badge]').hidden = !selected + card.querySelector('[data-default-badge]').hidden = !state.default_ids.includes(Number(card.dataset.mediaId)) + } + statusError.hidden = true + } catch (error) { + statusError.hidden = false + } finally { + // Schedule after completion so slow requests never overlap. + window.setTimeout(refreshSelection, 2000) + } +} + +window.setTimeout(refreshSelection, 2000) diff --git a/static/style.css b/static/style.css index 009a5ba..4f9eb2b 100644 --- a/static/style.css +++ b/static/style.css @@ -3,4 +3,16 @@ html { } body { background-color: #ebe1c7 !important; +} + +.media-preview { + aspect-ratio: 16 / 9; +} + +.media-thumbnail { + position: absolute; + inset: 0; + width: 100%; + height: 100%; + object-fit: contain; } \ No newline at end of file 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/templates/database_error.html b/templates/database_error.html new file mode 100644 index 0000000..de88254 --- /dev/null +++ b/templates/database_error.html @@ -0,0 +1,15 @@ + + + + Database unavailable - Sanctuary Commander + + + + +
+

Unable to complete the request

+ + Home +
+ + diff --git a/test/media_deletion_test.py b/test/media_deletion_test.py new file mode 100644 index 0000000..7096eaf --- /dev/null +++ b/test/media_deletion_test.py @@ -0,0 +1,260 @@ +from contextlib import closing +import hashlib +import json +import os +from pathlib import Path +import re +import runpy +import sqlite3 +import subprocess +import sys +import tempfile +import unittest +from unittest.mock import patch + +from utilities.database.sqlite import SQLite + + +ROOT = Path(__file__).resolve().parents[1] + + +class MediaDeletionTest(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.workdir / 'config.json').write_text(json.dumps({ + 'database': {'type': 'SQLite', 'name': str(self.database)}, + 'upload_location': '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 add_media(self, uri='Images/photo.png', name='Image', active=0, default=0): + with closing(sqlite3.connect(self.database)) as db: + media_id = db.execute( + 'INSERT INTO media (media_name, media_uri, media_active, media_default) VALUES (?, ?, ?, ?)', + [name, uri, active, default] + ).lastrowid + db.execute('INSERT INTO media_playback_option (media_id, media_playback_option, ' + 'media_playback_option_weight) VALUES (?, ?, ?)', [media_id, '-fs', 1]) + db.commit() + return media_id + + def create_file(self, name='Images/photo.png'): + path = self.workdir / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(b'stored file') + return path + + def exists_in_db(self, media_id): + with closing(sqlite3.connect(self.database)) as db: + return db.execute('SELECT COUNT(*) FROM media WHERE media_id = ?', [media_id]).fetchone()[0] == 1 + + def prompt(self, media_id): + response = self.client.get(f'/media/{media_id}/delete') + self.assertEqual(response.status_code, 200) + version = re.search(rb'name="version" value="([a-f0-9]+)"', response.data).group(1).decode() + return response, {'confirm': 'yes', 'version': version} + + def delete(self, media_id): + _, data = self.prompt(media_id) + return self.client.post(f'/media/{media_id}/delete', data=data) + + def test_library_links_to_confirmation_and_get_deletes_nothing(self): + path = self.create_file() + media_id = self.add_media(name='') + response = self.client.get('/media') + self.assertIn(f'/media/{media_id}/delete'.encode(), response.data) + response, _ = self.prompt(media_id) + self.assertIn(b'<Image>', response.data) + self.assertIn(b'Cancel', response.data) + self.assertIn(b'Yes, delete media', response.data) + self.assertTrue(path.exists()) + self.assertTrue(self.exists_in_db(media_id)) + + def test_confirmed_local_deletion_removes_record_options_file_and_thumbnails(self): + path = self.create_file() + media_id = self.add_media() + cache = self.workdir / '.thumbnails' + cache.mkdir() + preview = cache / f'{media_id}-old-preview.png' + preview.write_bytes(b'preview') + stat = path.stat() + legacy = cache / (hashlib.sha256( + f'{media_id}:{path}:{stat.st_mtime_ns}:{stat.st_size}'.encode()).hexdigest() + '.png') + legacy.write_bytes(b'legacy preview') + unrelated = cache / '999-preview.png' + unrelated.write_bytes(b'unrelated') + response = self.delete(media_id) + self.assertEqual(response.status_code, 303) + self.assertTrue(response.location.endswith('/media')) + self.assertFalse(path.exists()) + self.assertFalse(self.exists_in_db(media_id)) + self.assertFalse(preview.exists()) + self.assertFalse(legacy.exists()) + self.assertTrue(unrelated.exists()) + with closing(sqlite3.connect(self.database)) as db: + self.assertEqual(db.execute('SELECT COUNT(*) FROM media_playback_option').fetchone(), (0,)) + self.assertEqual(list(path.parent.glob('.deleting-*')), []) + + def test_video_legacy_and_custom_storage_files_are_deleted(self): + for filename in ('Videos/job-1.mp4', 'uploads/Old image/old.jpg', 'CustomImages/new.png'): + with self.subTest(filename=filename): + self.app.config['config']['image_upload_location'] = 'CustomImages' + path = self.create_file(filename) + media_id = self.add_media(str(path)) + self.assertEqual(self.delete(media_id).status_code, 303) + self.assertFalse(path.exists()) + + def test_stream_and_missing_files_only_remove_records(self): + for uri in ('https://example.com/live', 'rtsp://example.com/live', 'Images/missing.png', None): + with self.subTest(uri=uri): + media_id = self.add_media(uri) + self.assertEqual(self.delete(media_id).status_code, 303) + self.assertFalse(self.exists_in_db(media_id)) + + def test_shared_file_is_retained_until_last_reference_deleted(self): + path = self.create_file() + first = self.add_media('Images/photo.png') + second = self.add_media(path.as_uri()) + response, _ = self.prompt(first) + self.assertIn(b'Another media item uses this file', response.data) + self.assertEqual(self.delete(first).status_code, 303) + self.assertTrue(path.exists()) + self.assertTrue(self.exists_in_db(second)) + self.assertEqual(self.delete(second).status_code, 303) + self.assertFalse(path.exists()) + + def test_outside_paths_and_symlinks_are_not_deleted(self): + outside = self.create_file('private/image.png') + managed = self.create_file('Images/real.png') + (self.workdir / 'Images/link-out.png').symlink_to(outside) + (self.workdir / 'Images/link-in.png').symlink_to(managed) + for uri in (str(outside), 'Images/link-out.png', 'Images/link-in.png'): + media_id = self.add_media(uri) + self.assertEqual(self.delete(media_id).status_code, 303) + self.assertTrue(outside.exists()) + self.assertTrue(managed.exists()) + self.assertTrue((self.workdir / 'Images/link-in.png').is_symlink()) + self.assertTrue((self.workdir / 'Images/link-out.png').is_symlink()) + + def test_directories_are_never_recursively_deleted(self): + path = self.create_file('Images/folder/image.png') + media_id = self.add_media('Images/folder') + self.assertEqual(self.delete(media_id).status_code, 303) + self.assertTrue(path.exists()) + + def test_confirmation_is_required_and_stale_prompt_must_be_reviewed(self): + path = self.create_file() + media_id = self.add_media() + _, data = self.prompt(media_id) + self.assertEqual(self.client.post(f'/media/{media_id}/delete').status_code, 400) + self.assertEqual(self.client.post(f'/media/{media_id}/delete', data={'confirm': 'yes'}).status_code, 409) + path.write_bytes(b'changed file') + response = self.client.post(f'/media/{media_id}/delete', data=data) + self.assertEqual(response.status_code, 409) + self.assertIn(b'review and confirm again', response.data) + self.assertTrue(path.exists()) + self.assertTrue(self.exists_in_db(media_id)) + + def test_cross_site_confirmation_is_rejected(self): + path = self.create_file() + media_id = self.add_media() + _, data = self.prompt(media_id) + response = self.client.post(f'/media/{media_id}/delete', data=data, + headers={'Origin': 'https://unrelated.example'}) + self.assertEqual(response.status_code, 403) + self.assertTrue(path.exists()) + self.assertTrue(self.exists_in_db(media_id)) + + def test_database_delete_failure_restores_file_and_options(self): + path = self.create_file() + media_id = self.add_media() + with closing(sqlite3.connect(self.database)) as db: + db.execute("""CREATE TRIGGER reject_delete BEFORE DELETE ON media + BEGIN SELECT RAISE(ABORT, 'Test failure'); END""") + db.commit() + _, data = self.prompt(media_id) + with self.assertLogs(self.app.logger, level='ERROR'): + response = self.client.post(f'/media/{media_id}/delete', data=data) + self.assertEqual(response.status_code, 503) + self.assertTrue(path.exists()) + self.assertTrue(self.exists_in_db(media_id)) + self.assertEqual(list(path.parent.glob('.deleting-*')), []) + with closing(sqlite3.connect(self.database)) as db: + self.assertEqual(db.execute('SELECT COUNT(*) FROM media_playback_option').fetchone(), (1,)) + + def test_commit_failure_also_restores_file(self): + path = self.create_file() + media_id = self.add_media() + _, data = self.prompt(media_id) + original_query = SQLite.query + def failing_commit(db, query, parameters=None): + if query == 'COMMIT': + raise sqlite3.OperationalError('Commit failed') + return original_query(db, query, parameters) + with patch.object(SQLite, 'query', failing_commit): + with self.assertLogs(self.app.logger, level='ERROR'): + response = self.client.post(f'/media/{media_id}/delete', data=data) + self.assertEqual(response.status_code, 503) + self.assertTrue(path.exists()) + self.assertTrue(self.exists_in_db(media_id)) + + def test_storage_rename_failure_leaves_record_unchanged(self): + path = self.create_file() + media_id = self.add_media() + _, data = self.prompt(media_id) + with patch.object(Path, 'rename', side_effect=PermissionError('Permission denied')): + with self.assertLogs(self.app.logger, level='ERROR'): + response = self.client.post(f'/media/{media_id}/delete', data=data) + self.assertEqual(response.status_code, 500) + self.assertIn(b'record was not deleted', response.data) + self.assertTrue(path.exists()) + self.assertTrue(self.exists_in_db(media_id)) + + def test_final_cleanup_failure_reports_retained_storage(self): + path = self.create_file() + media_id = self.add_media() + _, data = self.prompt(media_id) + original_unlink = Path.unlink + def failing_cleanup(file, *args, **kwargs): + if file.name.startswith('.deleting-'): + raise PermissionError('Permission denied') + return original_unlink(file, *args, **kwargs) + with patch.object(Path, 'unlink', failing_cleanup): + with self.assertLogs(self.app.logger, level='ERROR'): + response = self.client.post(f'/media/{media_id}/delete', data=data) + self.assertEqual(response.status_code, 500) + self.assertIn(b'Storage has not been freed', response.data) + self.assertFalse(self.exists_in_db(media_id)) + retained = list(path.parent.glob('.deleting-*')) + self.assertEqual(len(retained), 1) + self.assertEqual(retained[0].read_bytes(), b'stored file') + + def test_deleting_active_media_updates_default_or_blank_selection(self): + first = self.add_media('https://example.com/first', active=1) + second = self.add_media('https://example.com/default', default=1) + response, _ = self.prompt(first) + self.assertIn(b'active or marked as default', response.data) + self.assertEqual(self.delete(first).status_code, 303) + self.assertEqual(self.client.get('/media/status').json['selected_id'], second) + self.assertEqual(self.delete(second).status_code, 303) + self.assertTrue(self.client.get('/media/status').json['blank']) + + def test_missing_media_returns_not_found(self): + self.assertEqual(self.client.get('/media/999/delete').status_code, 404) + self.assertEqual(self.client.post('/media/999/delete', data={'confirm': 'yes'}).status_code, 404) + + +if __name__ == '__main__': + unittest.main() diff --git a/test/media_library_test.py b/test/media_library_test.py new file mode 100644 index 0000000..f772f7b --- /dev/null +++ b/test/media_library_test.py @@ -0,0 +1,208 @@ +from contextlib import closing +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.media_library.media_library import media_kind +from player import select_media + + +ROOT = Path(__file__).resolve().parents[1] + + +class MediaLibraryTest(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.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 add_media(self, name='Video', uri='Videos/video.mp4', active=0, default=0): + with closing(sqlite3.connect(self.database)) as db: + media_id = db.execute( + 'INSERT INTO media (media_name, media_uri, media_active, media_default) VALUES (?, ?, ?, ?)', + [name, uri, active, default] + ).lastrowid + db.commit() + return media_id + + def create_local(self, name='Images/photo.png'): + path = self.workdir / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(b'local media') + return path + + def fake_ffmpeg(self, command, **kwargs): + Path(command[-1]).write_bytes(b'cached preview') + return subprocess.CompletedProcess(command, 0) + + def assert_active(self, expected): + with closing(sqlite3.connect(self.database)) as db: + self.assertEqual(db.execute('SELECT media_id FROM media WHERE media_active = 1').fetchall(), + [(expected,)] if expected is not None else []) + + def test_home_links_to_unified_library_and_empty_state(self): + home = self.client.get('/') + self.assertIn(b'href="/media"', home.data) + self.assertNotIn(b'>Show Static Image', home.data) + response = self.client.get('/media') + self.assertEqual(response.status_code, 200) + self.assertIn(b'No media yet.', response.data) + self.assertIn(b'Blank screen selected', response.data) + + def test_play_selects_one_media_and_preserves_defaults(self): + first = self.add_media(active=1, default=1) + second = self.add_media(uri='https://example.com/live') + response = self.client.post(f'/media/{second}/play') + self.assertEqual(response.status_code, 303) + self.assertTrue(response.location.endswith('/media')) + self.assert_active(second) + state = self.client.get('/media/status').json + self.assertEqual(state['selected_id'], second) + self.assertFalse(state['using_default']) + self.assertEqual(state['default_ids'], [first]) + self.client.post(f'/media/{second}/play') + self.assert_active(second) + + def test_play_requires_post(self): + media_id = self.add_media() + self.assertEqual(self.client.get(f'/media/{media_id}/play').status_code, 405) + self.assert_active(None) + + def test_missing_or_empty_media_does_not_clear_active(self): + active = self.add_media(active=1) + empty = self.add_media(uri=' ') + self.assertEqual(self.client.post('/media/999/play').status_code, 404) + self.assertEqual(self.client.post(f'/media/{empty}/play').status_code, 400) + self.assert_active(active) + + def test_failed_selection_transaction_restores_previous_active(self): + first = self.add_media(active=1) + second = self.add_media() + with closing(sqlite3.connect(self.database)) as db: + db.execute(f''' + CREATE TRIGGER reject_selection BEFORE UPDATE ON media + WHEN NEW.media_id = {second} AND NEW.media_active = 1 + BEGIN SELECT RAISE(ABORT, 'Test failure'); END + ''') + db.commit() + with self.assertLogs(self.app.logger, level='ERROR'): + response = self.client.post(f'/media/{second}/play') + self.assertEqual(response.status_code, 503) + self.assertIn(b'database is unavailable', response.data) + self.assert_active(first) + + def test_status_matches_player_priority_and_changes(self): + first = self.add_media(name='First default', default=1) + self.add_media(name='Second default', default=1) + active = self.add_media(name='Active', active=1) + self.add_media(name='Second active', active=1) + for expected, default in ((active, False), (first, True), (None, False)): + state = self.client.get('/media/status') + self.assertEqual(state.json['selected_id'], expected) + self.assertEqual(state.json['using_default'], default) + self.assertEqual(state.headers['Cache-Control'], 'no-store') + with closing(sqlite3.connect(self.database)) as db: + selected = select_media(db) + self.assertEqual(selected[0] if selected else None, expected) + if expected == active: + db.execute('UPDATE media SET media_active = 0') + else: + db.execute('UPDATE media SET media_default = 0') + db.commit() + + def test_names_are_escaped_and_icons_are_present(self): + self.add_media(name='', uri='Images/photo.PNG', default=1) + self.add_media(uri='Videos/local.mp4') + self.add_media(uri='https://example.com/video.mp4') + response = self.client.get('/media') + self.assertNotIn(b'', response.data) + self.assertIn(b'<script>', response.data) + self.assertIn(b'image', response.data) + self.assertIn(b'video', response.data) + self.assertIn(b'stream', response.data) + self.assertIn(b'Selected', response.data) + self.assertIn(b'Default', response.data) + + def test_thumbnail_generation_cache_and_file_change(self): + source = self.create_local() + media_id = self.add_media(uri=str(source)) + page = self.client.get('/media') + self.assertIn(f'/media/{media_id}/thumbnail'.encode(), page.data) + with patch('blueprints.media_library.media_library.subprocess.run', side_effect=self.fake_ffmpeg) as run: + with self.client.get(f'/media/{media_id}/thumbnail') as response: + self.assertEqual(response.status_code, 200) + self.assertEqual(response.mimetype, 'image/png') + self.assertEqual(response.data, b'cached preview') + with self.client.get(f'/media/{media_id}/thumbnail') as response: + self.assertEqual(response.status_code, 200) + self.assertEqual(run.call_count, 1) + command = run.call_args.args[0] + self.assertIn('file,pipe', command) + self.assertIn(str(source), command) + self.assertEqual(run.call_args.kwargs['timeout'], 10) + source.write_bytes(b'changed content and size') + with self.client.get(f'/media/{media_id}/thumbnail') as response: + self.assertEqual(response.status_code, 200) + self.assertEqual(run.call_count, 2) + + def test_remote_and_outside_sources_never_invoke_ffmpeg(self): + outside = self.create_local('private/image.png') + (self.workdir / 'Images').mkdir() + (self.workdir / 'Images/link.png').symlink_to(outside) + sources = ['https://example.com/image.png', str(outside), 'Images/link.png', + 'Images/missing.png', 'Videos/playlist.m3u8', None] + with patch('blueprints.media_library.media_library.subprocess.run') as run: + for source in sources: + media_id = self.add_media(uri=source) + self.assertEqual(self.client.get(f'/media/{media_id}/thumbnail').status_code, 404) + run.assert_not_called() + + def test_thumbnail_failure_cleans_temporary_files(self): + self.create_local() + media_id = self.add_media(uri='Images/photo.png') + for error in (FileNotFoundError('ffmpeg missing'), subprocess.TimeoutExpired('ffmpeg', 10)): + with self.subTest(error=error): + with patch('blueprints.media_library.media_library.subprocess.run', side_effect=error): + with self.assertLogs(self.app.logger, level='WARNING'): + self.assertEqual(self.client.get(f'/media/{media_id}/thumbnail').status_code, 404) + self.assertEqual(list((self.workdir / '.thumbnails').iterdir()), []) + + def test_thumbnail_supports_custom_storage_root(self): + self.app.config['config']['image_upload_location'] = 'CustomImages' + self.create_local('CustomImages/photo.png') + media_id = self.add_media(uri='CustomImages/photo.png') + with patch('blueprints.media_library.media_library.subprocess.run', side_effect=self.fake_ffmpeg): + with self.client.get(f'/media/{media_id}/thumbnail') as response: + self.assertEqual(response.status_code, 200) + + def test_media_types(self): + for uri, kind in [('Images/a.JPG', 'image'), ('Videos/a.mkv', 'video'), + ('https://example.com/a.png', 'stream'), (None, 'unknown')]: + self.assertEqual(media_kind(uri), kind) + + +if __name__ == '__main__': + unittest.main() 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/submission_validation_test.py b/test/submission_validation_test.py new file mode 100644 index 0000000..54ca878 --- /dev/null +++ b/test/submission_validation_test.py @@ -0,0 +1,239 @@ +from concurrent.futures import ThreadPoolExecutor +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 threading +import unittest +import wave +from unittest.mock import patch + +from test.upload_photo_test import PNG +from test.upload_video_test import VIDEO +from utilities.validation import valid_stream_url + + +ROOT = Path(__file__).resolve().parents[1] + + +class SubmissionValidationTest(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.workdir / 'config.json').write_text(json.dumps({ + 'database': {'type': 'SQLite', 'name': 'test.db'}, + 'upload_location': '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 submit(self, kind, name): + if kind == 'photo': + return self.client.post('/upload/photo', data={ + 'name': name, 'files[]': (BytesIO(PNG), 'photo.png')}) + if kind == 'video': + return self.client.post('/upload/video', data={ + 'name': name, 'files[]': (BytesIO(VIDEO), 'video.mp4')}) + if kind == 'stream': + return self.client.post('/configure/stream', data={ + 'buttonName': name, 'streamURL': 'https://example.com/stream'}) + return self.client.post('/youtube/download', data={ + 'media_name': name, 'youtube_url': 'https://youtu.be/video'}) + + def test_duplicate_catalog_names_rejected_for_all_workflows(self): + with closing(sqlite3.connect(self.database)) as db: + db.execute('INSERT INTO media (media_name, media_uri) VALUES (?, ?)', ['Straße', 'old']) + db.commit() + for kind in ('photo', 'video', 'stream', 'youtube'): + with self.subTest(kind=kind): + response = self.submit(kind, ' STRASSE ') + self.assertEqual(response.status_code, 400) + message = response.json['error'] if response.is_json else response.get_data(as_text=True) + self.assertIn('already in use', message) + self.assertEqual(list((self.workdir / 'Images').glob('*')), []) + self.assertEqual(list((self.workdir / 'Videos').glob('*')), []) + + def test_pending_and_downloading_jobs_reserve_names_but_failed_jobs_do_not(self): + for status in ('pending', 'downloading', 'failed', 'downloaded'): + with self.subTest(status=status): + with closing(sqlite3.connect(self.database)) as db: + db.execute('DELETE FROM youtube_download_job') + db.execute('DELETE FROM media') + db.execute('INSERT INTO youtube_download_job (youtube_download_job_url, ' + 'youtube_download_job_media_name, youtube_download_job_status) VALUES (?, ?, ?)', + ['https://youtu.be/video', 'Reserved', status]) + db.commit() + for kind in ('photo', 'video', 'stream', 'youtube'): + response = self.submit(kind, ' reserved ') + if status in ('pending', 'downloading'): + self.assertEqual(response.status_code, 400, kind) + else: + self.assertIn(response.status_code, (200, 303), kind) + # Isolate each submission so successful routes do not reserve the name for the next. + with closing(sqlite3.connect(self.database)) as db: + db.execute('DELETE FROM media') + db.execute("DELETE FROM youtube_download_job WHERE youtube_download_job_status = 'pending'") + db.commit() + + def test_names_must_be_nonempty_bounded_and_without_controls(self): + for name in ('', ' ', 'x' * 121, 'x\x00y', 'x\n'): + for kind in ('photo', 'video', 'stream', 'youtube'): + with self.subTest(name=name, kind=kind): + self.assertEqual(self.submit(kind, name).status_code, 400) + + def test_stream_url_validation_and_error_preserves_input(self): + for url in ('https://example.com/live', 'rtsp://192.168.1.20:8554/live', + 'rtmp://localhost/live', 'udp://239.1.1.1:1234', 'tcp://[::1]:8000'): + self.assertTrue(valid_stream_url(url), url) + for url in ('', 'file:///etc/passwd', 'https://', 'https://host:bad/path', + 'https://a b/test', 'http://example.com\\@evil/', 'https://-bad.host/test', + 'http://host:0/', 'concat:foo', 'http://host/\x00'): + self.assertFalse(valid_stream_url(url), repr(url)) + response = self.client.post('/configure/stream', data={ + 'buttonName': '', 'streamURL': 'not-a-url'}) + self.assertEqual(response.status_code, 400) + self.assertIn(b'<Name>', response.data) + self.assertIn(b'network stream URL', response.data) + self.assertEqual(self.client.post('/configure/stream', data={}).status_code, 400) + + def test_stream_is_atomic_and_checkbox_optional(self): + with closing(sqlite3.connect(self.database)) as db: + db.execute("""CREATE TRIGGER reject_option BEFORE INSERT ON media_playback_option + BEGIN SELECT RAISE(ABORT, 'option failure'); END""") + db.commit() + with self.assertLogs(self.app.logger, level='ERROR'): + response = self.client.post('/configure/stream', data={ + 'buttonName': 'Stream', 'streamURL': 'rtsp://example.com/live', 'fullScreen': 'on'}) + self.assertEqual(response.status_code, 503) + with closing(sqlite3.connect(self.database)) as db: + self.assertEqual(db.execute('SELECT COUNT(*) FROM media').fetchone(), (0,)) + response = self.client.post('/configure/stream', data={ + 'buttonName': 'Stream', 'streamURL': 'rtsp://example.com/live'}) + self.assertEqual(response.status_code, 303) + with closing(sqlite3.connect(self.database)) as db: + self.assertEqual(db.execute('SELECT media_name, media_uri FROM media').fetchall(), + [('Stream', 'rtsp://example.com/live')]) + + def test_youtube_urls_require_specific_video(self): + from blueprints.youtube_download.youtube_download import valid_youtube_url + for url in ('https://youtu.be/abc', 'https://youtube.com/watch?v=abc', + 'https://www.youtube.com/shorts/abc', 'https://youtube.com/live/abc', + 'https://youtube.com/embed/abc'): + self.assertTrue(valid_youtube_url(url), url) + for url in ('https://youtube.com/watch', 'https://youtube.com/watch?v=', + 'https://youtube.com/playlist?list=abc', 'https://youtube.com/channel/abc', + 'https://youtube.com/unrelated', 'https://youtu.be/', + 'https://youtube.com/watch?v=abc&v=def', 'https://youtube.com/watch?v=abc%0A'): + self.assertFalse(valid_youtube_url(url), url) + + def test_uploads_reject_invalid_and_mismatched_content(self): + cases = [('/upload/photo', b'not an image', 'image.png'), + ('/upload/photo', VIDEO, 'image.png'), + ('/upload/photo', PNG, 'image.jpg'), + ('/upload/video', b'not a video', 'video.mp4'), + ('/upload/video', PNG, 'video.mp4')] + for route, content, filename in cases: + with self.subTest(route=route, filename=filename): + response = self.client.post(route, data={'name': 'Name', 'files[]': (BytesIO(content), filename)}) + self.assertEqual(response.status_code, 400) + self.assertEqual(response.json['status'], 'FAILED') + self.assertEqual(list((self.workdir / 'Images').glob('*')), []) + self.assertEqual(list((self.workdir / 'Videos').glob('*')), []) + with closing(sqlite3.connect(self.database)) as db: + self.assertEqual(db.execute('SELECT COUNT(*) FROM media').fetchone(), (0,)) + + def test_audio_only_and_truncated_files_are_rejected(self): + buffer = BytesIO() + with wave.open(buffer, 'wb') as audio: + audio.setnchannels(1) + audio.setsampwidth(2) + audio.setframerate(8000) + audio.writeframes(b'\x00\x00' * 800) + for route, content, filename in ( + ('/upload/video', buffer.getvalue(), 'audio.mp4'), + ('/upload/photo', PNG[:35], 'truncated.png'), + ('/upload/video', VIDEO[:80], 'truncated.mp4') + ): + with self.subTest(filename=filename): + response = self.client.post(route, data={'name': 'Name', 'files[]': (BytesIO(content), filename)}) + self.assertEqual(response.status_code, 400) + self.assertEqual(list((self.workdir / 'Images').glob('*')), []) + self.assertEqual(list((self.workdir / 'Videos').glob('*')), []) + + def test_upload_unexpected_extra_files_are_rejected(self): + for route, content, filename in (('/upload/photo', PNG, 'photo.png'), + ('/upload/video', VIDEO, 'video.mp4')): + response = self.client.post(route, data={'name': 'Name', 'files[]': (BytesIO(content), filename), + 'extra': (BytesIO(b'bad'), 'other.txt')}) + self.assertEqual(response.status_code, 400) + + def test_probe_unavailable_or_timed_out_is_helpful_and_cleans_up(self): + for error in (FileNotFoundError(), subprocess.TimeoutExpired('ffprobe', 30)): + with self.subTest(error=error): + with patch('utilities.validation.subprocess.run', side_effect=error): + with self.assertLogs(self.app.logger, level='WARNING'): + response = self.submit('photo', 'Name') + self.assertEqual(response.status_code, 503) + self.assertIn('validat', response.json['error']) + self.assertEqual(list((self.workdir / 'Images').glob('*')), []) + + def test_corrupt_or_excessive_image_metadata_is_rejected(self): + for width, height in ((0, 10), (10000, 10000)): + report = json.dumps({'format': {'format_name': 'png_pipe'}, 'streams': [{ + 'codec_type': 'video', 'codec_name': 'png', 'width': width, 'height': height + }]}).encode() + with self.subTest(width=width, height=height): + with patch('utilities.validation.subprocess.run', return_value=subprocess.CompletedProcess([], 0, report)): + response = self.submit('photo', 'Name') + self.assertEqual(response.status_code, 400) + self.assertIn('dimensions', response.json['error']) + self.assertEqual(list((self.workdir / 'Images').glob('*')), []) + + def test_database_failure_reports_error_for_forms_and_listing(self): + with patch('utilities.database.sqlite.SQLite.query', side_effect=sqlite3.OperationalError('secret')): + for kind in ('stream', 'youtube'): + with self.subTest(kind=kind): + with self.assertLogs(self.app.logger, level='ERROR'): + response = self.submit(kind, 'Name') + self.assertEqual(response.status_code, 503) + self.assertIn(b'database', response.data) + self.assertNotIn(b'secret', response.data) + for endpoint in ('/youtube/jobs', '/media', '/media/status'): + with self.assertLogs(self.app.logger, level='ERROR'): + response = self.client.get(endpoint) + self.assertEqual(response.status_code, 503) + self.assertNotIn(b'secret', response.data) + + def test_concurrent_submissions_allow_only_one_name(self): + barrier = threading.Barrier(2) + def submit(kind): + with self.app.test_client() as client: + barrier.wait(timeout=5) + if kind == 'youtube': + return client.post('/youtube/download', data={ + 'media_name': 'Same Name', 'youtube_url': 'https://youtu.be/video'}).status_code + return client.post('/configure/stream', data={ + 'buttonName': 'same name', 'streamURL': 'https://example.com/stream'}).status_code + with ThreadPoolExecutor(max_workers=2) as executor: + results = list(executor.map(submit, ('youtube', 'stream'))) + self.assertCountEqual(results, [303, 400]) + + +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..3a92242 --- /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 index in range(2): + self.assertEqual(self.post_image(name=f'../../Display name {index}', 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..762803a --- /dev/null +++ b/test/upload_video_test.py @@ -0,0 +1,137 @@ +from contextlib import closing +import base64 +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] +VIDEO = base64.b64decode('AAAAHGZ0eXBpc29tAAACAGlzb21pc28ybXA0MQAAAAhmcmVlAAAAGW1kYXQAAAGzABAHAAABthYFGCPbfgAAAz9tb292AAAAbG12aGQAAAAAAAAAAAAAAAAAAAPoAAAD6AABAAABAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAACanRyYWsAAABcdGtoZAAAAAMAAAAAAAAAAAAAAAEAAAAAAAAD6AAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAEAAAAAAEAAAABAAAAAAACRlZHRzAAAAHGVsc3QAAAAAAAAAAQAAA+gAAAAAAAEAAAAAAeJtZGlhAAAAIG1kaGQAAAAAAAAAAAAAAAAAAEAAAABAAFXEAAAAAAAtaGRscgAAAAAAAAAAdmlkZQAAAAAAAAAAAAAAAFZpZGVvSGFuZGxlcgAAAAGNbWluZgAAABR2bWhkAAAAAQAAAAAAAAAAAAAAJGRpbmYAAAAcZHJlZgAAAAAAAAABAAAADHVybCAAAAABAAABTXN0YmwAAADpc3RzZAAAAAAAAAABAAAA2W1wNHYAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAEAAQAEgAAABIAAAAAAAAAAESTGF2YzYzLjEuMTAyIG1wZWc0AAAAAAAAAAAAAAAAAAAY//8AAABfZXNkcwAAAAADgICATgABAASAgIBAIBEAAAAAAw1AAAAAiAWAgIAuAAABsAEAAAG1iRMAAAEAAAABIADEjYgADQCEAhRjAAABskxhdmM2My4xLjEwMgaAgIABAgAAABBwYXNwAAAAAQAAAAEAAAAUYnRydAAAAAAAAw1AAAAAiAAAABhzdHRzAAAAAAAAAAEAAAABAABAAAAAABxzdHNjAAAAAAAAAAEAAAABAAAAAQAAAAEAAAAUc3RzegAAAAAAAAARAAAAAQAAABRzdGNvAAAAAAAAAAEAAAAsAAAAYXVkdGEAAABZbWV0YQAAAAAAAAAhaGRscgAAAAAAAAAAbWRpcmFwcGwAAAAAAAAAAAAAAAAsaWxzdAAAACSpdG9vAAAAHGRhdGEAAAABAAAAAExhdmY2My4xLjEwMg==') + + +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=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(), 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', len(VIDEO)): + response = self.post_video(content=VIDEO + b'x') + self.assertEqual(response.status_code, 413) + self.assertEqual(response.json['status'], 'FAILED') + self.assert_no_files_or_records() + self.assertEqual(self.post_video().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 index in range(2): + self.assertEqual(self.post_video(name=f'../../Display name {index}', 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() diff --git a/test/youtube_download_job_test.py b/test/youtube_download_job_test.py new file mode 100644 index 0000000..c4a83eb --- /dev/null +++ b/test/youtube_download_job_test.py @@ -0,0 +1,362 @@ +from contextlib import closing +import json +from pathlib import Path +import sqlite3 +import subprocess +import sys +import tempfile +import unittest +from unittest.mock import patch + +from youtube_downloader import claim_next_job, download_video, main, process_next_job + + +GENERATOR = Path(__file__).resolve().parents[1] / "sc_database_generator.py" + + +class YouTubeDownloadJobTest(unittest.TestCase): + def setUp(self): + self.directory = tempfile.TemporaryDirectory() + self.addCleanup(self.directory.cleanup) + self.workdir = Path(self.directory.name) + (self.workdir / "config.json").write_text(json.dumps({ + "database": {"type": "SQLite", "name": "test.db"} + })) + self.initialize_database() + self.db = sqlite3.connect(self.workdir / "test.db") + self.addCleanup(self.db.close) + + def initialize_database(self): + subprocess.run( + [sys.executable, str(GENERATOR)], + cwd=self.workdir, + check=True, + capture_output=True, + text=True + ) + + def insert_job(self, url="https://www.youtube.com/watch?v=test"): + return self.db.execute( + "INSERT INTO youtube_download_job (youtube_download_job_url) VALUES (?)", + [url] + ).lastrowid + + def test_new_job_defaults_to_pending(self): + job_id = self.insert_job() + self.assertEqual(self.db.execute( + "SELECT youtube_download_job_id, youtube_download_job_url, youtube_download_job_status " + "FROM youtube_download_job WHERE youtube_download_job_id = ?", + [job_id] + ).fetchone(), (job_id, "https://www.youtube.com/watch?v=test", "pending")) + + def test_job_can_be_marked_downloading_and_downloaded(self): + job_id = self.insert_job() + for status in ("downloading", "downloaded"): + self.db.execute( + "UPDATE youtube_download_job SET youtube_download_job_status = ? " + "WHERE youtube_download_job_id = ?", + [status, job_id] + ) + self.assertEqual(self.db.execute( + "SELECT youtube_download_job_status FROM youtube_download_job " + "WHERE youtube_download_job_id = ?", [job_id] + ).fetchone()[0], status) + + def test_invalid_or_null_status_is_rejected(self): + for status in ("unknown", None): + with self.subTest(status=status): + with self.assertRaises(sqlite3.IntegrityError): + self.db.execute( + "INSERT INTO youtube_download_job " + "(youtube_download_job_url, youtube_download_job_status) VALUES (?, ?)", + ["https://www.youtube.com/watch?v=test", status] + ) + + def test_retry_count_defaults_to_zero_and_rejects_invalid_values(self): + job_id = self.insert_job() + self.assertEqual(self.db.execute( + 'SELECT youtube_download_job_retry_count FROM youtube_download_job' + ).fetchone(), (0,)) + for count in (-1, None, 1.5): + with self.subTest(count=count): + with self.assertRaises(sqlite3.IntegrityError): + self.db.execute( + 'UPDATE youtube_download_job SET youtube_download_job_retry_count = ? ' + 'WHERE youtube_download_job_id = ?', [count, job_id] + ) + + def test_retry_limit_marks_failed_and_moves_to_next_job(self): + first = self.insert_job() + second = self.insert_job() + self.db.commit() + for failure_count in range(1, 5): + with patch('youtube_downloader.download_video', side_effect=OSError('Unavailable')): + with self.assertLogs('youtube_downloader', level='ERROR'): + self.assertFalse(process_next_job(self.db, self.workdir, max_retries=3)) + expected_status = 'pending' if failure_count <= 3 else 'failed' + self.assertEqual(self.db.execute( + 'SELECT youtube_download_job_status, youtube_download_job_retry_count ' + 'FROM youtube_download_job WHERE youtube_download_job_id = ?', [first] + ).fetchone(), (expected_status, failure_count)) + self.assertEqual(claim_next_job(self.db)[0], second) + self.assertIsNone(claim_next_job(self.db)) + self.assertEqual(self.db.execute('SELECT COUNT(*) FROM media').fetchone(), (0,)) + + def test_zero_retries_fails_after_first_attempt(self): + self.insert_job() + self.db.commit() + with patch('youtube_downloader.download_video', side_effect=OSError('Unavailable')): + with self.assertLogs('youtube_downloader', level='ERROR'): + self.assertFalse(process_next_job(self.db, self.workdir, max_retries=0)) + self.assertEqual(self.db.execute( + 'SELECT youtube_download_job_status, youtube_download_job_retry_count FROM youtube_download_job' + ).fetchone(), ('failed', 1)) + with patch('youtube_downloader.download_video') as download: + self.assertFalse(process_next_job(self.db, self.workdir, max_retries=0)) + download.assert_not_called() + + def test_pending_jobs_above_new_limit_are_skipped(self): + first = self.insert_job() + second = self.insert_job() + self.db.execute( + 'UPDATE youtube_download_job SET youtube_download_job_retry_count = 3 ' + 'WHERE youtube_download_job_id = ?', [first] + ) + self.db.commit() + self.assertEqual(claim_next_job(self.db, max_retries=1)[0], second) + self.assertEqual(self.db.execute( + 'SELECT youtube_download_job_status FROM youtube_download_job ' + 'WHERE youtube_download_job_id = ?', [first] + ).fetchone(), ('failed',)) + + def test_retry_count_persists_and_success_does_not_increment_it(self): + self.insert_job() + self.db.commit() + with patch('youtube_downloader.download_video', side_effect=OSError('Unavailable')): + with self.assertLogs('youtube_downloader', level='ERROR'): + process_next_job(self.db, self.workdir) + with closing(sqlite3.connect(self.workdir / 'test.db')) as restarted: + self.assertEqual(restarted.execute( + 'SELECT youtube_download_job_retry_count FROM youtube_download_job' + ).fetchone(), (1,)) + with patch('youtube_downloader.download_video', return_value=(self.workdir / 'video.mp4', 'Title')): + self.assertTrue(process_next_job(restarted, self.workdir)) + self.assertEqual(self.db.execute( + 'SELECT youtube_download_job_status, youtube_download_job_retry_count FROM youtube_download_job' + ).fetchone(), ('downloaded', 1)) + + def test_url_is_required(self): + with self.assertRaises(sqlite3.IntegrityError): + self.insert_job(url=None) + + def test_initialization_preserves_existing_records(self): + self.insert_job() + self.db.execute( + "INSERT INTO media (media_name, media_uri) VALUES (?, ?)", + ["Existing stream", "https://example.com/stream"] + ) + self.db.execute( + "INSERT INTO media_playback_option " + "(media_id, media_playback_option, media_playback_option_weight) " + "VALUES (1, '-fs', 1)" + ) + self.db.commit() + tables = ("media", "media_playback_option", "youtube_download_job") + before = {table: self.db.execute(f"SELECT * FROM {table}").fetchall() for table in tables} + self.initialize_database() + after = {table: self.db.execute(f"SELECT * FROM {table}").fetchall() for table in tables} + self.assertEqual(before, after) + self.assertEqual(self.db.execute( + "SELECT name FROM sqlite_master WHERE type='table' " + "AND name NOT LIKE 'sqlite_%' ORDER BY name" + ).fetchall(), [(table,) for table in tables]) + + def test_old_schema_is_migrated_without_losing_jobs(self): + self.db.execute('DROP TABLE youtube_download_job') + self.db.execute(""" + CREATE TABLE youtube_download_job ( + youtube_download_job_id INTEGER PRIMARY KEY AUTOINCREMENT, + youtube_download_job_url TEXT NOT NULL, + youtube_download_job_status TEXT NOT NULL DEFAULT 'pending' + CHECK(youtube_download_job_status IN ('pending', 'downloading', 'downloaded')) + ) + """) + job_id = self.insert_job() + self.db.commit() + self.initialize_database() + self.assertEqual(self.db.execute( + 'SELECT youtube_download_job_media_name FROM youtube_download_job ' + 'WHERE youtube_download_job_id = ?', [job_id] + ).fetchone(), ('',)) + + def test_previous_schema_migration_preserves_jobs_and_sequence(self): + self.db.execute('DROP TABLE youtube_download_job') + self.db.execute(""" + CREATE TABLE youtube_download_job ( + youtube_download_job_id INTEGER PRIMARY KEY AUTOINCREMENT, + youtube_download_job_url TEXT NOT NULL, + youtube_download_job_media_name TEXT NOT NULL DEFAULT '', + youtube_download_job_status TEXT NOT NULL DEFAULT 'pending' + CHECK(youtube_download_job_status IN ('pending', 'downloading', 'downloaded')) + ) + """) + for status in ('pending', 'downloading', 'downloaded'): + self.db.execute( + 'INSERT INTO youtube_download_job (youtube_download_job_url, ' + 'youtube_download_job_media_name, youtube_download_job_status) VALUES (?, ?, ?)', + ['https://youtu.be/test', 'Saved name', status] + ) + deleted_id = self.insert_job() + self.db.execute('DELETE FROM youtube_download_job WHERE youtube_download_job_id = ?', [deleted_id]) + self.db.commit() + before = self.db.execute('SELECT * FROM youtube_download_job ORDER BY 1').fetchall() + self.initialize_database() + self.assertEqual(self.db.execute( + 'SELECT youtube_download_job_id, youtube_download_job_url, youtube_download_job_media_name, ' + 'youtube_download_job_status FROM youtube_download_job ORDER BY 1' + ).fetchall(), before) + self.assertEqual(self.db.execute( + 'SELECT youtube_download_job_retry_count FROM youtube_download_job' + ).fetchall(), [(0,), (0,), (0,)]) + self.assertGreater(self.insert_job(), deleted_id) + self.db.execute("UPDATE youtube_download_job SET youtube_download_job_status = 'failed'") + self.db.commit() + self.initialize_database() + self.assertEqual(self.db.execute( + "SELECT COUNT(*) FROM youtube_download_job WHERE youtube_download_job_status = 'failed'" + ).fetchone(), (4,)) + + def test_worker_rejects_a_legacy_catalog_name_collision(self): + self.insert_job() + self.db.execute("UPDATE youtube_download_job SET youtube_download_job_media_name = 'VIDEO'") + self.db.execute("INSERT INTO media (media_name, media_uri) VALUES ('Video', 'existing')") + self.db.commit() + with patch('youtube_downloader.download_video', return_value=(self.workdir / 'video.mp4', 'Title')): + with self.assertLogs('youtube_downloader', level='ERROR'): + self.assertFalse(process_next_job(self.db, self.workdir, max_retries=0)) + self.assertEqual(self.db.execute('SELECT media_name, media_uri FROM media').fetchall(), [('Video', 'existing')]) + self.assertEqual(self.db.execute( + 'SELECT youtube_download_job_status, youtube_download_job_retry_count FROM youtube_download_job' + ).fetchone(), ('failed', 1)) + + def test_claims_oldest_pending_job_only_once(self): + first = self.insert_job() + second = self.insert_job() + self.db.commit() + self.assertEqual(claim_next_job(self.db)[0], first) + with closing(sqlite3.connect(self.workdir / 'test.db')) as other_worker: + self.assertEqual(claim_next_job(other_worker)[0], second) + self.assertIsNone(claim_next_job(other_worker)) + + def test_success_registers_local_file_and_requested_name(self): + job_id = self.insert_job() + self.db.execute( + 'UPDATE youtube_download_job SET youtube_download_job_media_name = ?', + ['My video'] + ) + self.db.commit() + storage = self.workdir / 'Videos' + def fake_download(command, **kwargs): + storage.mkdir(exist_ok=True) + path = storage / f'job-{job_id}.mkv' + path.touch() + return subprocess.CompletedProcess(command, 0, json.dumps({ + 'filepath': str(path), 'title': 'YouTube title' + }), '') + with patch('youtube_downloader.subprocess.run', side_effect=fake_download) as run: + self.assertTrue(process_next_job(self.db, storage)) + self.assertEqual(run.call_args.args[0][-2:], ['--', 'https://www.youtube.com/watch?v=test']) + self.assertIn('--no-playlist', run.call_args.args[0]) + self.assertEqual(self.db.execute('SELECT media_name, media_uri FROM media').fetchall(), + [('My video', str(storage / f'job-{job_id}.mkv'))]) + self.assertEqual(self.db.execute( + 'SELECT youtube_download_job_status FROM youtube_download_job' + ).fetchone(), ('downloaded',)) + with patch('youtube_downloader.subprocess.run') as run: + self.assertFalse(process_next_job(self.db, storage)) + run.assert_not_called() + + def test_blank_name_uses_video_title(self): + self.insert_job() + self.db.commit() + path = self.workdir / 'video.mp4' + with patch('youtube_downloader.download_video', return_value=(path, 'Video title')): + self.assertTrue(process_next_job(self.db, self.workdir)) + self.assertEqual(self.db.execute('SELECT media_name FROM media').fetchone(), ('Video title',)) + + def test_failed_download_returns_to_pending_without_media(self): + self.insert_job() + self.db.commit() + errors = [FileNotFoundError('yt-dlp missing'), + subprocess.CalledProcessError(1, ['yt-dlp'], stderr='Download failed')] + for error in errors: + with self.subTest(error=error): + with patch('youtube_downloader.subprocess.run', side_effect=error): + with self.assertLogs('youtube_downloader', level='ERROR'): + self.assertFalse(process_next_job(self.db, self.workdir)) + self.assertEqual(self.db.execute('SELECT COUNT(*) FROM media').fetchone(), (0,)) + self.assertEqual(self.db.execute( + 'SELECT youtube_download_job_status FROM youtube_download_job' + ).fetchone(), ('pending',)) + + def test_missing_or_outside_download_file_is_rejected(self): + for path in (self.workdir / 'Videos' / 'missing.mp4', GENERATOR): + with self.subTest(path=path): + result = subprocess.CompletedProcess([], 0, json.dumps({ + 'filepath': str(path), 'title': 'Title' + }), '') + with patch('youtube_downloader.subprocess.run', return_value=result): + with self.assertRaises(ValueError): + download_video(1, 'https://youtu.be/test', self.workdir / 'Videos') + + def test_interrupt_releases_job_without_registering_media(self): + self.insert_job() + self.db.commit() + with patch('youtube_downloader.download_video', side_effect=KeyboardInterrupt): + with self.assertRaises(KeyboardInterrupt): + process_next_job(self.db, self.workdir) + self.assertEqual(self.db.execute( + 'SELECT youtube_download_job_status FROM youtube_download_job' + ).fetchone(), ('pending',)) + self.assertEqual(self.db.execute('SELECT COUNT(*) FROM media').fetchone(), (0,)) + self.assertEqual(self.db.execute( + 'SELECT youtube_download_job_retry_count FROM youtube_download_job' + ).fetchone(), (0,)) + + @patch('youtube_downloader.logging.basicConfig') + def test_main_polls_with_paths_relative_to_config(self, configure_logging): + (self.workdir / 'config.json').write_text(json.dumps({ + 'database': {'type': 'SQLite', 'name': 'test.db'}, + 'youtube_download_location': 'CustomVideos', + 'youtube_download_max_retries': 2 + })) + with patch('sys.argv', ['youtube_downloader.py', '--config', + str(self.workdir / 'config.json'), '--poll-interval', '2']): + with patch('youtube_downloader.process_next_job', return_value=False) as process: + with patch('youtube_downloader.time.sleep', side_effect=KeyboardInterrupt) as sleep: + with self.assertLogs('youtube_downloader', level='INFO'): + main() + self.assertEqual(process.call_args.args[1], self.workdir / 'CustomVideos') + self.assertEqual(process.call_args.args[2], 2) + self.assertTrue((self.workdir / 'CustomVideos').is_dir()) + sleep.assert_called_once_with(2.0) + + def test_media_insert_is_rolled_back_if_job_update_fails(self): + self.insert_job() + self.db.execute(""" + CREATE TRIGGER reject_completion BEFORE UPDATE ON youtube_download_job + WHEN NEW.youtube_download_job_status = 'downloaded' + BEGIN SELECT RAISE(ABORT, 'Simulated database failure'); END + """) + self.db.commit() + with patch('youtube_downloader.download_video', return_value=(self.workdir / 'file.mp4', 'Title')): + with self.assertLogs('youtube_downloader', level='ERROR'): + self.assertFalse(process_next_job(self.db, self.workdir)) + self.assertEqual(self.db.execute('SELECT COUNT(*) FROM media').fetchone(), (0,)) + self.assertEqual(self.db.execute( + 'SELECT youtube_download_job_status FROM youtube_download_job' + ).fetchone(), ('pending',)) + + +if __name__ == "__main__": + unittest.main() diff --git a/test/youtube_download_web_test.py b/test/youtube_download_web_test.py new file mode 100644 index 0000000..129f5b5 --- /dev/null +++ b/test/youtube_download_web_test.py @@ -0,0 +1,125 @@ +from contextlib import closing +import json +import os +from pathlib import Path +import runpy +import sqlite3 +import subprocess +import sys +import tempfile +import unittest + +from utilities.tools import get_db + + +ROOT = Path(__file__).resolve().parents[1] + + +class YouTubeDownloadWebTest(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.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_directory = Path.cwd() + try: + os.chdir(self.workdir) + self.app = runpy.run_path(str(ROOT / 'sc_webserver.py'))['app'] + finally: + os.chdir(original_directory) + self.app.config['TESTING'] = True + self.client = self.app.test_client() + + def test_home_and_form_links(self): + home = self.client.get('/') + self.assertEqual(home.status_code, 200) + self.assertIn(b'/youtube/download', home.data) + self.assertIn(b'/youtube/jobs', home.data) + form = self.client.get('/youtube/download') + self.assertEqual(form.status_code, 200) + self.assertIn(b'name="media_name"', form.data) + self.assertIn(b'name="youtube_url"', form.data) + + def test_submission_queues_job_and_redirects_to_list(self): + response = self.client.post('/youtube/download', data={ + 'media_name': ' Sunday video ', + 'youtube_url': ' https://youtu.be/example ' + }) + self.assertEqual(response.status_code, 303) + self.assertTrue(response.location.endswith('/youtube/jobs')) + with closing(sqlite3.connect(self.database)) as db: + self.assertEqual(db.execute( + 'SELECT youtube_download_job_media_name, youtube_download_job_url, ' + 'youtube_download_job_status, youtube_download_job_retry_count ' + 'FROM youtube_download_job' + ).fetchall(), [('Sunday video', 'https://youtu.be/example', 'pending', 0)]) + self.assertEqual(db.execute('SELECT COUNT(*) FROM media').fetchone(), (0,)) + self.assertIn(b'Sunday video', self.client.get(response.location).data) + + def test_invalid_submissions_do_not_queue_jobs(self): + cases = [ + {}, {'media_name': ' ', 'youtube_url': 'https://youtu.be/test'}, + {'media_name': 'Video'}, + ] + for url in ('not a url', 'file:///video', 'https://example.com/video', + 'https://youtube.com.evil.example/watch?v=test', + 'https://youtube.com@evil.example/watch?v=test', + 'https://www.youtube.com/', 'https://youtu.be:bad/test'): + cases.append({'media_name': 'Video', 'youtube_url': url}) + for data in cases: + with self.subTest(data=data): + response = self.client.post('/youtube/download', data=data) + self.assertEqual(response.status_code, 400) + self.assertIn(b'role="alert"', response.data) + with closing(sqlite3.connect(self.database)) as db: + self.assertEqual(db.execute('SELECT COUNT(*) FROM youtube_download_job').fetchone(), (0,)) + + def test_list_hides_completed_only_until_opted_in(self): + with closing(sqlite3.connect(self.database)) as db: + for status in ('pending', 'downloading', 'failed', 'downloaded'): + db.execute( + 'INSERT INTO youtube_download_job (youtube_download_job_url, ' + 'youtube_download_job_media_name, youtube_download_job_status) VALUES (?, ?, ?)', + ['https://youtu.be/test', 'name-' + status, status] + ) + db.commit() + for suffix in ('', '?show_completed=0', '?show_completed=1'): + response = self.client.get('/youtube/jobs' + suffix) + self.assertEqual(response.status_code, 200) + for status in ('pending', 'downloading', 'failed'): + self.assertIn(('name-' + status).encode(), response.data) + if suffix == '?show_completed=1': + self.assertIn(b'name-downloaded', response.data) + self.assertIn(b'value="1" checked', response.data) + else: + self.assertNotIn(b'name-downloaded', response.data) + + def test_empty_jobs_page(self): + self.assertIn(b'No download jobs to show.', self.client.get('/youtube/jobs').data) + + def test_user_input_is_escaped_and_preserved_on_error(self): + name = '' + response = self.client.post('/youtube/download', data={'media_name': name, 'youtube_url': 'bad'}) + self.assertIn(b'<script>', response.data) + self.assertNotIn(name.encode(), response.data) + self.client.post('/youtube/download', data={'media_name': name, 'youtube_url': 'https://youtu.be/test'}) + response = self.client.get('/youtube/jobs') + self.assertIn(b'<script>', response.data) + self.assertNotIn(name.encode(), response.data) + + def test_request_scoped_database_is_closed(self): + with self.app.app_context(): + db = get_db() + db.query('SELECT 1') + with self.assertRaises(sqlite3.ProgrammingError): + db.query('SELECT 1') + + +if __name__ == '__main__': + unittest.main() diff --git a/utilities/media_deletion.py b/utilities/media_deletion.py new file mode 100644 index 0000000..9372cec --- /dev/null +++ b/utilities/media_deletion.py @@ -0,0 +1,65 @@ +"""Plan local-file removal conservatively; never recursively delete a directory.""" + +import hashlib +import json +from pathlib import Path +from urllib.parse import unquote, urlsplit + + +def local_media_path(uri, directory): + if not uri or not uri.strip() or '\x00' in uri: + return None + try: + parsed = urlsplit(uri) + except ValueError: + return None # An invalid legacy URI must never be treated as a deletion path. + if parsed.scheme == 'file': + if parsed.netloc.lower() not in ('', 'localhost') or parsed.query or parsed.fragment: + return None + uri = unquote(parsed.path) + elif parsed.scheme: + return None + if '\x00' in uri: + return None + return Path(directory) / uri + + +def deletion_plan(db, media, directory, config): + """media is (id, name, uri, active, default). Return a message and optional file.""" + plan = {'path': None, 'reason': 'remote', 'identity': None} + source = local_media_path(media[2], directory) + if source is None: + plan['message'] = 'Only the database record will be removed. No stored file is associated with this source.' + return plan + resolved = source.resolve() + roots = [(Path(directory) / config.get(key, default)).resolve() for key, default in ( + ('image_upload_location', 'Images'), ('youtube_download_location', 'Videos'), + ('upload_location', 'uploads') + )] + if not any(resolved.is_relative_to(root) and resolved != root for root in roots): + plan.update(reason='outside', message='This file is outside managed media storage. Its database record will be removed, but the file will be kept.') + return plan + if source.is_symlink(): + plan.update(reason='symlink', message='This source is a symbolic link. Its database record will be removed, but the link and target file will be kept.') + return plan + if not resolved.exists(): + plan.update(reason='missing', message='The stored file is already missing. Its database record will be removed.') + return plan + if not resolved.is_file(): + plan.update(reason='directory', message='This source is not a regular file. Its database record will be removed, but the source will be kept.') + return plan + for other_id, other_uri in db.query('SELECT media_id, media_uri FROM media WHERE media_id != ?', [media[0]])[1]: + other = local_media_path(other_uri, directory) + if other is not None and other.resolve() == resolved: + plan.update(reason='shared', message='Another media item uses this file. Only this database record will be removed; the shared file will be kept.') + return plan + stat = resolved.stat() + plan.update(path=resolved, reason='managed', + identity=(stat.st_dev, stat.st_ino, stat.st_size, stat.st_mtime_ns), + message='The stored file will be permanently deleted from the server to free its storage.') + return plan + + +def confirmation_version(media, plan): + value = [list(media), plan['reason'], str(plan['path']), plan['identity']] + return hashlib.sha256(json.dumps(value).encode()).hexdigest() diff --git a/utilities/tools.py b/utilities/tools.py index 357ad1b..7617379 100644 --- a/utilities/tools.py +++ b/utilities/tools.py @@ -1,12 +1,13 @@ from flask import g, current_app from .database.sqlite import SQLite -import json +from pathlib import Path def get_db(): db = getattr(g, "_database", None) if db is None: if str(current_app.config["config"]["database"]["type"]).casefold() == "SQLite".casefold(): - db = g._database = SQLite(current_app.config["config"]["database"]["name"]) + database = Path(current_app.config['CONFIG_DIRECTORY']) / current_app.config['config']['database']['name'] + db = g._database = SQLite(str(database)) return db \ No newline at end of file diff --git a/utilities/validation.py b/utilities/validation.py new file mode 100644 index 0000000..9e8f935 --- /dev/null +++ b/utilities/validation.py @@ -0,0 +1,155 @@ +"""Validation shared by media submission routes and the download worker.""" + +from contextlib import contextmanager +import json +from pathlib import Path +import re +import sqlite3 +import subprocess +import unicodedata +from urllib.parse import urlsplit + + +MAX_MEDIA_NAME_LENGTH = 120 +DUPLICATE_NAME_MESSAGE = 'That media name is already in use or reserved by a download. Please choose another name.' + + +class ValidationError(ValueError): + pass + + +class ValidationUnavailable(Exception): + pass + + +def validate_media_name(value): + name = unicodedata.normalize('NFC', value) + if any(unicodedata.category(char).startswith('C') for char in name): + raise ValidationError('Media names cannot contain control characters.') + name = name.strip() + if not name: + raise ValidationError('Please enter a media name.') + if len(name) > MAX_MEDIA_NAME_LENGTH: + raise ValidationError(f'Media names must be at most {MAX_MEDIA_NAME_LENGTH} characters.') + return name + + +def name_key(value): + return unicodedata.normalize('NFC', value or '').strip().casefold() + + +def ensure_catalog_name_available(connection, name): + key = name_key(name) + existing = connection.execute('SELECT media_name FROM media') + if any(name_key(row[0]) == key for row in existing): + raise ValidationError(DUPLICATE_NAME_MESSAGE) + + +def ensure_name_available(connection, name): + """Call while holding a write transaction so checks and insertion are atomic.""" + ensure_catalog_name_available(connection, name) + key = name_key(name) + jobs = connection.execute(""" + SELECT youtube_download_job_media_name FROM youtube_download_job + WHERE youtube_download_job_status IN ('pending', 'downloading') + """) + if any(name_key(row[0]) == key for row in jobs): + raise ValidationError(DUPLICATE_NAME_MESSAGE) + + +@contextmanager +def write_transaction(db): + db.query('BEGIN IMMEDIATE') + try: + yield db + db.query('COMMIT') + except BaseException: + try: + db.query('ROLLBACK') + except sqlite3.Error: + pass # Keep the original failure; SQLite may already have rolled back. + raise + + +def valid_stream_url(value): + """Accept network streams, not local paths or arbitrary FFmpeg protocols.""" + if not value or any(char.isspace() or unicodedata.category(char).startswith('C') for char in value): + return False + if '\\' in value: + return False + try: + url = urlsplit(value) + if url.scheme.lower() not in {'http', 'https', 'rtsp', 'rtmp', 'rtmps', 'udp', 'tcp'}: + return False + hostname = url.hostname + if not hostname or url.port == 0: + return False + if any(char in hostname for char in '/?#%@'): + return False + # IPv6 is parsed by urlsplit; hostnames must not contain stray brackets. + if ':' not in hostname: + hostname = hostname.encode('idna').decode('ascii') + if len(hostname) > 253 or not all( + re.fullmatch(r'[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?', part) + for part in hostname.rstrip('.').split('.') + ): + return False + return True + except (ValueError, UnicodeError): + return False + + +IMAGE_CODECS = { + '.jpg': {'mjpeg'}, '.jpeg': {'mjpeg'}, '.png': {'png', 'apng'}, + '.webp': {'webp'}, '.bmp': {'bmp'}, '.tif': {'tiff'}, '.tiff': {'tiff'}, + '.gif': {'gif'}, +} + + +def validate_upload_content(path, kind, extension): + """Probe local content, rejecting mismatched/invalid files and network inputs.""" + try: + result = subprocess.run( + ['ffprobe', '-v', 'error', '-protocol_whitelist', 'file,pipe', + '-show_entries', 'format=format_name:stream=codec_type,codec_name,width,height', + '-of', 'json', str(Path(path))], + check=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, + timeout=30 + ) + metadata = json.loads(result.stdout) + except FileNotFoundError as error: + raise ValidationUnavailable('File validation is unavailable. Please contact the administrator.') from error + except (OSError, subprocess.TimeoutExpired) as error: + raise ValidationUnavailable('Unable to validate the uploaded file. Please try again.') from error + except (subprocess.CalledProcessError, ValueError) as error: + raise ValidationError(f'The uploaded file is not a valid {kind}.') from error + streams = metadata.get('streams', []) + video_streams = [stream for stream in streams if stream.get('codec_type') == 'video'] + formats = set(metadata.get('format', {}).get('format_name', '').split(',')) + if kind == 'image': + if not video_streams or video_streams[0].get('codec_name') not in IMAGE_CODECS[extension]: + raise ValidationError('The image content does not match its file extension or is invalid.') + elif not video_streams or formats.intersection({'image2', 'image2pipe', 'png_pipe', 'jpeg_pipe', + 'webp_pipe', 'bmp_pipe', 'tiff_pipe', 'gif', 'apng'}): + raise ValidationError('The uploaded file must contain a valid video, not an image or audio-only file.') + + width = video_streams[0].get('width', 0) + height = video_streams[0].get('height', 0) + if kind == 'image' and (not isinstance(width, int) or not isinstance(height, int) + or width <= 0 or height <= 0 or width * height > 50_000_000): + raise ValidationError('The image dimensions are invalid or exceed 50 megapixels.') + # Probe metadata alone can accept a truncated image. Decode one frame; this is + # bounded and avoids decoding an entire large video or animated image. + try: + subprocess.run( + ['ffmpeg', '-hide_banner', '-v', 'error', '-xerror', '-nostdin', + '-protocol_whitelist', 'file,pipe', '-i', str(Path(path)), + '-map', '0:v:0', '-frames:v', '1', '-f', 'null', '-'], + check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=30 + ) + except FileNotFoundError as error: + raise ValidationUnavailable('File validation is unavailable. Please contact the administrator.') from error + except (OSError, subprocess.TimeoutExpired) as error: + raise ValidationUnavailable('Unable to validate the uploaded file. Please try again.') from error + except subprocess.CalledProcessError as error: + raise ValidationError(f'The uploaded file is not a valid {kind}.') from error diff --git a/youtube_downloader.py b/youtube_downloader.py new file mode 100644 index 0000000..519bb45 --- /dev/null +++ b/youtube_downloader.py @@ -0,0 +1,156 @@ +"""Poll queued YouTube jobs and register completed downloads in the media catalog.""" + +import argparse +import json +import logging +from pathlib import Path +import sqlite3 +import subprocess +import time + +from utilities.validation import ensure_catalog_name_available, validate_media_name + + +LOGGER = logging.getLogger(__name__) + + +def claim_next_job(db, max_retries=3): + """Claim the oldest pending job without letting another worker claim it too.""" + with db: + db.execute("BEGIN IMMEDIATE") + # Also honor a lower retry limit configured after earlier failures. + db.execute(""" + UPDATE youtube_download_job SET youtube_download_job_status = 'failed' + WHERE youtube_download_job_status = 'pending' + AND youtube_download_job_retry_count > ? + """, [max_retries]) + job = db.execute(""" + SELECT youtube_download_job_id, youtube_download_job_url, + youtube_download_job_media_name + FROM youtube_download_job + WHERE youtube_download_job_status = 'pending' + ORDER BY youtube_download_job_id + LIMIT 1 + """).fetchone() + if job is not None: + db.execute(""" + UPDATE youtube_download_job SET youtube_download_job_status = 'downloading' + WHERE youtube_download_job_id = ? + """, [job[0]]) + return job + + +def download_video(job_id, url, storage): + """Return the final file path and title reported by yt-dlp after postprocessing.""" + storage = Path(storage).resolve() + storage.mkdir(parents=True, exist_ok=True) + result = subprocess.run( + [ + 'yt-dlp', '--ignore-config', '--no-playlist', '--no-simulate', + '--no-progress', + '--output', str(storage / f'job-{job_id}.%(ext)s'), + '--print', 'after_move:{"filepath": %(filepath)j, "title": %(title)j}', + '--', url + ], + check=True, + capture_output=True, + text=True + ) + reports = [line for line in result.stdout.splitlines() if line.strip()] + if len(reports) != 1: + raise ValueError('Expected exactly one completed video from yt-dlp') + report = json.loads(reports[0]) + path = Path(report['filepath']).resolve() + if not path.is_relative_to(storage) or not path.is_file(): + raise ValueError('yt-dlp did not produce a video file inside the storage directory') + return path, report['title'] + + +def process_next_job(db, storage, max_retries=3): + """Process one job. Return False when idle or after a failed attempt.""" + job = claim_next_job(db, max_retries) + if job is None: + return False + job_id, url, requested_name = job + completed = False + try: + LOGGER.info('Downloading job %s: %s', job_id, url) + path, title = download_video(job_id, url, storage) + media_name = validate_media_name(requested_name.strip() or title) + # Check existing catalog names under the same write lock as completion. + # The job's own reservation is intentionally not treated as a conflict. + with db: + db.execute('BEGIN IMMEDIATE') + ensure_catalog_name_available(db, media_name) + db.execute( + 'INSERT INTO media (media_name, media_uri) VALUES (?, ?)', + [media_name, str(path)] + ) + db.execute(""" + UPDATE youtube_download_job SET youtube_download_job_status = 'downloaded' + WHERE youtube_download_job_id = ? + """, [job_id]) + completed = True + LOGGER.info('Completed job %s: %s', job_id, path) + return True + except (OSError, ValueError, KeyError, TypeError, subprocess.CalledProcessError, sqlite3.Error) as error: + with db: + db.execute(""" + UPDATE youtube_download_job + SET youtube_download_job_retry_count = youtube_download_job_retry_count + 1, + youtube_download_job_status = CASE + WHEN youtube_download_job_retry_count + 1 > ? THEN 'failed' + ELSE 'pending' + END + WHERE youtube_download_job_id = ? AND youtube_download_job_status = 'downloading' + """, [max_retries, job_id]) + LOGGER.exception('Job %s attempt failed (retry limit: %s)', job_id, max_retries) + if isinstance(error, subprocess.CalledProcessError): + LOGGER.error('yt-dlp: %s', error.stderr) + return False + finally: + # This also releases the claim on a normal Ctrl+C interruption. + if not completed: + with db: + db.execute(""" + UPDATE youtube_download_job SET youtube_download_job_status = 'pending' + WHERE youtube_download_job_id = ? AND youtube_download_job_status = 'downloading' + """, [job_id]) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--config', type=Path, default=Path(__file__).with_name('config.json')) + parser.add_argument('--poll-interval', type=float, default=5.0, help='Idle/retry delay in seconds (default: 5)') + args = parser.parse_args() + if not 0 < args.poll_interval < float('inf'): + parser.error('--poll-interval must be a positive, finite number') + logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s') + 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 download worker currently supports only SQLite') + max_retries = config.get('youtube_download_max_retries', 3) + if type(max_retries) is not int or max_retries < 0: + parser.error('youtube_download_max_retries must be a non-negative integer') + # Relative paths are anchored to config.json, not the caller's directory. + database = config_path.parent / config['database']['name'] + storage = config_path.parent / config.get('youtube_download_location', 'Videos') + if not database.is_file(): + parser.error('Database does not exist; run sc_database_generator.py first') + storage.mkdir(parents=True, exist_ok=True) + db = sqlite3.connect(database, timeout=30) + try: + LOGGER.info('Watching for download jobs; storage: %s', storage) + while True: + if not process_next_job(db, storage, max_retries): + time.sleep(args.poll_interval) + except KeyboardInterrupt: + LOGGER.info('Download worker stopped') + finally: + db.close() + + +if __name__ == '__main__': + main()