| 1 | import type { |
| 2 | CreateVideoGenerationTaskRequest, |
| 3 | CreateVideoGenerationTaskResponse, |
| 4 | GetVideoGenerationTaskResponse, |
| 5 | } from '../volcengine.interface' |
| 6 | import { Injectable } from '@nestjs/common' |
| 7 | import axios, { AxiosError, AxiosInstance, AxiosResponse } from 'axios' |
| 8 | import { VolcengineConfig } from '../volcengine.config' |
| 9 | import { VolcengineException } from '../volcengine.exception' |
| 10 | import { BaseService } from './base.service' |
| 11 | |
| 12 | /** |
| 13 | * Volcengine 视频生成服务 |
| 14 | * 负责 Ark API 视频生成功能 |
| 15 | */ |
| 16 | @Injectable() |
| 17 | export class VideoGenService extends BaseService { |
| 18 | private readonly httpClient: AxiosInstance |
| 19 | |
| 20 | constructor(config: VolcengineConfig) { |
| 21 | super(config) |
| 22 | this.httpClient = this.createHttpClient() |
| 23 | } |
| 24 | |
| 25 | /** |
| 26 | * 创建HTTP客户端 |
| 27 | */ |
| 28 | private createHttpClient(): AxiosInstance { |
| 29 | const httpClient = axios.create({ |
| 30 | baseURL: this.config.baseUrl, |
| 31 | timeout: 30000, |
| 32 | headers: { |
| 33 | 'Content-Type': 'application/json', |
| 34 | 'Authorization': `Bearer ${this.config.apiKey}`, |
| 35 | }, |
| 36 | }) |
| 37 | |
| 38 | httpClient.interceptors.response.use( |
| 39 | response => response, |
| 40 | (error: AxiosError) => { |
| 41 | const method = error.config?.method?.toUpperCase() || 'UNKNOWN' |
| 42 | const url = error.config?.url || 'unknown' |
| 43 | return Promise.reject(VolcengineException.buildFromError(error, `${method} ${url}`)) |
| 44 | }, |
| 45 | ) |
| 46 | |
| 47 | return httpClient |
| 48 | } |
| 49 | |
| 50 | /** |
| 51 | * 创建视频生成任务 |
| 52 | * POST https://ark.cn-beijing.volces.com/api/v3/contents/generations/tasks |
| 53 | */ |
| 54 | async createVideoGenerationTask( |
| 55 | request: CreateVideoGenerationTaskRequest, |
| 56 | ) { |
| 57 | const response: AxiosResponse<CreateVideoGenerationTaskResponse> = await this.httpClient.post( |
| 58 | '/api/v3/contents/generations/tasks', |
| 59 | request, |
| 60 | ) |
| 61 | |
| 62 | return response.data |
| 63 | } |
| 64 | |
| 65 | /** |
| 66 | * 查询视频生成任务 |
| 67 | * GET https://ark.cn-beijing.volces.com/api/v3/contents/generations/tasks/{id} |
| 68 | */ |
| 69 | async getVideoGenerationTask( |
| 70 | taskId: string, |
| 71 | ) { |
| 72 | const response: AxiosResponse<GetVideoGenerationTaskResponse> = await this.httpClient.get( |
| 73 | `/api/v3/contents/generations/tasks/${taskId}`, |
| 74 | ) |
| 75 | |
| 76 | return response.data |
| 77 | } |
| 78 | |
| 79 | /** |
| 80 | * 取消或删除视频生成任务 |
| 81 | * DELETE https://ark.cn-beijing.volces.com/api/v3/contents/generations/tasks/{id} |
| 82 | */ |
| 83 | async deleteVideoGenerationTask( |
| 84 | taskId: string, |
| 85 | ) { |
| 86 | await this.httpClient.delete(`/api/v3/contents/generations/tasks/${taskId}`) |
| 87 | } |
| 88 | } |
| 89 |