File size: 3,495 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
using System.Net.Http.Headers;
using System.Text.Json;
using ClipForge.Core.Interfaces.Services;
using ClipForge.Infrastructure.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace ClipForge.Infrastructure.Services;

public class PexelsStockMediaService : IStockMediaService
{
    private readonly HttpClient _httpClient;
    private readonly PexelsSettings _settings;
    private readonly ILogger<PexelsStockMediaService> _logger;

    public PexelsStockMediaService(HttpClient httpClient, IOptions<PexelsSettings> settings, ILogger<PexelsStockMediaService> logger)
    {
        _httpClient = httpClient;
        _settings = settings.Value;
        _logger = logger;

        _httpClient.BaseAddress = new Uri(_settings.BaseUrl);
        _httpClient.DefaultRequestHeaders.Add("Authorization", _settings.ApiKey);
    }

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

    public async Task<IReadOnlyList<string>> DownloadMultipleVideosAsync(string query, int count, string outputDir, CancellationToken ct = default)
    {
        _logger.LogInformation("Searching Pexels for '{Query}', count: {Count}", query, count);

        Directory.CreateDirectory(outputDir);

        var response = await _httpClient.GetAsync($"/videos/search?query={Uri.EscapeDataString(query)}&per_page={count}&orientation=portrait", ct);
        response.EnsureSuccessStatusCode();

        var json = await response.Content.ReadAsStringAsync(ct);
        using var doc = JsonDocument.Parse(json);

        var downloadedFiles = new List<string>();
        var videos = doc.RootElement.GetProperty("videos");

        foreach (var video in videos.EnumerateArray())
        {
            var videoFiles = video.GetProperty("video_files");
            // Prefer HD quality vertical video
            string? downloadUrl = null;

            foreach (var file in videoFiles.EnumerateArray())
            {
                var width = file.TryGetProperty("width", out var w) ? w.GetInt32() : 0;
                var height = file.TryGetProperty("height", out var h) ? h.GetInt32() : 0;

                // Prefer vertical or square videos with decent quality
                if (height >= width && height >= 720)
                {
                    downloadUrl = file.GetProperty("link").GetString();
                    break;
                }
            }

            // Fallback to first available file
            if (downloadUrl is null && videoFiles.GetArrayLength() > 0)
            {
                downloadUrl = videoFiles[0].GetProperty("link").GetString();
            }

            if (downloadUrl is not null)
            {
                var fileName = $"{Guid.NewGuid()}.mp4";
                var filePath = Path.Combine(outputDir, fileName);

                using var videoResponse = await _httpClient.GetAsync(downloadUrl, ct);
                videoResponse.EnsureSuccessStatusCode();

                var bytes = await videoResponse.Content.ReadAsByteArrayAsync(ct);
                await File.WriteAllBytesAsync(filePath, bytes, ct);

                downloadedFiles.Add(filePath);
                _logger.LogInformation("Downloaded stock video: {FilePath}", filePath);
            }
        }

        return downloadedFiles;
    }
}