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 _logger; public PexelsStockMediaService(HttpClient httpClient, IOptions settings, ILogger logger) { _httpClient = httpClient; _settings = settings.Value; _logger = logger; _httpClient.BaseAddress = new Uri(_settings.BaseUrl); _httpClient.DefaultRequestHeaders.Add("Authorization", _settings.ApiKey); } public async Task DownloadVideoAsync(string query, string outputDir, CancellationToken ct = default) { var videos = await DownloadMultipleVideosAsync(query, 1, outputDir, ct); return videos.FirstOrDefault() ?? string.Empty; } public async Task> 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(); 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; } }