From a3f55a8c356faffa30e8a881b5eeef29af970c43 Mon Sep 17 00:00:00 2001 From: Bradley Date: Thu, 12 Nov 2026 20:20:14 -0500 Subject: [PATCH] First work session with OpenCode and OpenRouter --- .gitignore | 3 +- README.md | 102 ++++- TODO.md | 83 +++++ .../configure_stream/configure_stream.py | 2 +- blueprints/home/home.html | 4 +- .../upload_slideshow/upload_slideshow.html | 46 --- .../upload_slideshow/upload_slideshow.py | 48 --- .../youtube_download/youtube_download.py | 67 ++++ blueprints/youtube_download/youtube_jobs.html | 49 +++ .../youtube_download/youtube_request.html | 37 ++ config.json | 4 +- sc_database_generator.py | 76 ++-- sc_webserver.py | 12 +- scdb.db | Bin 24576 -> 24576 bytes test/youtube_download_job_test.py | 349 ++++++++++++++++++ test/youtube_download_web_test.py | 125 +++++++ youtube_downloader.py | 151 ++++++++ 17 files changed, 1035 insertions(+), 123 deletions(-) create mode 100644 TODO.md delete mode 100644 blueprints/upload_slideshow/upload_slideshow.html delete mode 100644 blueprints/upload_slideshow/upload_slideshow.py create mode 100644 blueprints/youtube_download/youtube_download.py create mode 100644 blueprints/youtube_download/youtube_jobs.html create mode 100644 blueprints/youtube_download/youtube_request.html create mode 100644 test/youtube_download_job_test.py create mode 100644 test/youtube_download_web_test.py create mode 100644 youtube_downloader.py diff --git a/.gitignore b/.gitignore index abd32e8..fd7a08d 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ -*__pycache__* \ No newline at end of file +*__pycache__* +/Videos/ \ No newline at end of file diff --git a/README.md b/README.md index 962e769..d7c083f 100644 --- a/README.md +++ b/README.md @@ -10,4 +10,104 @@ 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 + +## 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 -v +``` \ No newline at end of file diff --git a/TODO.md b/TODO.md new file mode 100644 index 0000000..367dbb3 --- /dev/null +++ b/TODO.md @@ -0,0 +1,83 @@ +# 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 and media-storage +foundation; playback and device control are 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] Implement static-image uploads that save a file and create a 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 + +- [ ] Populate the home page with saved media and actionable playback buttons. +- [ ] Connect the existing placeholder controls to backend actions. +- [ ] Add input validation for media names, duplicate names, stream URLs, and + uploaded files. +- [ ] Ensure upload destinations remain inside the configured upload directory. +- [ ] 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 + +- [ ] Implement FFPlay-based video and audio playback. +- [ ] Display uploaded static images. +- [ ] Play registered streams and apply stored playback options. +- [ ] Support uploading and playing local video files. +- [x] 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. +- [ ] Track active and default media and implement their intended behavior. +- [ ] 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.py b/blueprints/configure_stream/configure_stream.py index dcf842c..9943df1 100644 --- a/blueprints/configure_stream/configure_stream.py +++ b/blueprints/configure_stream/configure_stream.py @@ -29,5 +29,5 @@ def upload(): ["media_id", "media_playback_option", "media_playback_option_weight"], [new_id, "-fs", 1] ) - + return redirect("/") diff --git a/blueprints/home/home.html b/blueprints/home/home.html index 05d1193..b5b124d 100644 --- a/blueprints/home/home.html +++ b/blueprints/home/home.html @@ -29,11 +29,11 @@
Upload a Static Image Configure a Stream -
- + Get Video from YouTube + YouTube Download Jobs
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/youtube_download/youtube_download.py b/blueprints/youtube_download/youtube_download.py new file mode 100644 index 0000000..14c779e --- /dev/null +++ b/blueprints/youtube_download/youtube_download.py @@ -0,0 +1,67 @@ +from urllib.parse import urlsplit + +from flask import Blueprint, request, render_template, redirect, url_for +from utilities.tools import get_db + + +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', '').strip() + youtube_url = request.form.get('youtube_url', '').strip() + if not media_name: + error = 'Please enter a name for the media item.' + elif not valid_youtube_url(youtube_url): + error = 'Please enter a valid YouTube video URL (youtube.com or youtu.be).' + else: + get_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) + + 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): + try: + parsed = urlsplit(value) + return ( + parsed.scheme in ('http', 'https') + and parsed.hostname in ('youtube.com', 'www.youtube.com', 'm.youtube.com', + 'music.youtube.com', 'youtu.be', 'www.youtu.be') + and not parsed.username and not parsed.password + and parsed.port in (None, 80, 443) + and bool(parsed.path.strip('/')) + and not any(character.isspace() for character in value) + ) + 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..024d686 --- /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..d9d1547 100644 --- a/config.json +++ b/config.json @@ -3,5 +3,7 @@ "type": "SQLite", "name": "scdb.db" }, - "upload_location": "uploads" + "upload_location": "uploads", + "youtube_download_location": "Videos", + "youtube_download_max_retries": 3 } \ No newline at end of file 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..8d56527 100644 --- a/sc_webserver.py +++ b/sc_webserver.py @@ -1,7 +1,8 @@ -from flask import Flask +from flask import Flask, g from blueprints.home.home import home_bp from blueprints.upload_photo.upload_photo import upload_photo_bp from blueprints.configure_stream.configure_stream import configure_stream_bp +from blueprints.youtube_download.youtube_download import youtube_download_bp import os import json @@ -17,6 +18,15 @@ app.config["config"] = config_json app.register_blueprint(home_bp) app.register_blueprint(upload_photo_bp) app.register_blueprint(configure_stream_bp) +app.register_blueprint(youtube_download_bp) + + +@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 1bf26f175c816cfb003e74f896dfa7f9325dd319..0924d7551e5773ca374860efd071651190dc1e7a 100644 GIT binary patch delta 726 zcmZoTz}Rqrae}m<00RR98x%7FY2JxC#^M4DdQ;Ev0(mT4DGYqAe8xO?xKcRQZWa`H z$64P}%E~ToYRcHjTauWRlUkWyT2h*n8lRG1o|luKm=d3rpM*_}#W~2;F~n6N#L>ye zRY3`x5+wx%1e5RROD%Fx*eq!9o`2#5K>(9IbDxgU!XmBY&0h-L@gM6lwdwG?4;pWDd7G+NU&nFp$5XsC-Nv%-u^b2uy zcMVc-_HcFf)<82S9-_w1R>4qH2bX2>DXBTBC8;TsE&1i^5ynGBffgue80Y{E&;%Qx z*_^=4F0QZ7*p`pv|AL~_g2bZ4lFa-(h!c>E09i}UUjP6A diff --git a/test/youtube_download_job_test.py b/test/youtube_download_job_test.py new file mode 100644 index 0000000..3b05bd5 --- /dev/null +++ b/test/youtube_download_job_test.py @@ -0,0 +1,349 @@ +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_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/youtube_downloader.py b/youtube_downloader.py new file mode 100644 index 0000000..8d9e5c2 --- /dev/null +++ b/youtube_downloader.py @@ -0,0 +1,151 @@ +"""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 + + +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 = requested_name.strip() or title + # Insert the media and finish the job together, or roll both changes back. + with db: + 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()