using System.Diagnostics; using System.Text.Json; using ClipForge.Core.Interfaces.Services; using Microsoft.Extensions.Logging; namespace ClipForge.Infrastructure.Services; /// /// Downloads clips from YouTube using yt-dlp. /// Strategy: search for relevant videos, download them, then use FFmpeg to cut segments. /// public class YouTubeMediaService : IStockMediaService { private readonly ILogger _logger; public YouTubeMediaService(ILogger logger) { _logger = logger; } public async Task DownloadVideoAsync(string query, string outputDir, CancellationToken ct = default) { var clips = await DownloadMultipleVideosAsync(query, 1, outputDir, ct); return clips.FirstOrDefault() ?? string.Empty; } public async Task> DownloadMultipleVideosAsync(string query, int count, string outputDir, CancellationToken ct = default) { _logger.LogInformation("YouTube: searching '{Query}', need {Count} clips", query, count); Directory.CreateDirectory(outputDir); var downloadedFiles = new List(); // Search YouTube for relevant videos var searchCount = Math.Max(count * 2, 6); var args = $"\"ytsearch{searchCount}:{query}\" --dump-json --flat-playlist --no-download --quiet --no-warnings --no-check-certificates"; var searchOutput = await RunAndGetOutputAsync(args, ct); if (string.IsNullOrEmpty(searchOutput)) return downloadedFiles; var videos = new List<(string Id, string Title)>(); foreach (var line in searchOutput.Split('\n', StringSplitOptions.RemoveEmptyEntries)) { try { using var doc = JsonDocument.Parse(line.Trim()); var root = doc.RootElement; var id = root.TryGetProperty("id", out var idProp) ? idProp.GetString() ?? "" : ""; var title = root.TryGetProperty("title", out var t) ? t.GetString() ?? "" : ""; var duration = root.TryGetProperty("duration", out var d) ? d.GetDouble() : 0; // Skip very short (<15s) or very long (>600s) videos if (!string.IsNullOrEmpty(id) && duration > 15 && duration < 600) { videos.Add((id, title)); _logger.LogInformation(" Found: '{Title}' ({Duration}s)", title[..Math.Min(60, title.Length)], duration); } } catch { } } // Download videos and cut 8-second segments from different parts foreach (var video in videos.Take(count + 2)) { if (downloadedFiles.Count >= count) break; var outputFile = Path.Combine(outputDir, $"{Guid.NewGuid()}.mp4"); var url = $"https://www.youtube.com/watch?v={video.Id}"; // Download full video (limited duration) var dlArgs = $"\"{url}\" " + $"-f \"bestvideo[height<=720][ext=mp4]+bestaudio[ext=m4a]/best[height<=720][ext=mp4]/best\" " + $"--merge-output-format mp4 " + $"-o \"{outputFile}\" " + $"--no-playlist --quiet --no-warnings " + $"--no-check-certificates " + $"--socket-timeout 30 " + $"--retries 3"; // Only download first 15 seconds _logger.LogInformation(" Downloading: '{Title}'...", video.Title[..Math.Min(50, video.Title.Length)]); var success = await RunAsync(dlArgs, ct); if (success && File.Exists(outputFile) && new FileInfo(outputFile).Length > 100000) { downloadedFiles.Add(outputFile); _logger.LogInformation(" ✓ Downloaded ({Size}KB): '{Title}'", new FileInfo(outputFile).Length / 1024, video.Title[..Math.Min(40, video.Title.Length)]); } else { _logger.LogWarning(" ✗ Failed: '{Title}'", video.Title[..Math.Min(40, video.Title.Length)]); if (File.Exists(outputFile)) File.Delete(outputFile); } } _logger.LogInformation("YouTube: downloaded {Count} clips for '{Query}'", downloadedFiles.Count, query); return downloadedFiles; } private async Task RunAndGetOutputAsync(string arguments, CancellationToken ct) { try { var process = new Process { StartInfo = new ProcessStartInfo { FileName = "yt-dlp", Arguments = arguments, RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true } }; process.Start(); var output = await process.StandardOutput.ReadToEndAsync(ct); await process.WaitForExitAsync(ct); return output; } catch (Exception ex) { _logger.LogError(ex, "yt-dlp failed"); return string.Empty; } } private async Task RunAsync(string arguments, CancellationToken ct) { try { var process = new Process { StartInfo = new ProcessStartInfo { FileName = "yt-dlp", Arguments = arguments, RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true } }; process.Start(); await process.StandardError.ReadToEndAsync(ct); await process.WaitForExitAsync(ct); return process.ExitCode == 0; } catch { return false; } } }