const { createClient } = require('pexels'); const axios = require('axios'); const fs = require('fs'); const path = require('path'); /** * Pexels Service for high-quality stock video automation */ class PexelsService { constructor() { this.apiKey = process.env.PEXELS_API_KEY; if (this.apiKey) { this.client = createClient(this.apiKey); } } /** * Search for a 9:16 portrait video matching the query * @param {string} query - Search term * @returns {string|null} Download link for the best matching video */ async searchVideo(query) { if (!this.client) { console.warn('⚠️ Pexels API Key missing. Skipping stock video search.'); return null; } try { console.log(` 🔍 Pexels: Searching for "${query}"...`); const result = await this.client.videos.search({ query, orientation: 'portrait', per_page: 5, // Get a few to find the best match }); if (!result.videos || result.videos.length === 0) { console.log(` ⚠️ Pexels: No videos found for "${query}"`); return null; } // Find the best quality 1080x1920 file const video = result.videos[0]; const videoFile = video.video_files.find( f => f.width === 1080 && f.height === 1920 ) || video.video_files[0]; // Fallback to first file return videoFile.link; } catch (error) { console.error(' ❌ Pexels Search Error:', error.message); return null; } } /** * Download a video from a URL * @param {string} url - Download URL * @param {string} outputPath - Path to save the file * @returns {string} Saved file path */ async downloadVideo(url, outputPath) { console.log(` 📥 Pexels: Downloading video...`); const response = await axios({ method: 'get', url: url, responseType: 'stream', }); const writer = fs.createWriteStream(outputPath); response.data.pipe(writer); return new Promise((resolve, reject) => { writer.on('finish', () => resolve(outputPath)); writer.on('error', reject); }); } } module.exports = new PexelsService();