#!/usr/bin/env python3 """ Downloader module for yt-ops-client. """ import json import logging import subprocess import sys from typing import Dict logger = logging.getLogger(__name__) def download_with_config(url: str, config: Dict) -> int: """ Download a video using yt-dlp with the given configuration. Args: url: The URL to download config: A dictionary of yt-dlp options Returns: Exit code (0 for success, non-zero for failure) """ # Build the command cmd = ['yt-dlp'] # Convert config to command-line arguments for key, value in config.items(): if isinstance(value, bool): if value: cmd.append(f'--{key}') else: cmd.append(f'--no-{key}') elif isinstance(value, (int, float, str)): cmd.append(f'--{key}') cmd.append(str(value)) elif isinstance(value, dict): # Handle nested options (like postprocessor) # For simplicity, convert to JSON string cmd.append(f'--{key}') cmd.append(json.dumps(value)) elif value is None: # Skip None values continue else: logger.warning(f"Unsupported config value type for key '{key}': {type(value)}") cmd.append(f'--{key}') cmd.append(str(value)) cmd.append(url) # Run the command logger.info(f"Running command: {' '.join(cmd)}") try: result = subprocess.run(cmd, check=True) return result.returncode except subprocess.CalledProcessError as e: logger.error(f"yt-dlp failed with exit code {e.returncode}") return e.returncode except FileNotFoundError: logger.error("yt-dlp not found. Please install yt-dlp first.") return 1 except Exception as e: logger.error(f"Unexpected error: {e}") return 1