File size: 6,059 Bytes
8fb6238
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
using System.Diagnostics;
using System.Text.Json;
using ClipForge.Core.Interfaces.Services;
using Microsoft.Extensions.Logging;

namespace ClipForge.Infrastructure.Services;

/// <summary>
/// Downloads clips from YouTube using yt-dlp.
/// Strategy: search for relevant videos, download them, then use FFmpeg to cut segments.
/// </summary>
public class YouTubeMediaService : IStockMediaService
{
    private readonly ILogger<YouTubeMediaService> _logger;

    public YouTubeMediaService(ILogger<YouTubeMediaService> logger)
    {
        _logger = logger;
    }

    public async Task<string> DownloadVideoAsync(string query, string outputDir, CancellationToken ct = default)
    {
        var clips = await DownloadMultipleVideosAsync(query, 1, outputDir, ct);
        return clips.FirstOrDefault() ?? string.Empty;
    }

    public async Task<IReadOnlyList<string>> 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<string>();

        // 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<string> 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<bool> 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;
        }
    }
}