"""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()