const fs = require('fs');
const https = require('https');
class Veo3Client {
constructor(apiKey) {
this.apiKey = apiKey;
this.baseUrl = 'https://api.kie.ai';
this.headers = {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
};
}
// Generate video
async generateVideo(prompt, options = {}) {
const payload = {
prompt,
model: options.model || 'veo3',
aspectRatio: options.aspectRatio || '16:9',
...options
};
try {
const response = await fetch(`${this.baseUrl}/api/v1/veo/generate`, {
method: 'POST',
headers: this.headers,
body: JSON.stringify(payload)
});
const data = await response.json();
if (response.ok && data.code === 200) {
return data.data.taskId;
} else {
throw new Error(`Video generation failed: ${data.msg || 'Unknown error'}`);
}
} catch (error) {
throw new Error(`Video generation failed: ${error.message}`);
}
}
// Check status
async getStatus(taskId) {
try {
const response = await fetch(`${this.baseUrl}/api/v1/veo/record-info?taskId=${taskId}`, {
method: 'GET',
headers: { 'Authorization': `Bearer ${this.apiKey}` }
});
const data = await response.json();
if (response.ok && data.code === 200) {
return data.data;
} else {
throw new Error(`Status check failed: ${data.msg || 'Unknown error'}`);
}
} catch (error) {
throw new Error(`Status check failed: ${error.message}`);
}
}
// Wait for completion
async waitForCompletion(taskId, maxWaitTime = 600000) { // Default max wait 10 minutes
const startTime = Date.now();
while (Date.now() - startTime < maxWaitTime) {
const status = await this.getStatus(taskId);
console.log(`Task ${taskId} status: ${status.successFlag}`);
if (status.successFlag === 1) {
return JSON.parse(status.resultUrls);
} else if (status.successFlag === 2 || status.successFlag === 3) {
throw new Error('Video generation failed');
}
await new Promise(resolve => setTimeout(resolve, 30000)); // Wait 30 seconds
}
throw new Error('Task timeout');
}
// Download video
async downloadVideo(url, filename) {
return new Promise((resolve, reject) => {
const file = fs.createWriteStream(filename);
https.get(url, (response) => {
if (response.statusCode === 200) {
response.pipe(file);
file.on('finish', () => {
file.close();
console.log(`Video downloaded: ${filename}`);
resolve(filename);
});
} else {
reject(new Error(`Download failed: HTTP ${response.statusCode}`));
}
}).on('error', reject);
});
}
// Complete workflow
async generateAndDownload(prompt, filename = 'video.mp4', options = {}) {
try {
console.log('Starting video generation...');
const taskId = await this.generateVideo(prompt, options);
console.log(`Task submitted: ${taskId}`);
console.log('Waiting for completion...');
const videoUrls = await this.waitForCompletion(taskId);
console.log('Video generation completed!');
console.log('Starting video download...');
await this.downloadVideo(videoUrls[0], filename);
return { taskId, videoUrls, filename };
} catch (error) {
console.error('Error:', error.message);
throw error;
}
}
}
// Usage example
async function main() {
const client = new Veo3Client('YOUR_API_KEY');
try {
const result = await client.generateAndDownload(
'A cute cat playing in a garden on a sunny day, high quality',
'cute_cat.mp4',
{ aspectRatio: '16:9' }
);
console.log('Complete!', result);
} catch (error) {
console.error('Generation failed:', error.message);
}
}
main();