返回 AiToEarn
video-metadata.service.spec.ts
根目录 / project / aitoearn-backend / libs / assets / src / video-metadata.service.spec.ts
1 import { writeFile } from 'node:fs/promises'
2 import { beforeEach, describe, expect, it, vi } from 'vitest'
3
4 import { VideoMetadataService } from './video-metadata.service'
5
6 const { execaMock } = vi.hoisted(() => ({
7 execaMock: vi.fn(),
8 }))
9
10 vi.mock('execa', () => ({
11 execa: (...args: unknown[]) => execaMock(...args),
12 }))
13
14 vi.mock('@yikart/mongodb', () => ({
15 AssetType: {
16 AiImage: 'aiImage',
17 AiVideo: 'aiVideo',
18 AiCard: 'aiCard',
19 AiChatImage: 'aiChatImage',
20 AideoOutput: 'aideoOutput',
21 VideoEdit: 'videoEdit',
22 DramaRecap: 'dramaRecap',
23 StyleTransfer: 'styleTransfer',
24 UserMedia: 'userMedia',
25 UserFile: 'userFile',
26 PublishMedia: 'publishMedia',
27 Avatar: 'avatar',
28 AgentSession: 'agentSession',
29 VideoThumbnail: 'videoThumbnail',
30 GooglePlace: 'googlePlace',
31 Temp: 'temp',
32 ImageEdit: 'imageEdit',
33 Subtitle: 'subtitle',
34 },
35 AssetStatus: {
36 Confirmed: 'confirmed',
37 },
38 AssetRepository: class {},
39 }))
40
41 function createService() {
42 const storage = {
43 putObject: vi.fn().mockResolvedValue({ path: 'uploaded-path' }),
44 buildUrl: vi.fn((objectPath: string) => `https://cdn.example.test/${objectPath}`),
45 }
46 const service = new VideoMetadataService(storage as never, {} as never)
47 return { service, storage }
48 }
49
50 function mp4Box(type: string, payloadSize: number): Buffer {
51 const box = Buffer.alloc(8 + payloadSize)
52 box.writeUInt32BE(box.length, 0)
53 box.write(type, 4, 'ascii')
54 return box
55 }
56
57 /** Build a fake mp4 byte layout: ftyp first, then moov/mdat in the given order. */
58 function fakeMp4(...order: ('moov' | 'mdat')[]): Buffer {
59 return Buffer.concat([
60 mp4Box('ftyp', 16),
61 ...order.map(type => mp4Box(type, 8)),
62 ])
63 }
64
65 function probeResult(codecName: string, formatName = 'mov,mp4,m4a,3gp,3g2,mj2') {
66 return {
67 streams: [{ codec_type: 'video', codec_name: codecName }],
68 format: { format_name: formatName },
69 }
70 }
71
72 function mockExeca(probe: unknown) {
73 execaMock.mockImplementation(async (cmd: string, args: string[]) => {
74 if (cmd === 'ffprobe') {
75 return { stdout: JSON.stringify(probe) }
76 }
77 if (cmd === 'ffmpeg') {
78 await writeFile(args[args.length - 1], 'transcoded')
79 return { stdout: '' }
80 }
81 throw new Error(`unexpected command: ${cmd}`)
82 })
83 }
84
85 function mockFetchWithMp4(...order: ('moov' | 'mdat')[]) {
86 const fetchMock = vi.fn().mockResolvedValue(new Response(fakeMp4(...order)))
87 vi.stubGlobal('fetch', fetchMock)
88 return fetchMock
89 }
90
91 describe('videoMetadataService.ensureCompatibleVideo', () => {
92 beforeEach(() => {
93 vi.unstubAllGlobals()
94 execaMock.mockReset()
95 })
96
97 it('returns the original URL when the video is H.264 in a faststart mp4', async () => {
98 mockFetchWithMp4('moov', 'mdat')
99 mockExeca(probeResult('h264'))
100 const { service, storage } = createService()
101
102 const url = 'https://cdn.example.test/video.mp4'
103 await expect(service.ensureCompatibleVideo(url)).resolves.toBe(url)
104
105 expect(storage.putObject).not.toHaveBeenCalled()
106 expect(execaMock).toHaveBeenCalledTimes(1)
107 expect(execaMock.mock.calls[0][0]).toBe('ffprobe')
108 })
109
110 it('transcodes non-H.264 videos and uploads the result', async () => {
111 mockFetchWithMp4('moov', 'mdat')
112 mockExeca(probeResult('hevc'))
113 const { service, storage } = createService()
114
115 const result = await service.ensureCompatibleVideo('https://cdn.example.test/hevc.mp4')
116
117 expect(execaMock).toHaveBeenCalledTimes(2)
118 const ffmpegCall = execaMock.mock.calls[1]
119 expect(ffmpegCall[0]).toBe('ffmpeg')
120 expect(ffmpegCall[1]).toEqual(expect.arrayContaining([
121 '-c:v',
122 'libx264',
123 '-movflags',
124 '+faststart',
125 '-f',
126 'mp4',
127 ]))
128 expect(ffmpegCall[2]).toMatchObject({ timeout: 600000 })
129
130 expect(storage.putObject).toHaveBeenCalledTimes(1)
131 const [objectPath, , contentType] = storage.putObject.mock.calls[0]
132 expect(objectPath).toContain('publish/media')
133 expect(contentType).toBe('video/mp4')
134 expect(result).toBe(`https://cdn.example.test/${objectPath}`)
135 })
136
137 it('transcodes H.264 videos whose moov atom is after mdat (not faststart)', async () => {
138 mockFetchWithMp4('mdat', 'moov')
139 mockExeca(probeResult('h264'))
140 const { service, storage } = createService()
141
142 const result = await service.ensureCompatibleVideo('https://cdn.example.test/slowstart.mp4')
143
144 expect(execaMock.mock.calls[1][0]).toBe('ffmpeg')
145 expect(storage.putObject).toHaveBeenCalledTimes(1)
146 expect(result).not.toBe('https://cdn.example.test/slowstart.mp4')
147 })
148
149 it('transcodes H.264 videos in non-mp4 containers', async () => {
150 mockFetchWithMp4('mdat', 'moov')
151 mockExeca(probeResult('h264', 'avi'))
152 const { service, storage } = createService()
153
154 await service.ensureCompatibleVideo('https://cdn.example.test/video.avi')
155
156 expect(storage.putObject).toHaveBeenCalledTimes(1)
157 })
158
159 it('throws when the URL is not http(s) or looks like an ffmpeg option', async () => {
160 const { service, storage } = createService()
161
162 await expect(service.ensureCompatibleVideo('-i evil')).rejects.toThrow('Invalid video URL')
163 await expect(service.ensureCompatibleVideo('ftp://example.test/video.mp4')).rejects.toThrow('Invalid video URL')
164
165 expect(execaMock).not.toHaveBeenCalled()
166 expect(storage.putObject).not.toHaveBeenCalled()
167 })
168
169 it('rejects downloads whose declared content-length exceeds the size cap', async () => {
170 const fetchMock = vi.fn().mockResolvedValue(new Response(fakeMp4('moov'), {
171 headers: { 'content-length': String(3 * 1024 * 1024 * 1024) },
172 }))
173 vi.stubGlobal('fetch', fetchMock)
174 const { service, storage } = createService()
175
176 await expect(service.ensureCompatibleVideo('https://cdn.example.test/huge.mp4'))
177 .rejects
178 .toThrow('Video too large to download')
179
180 expect(execaMock).not.toHaveBeenCalled()
181 expect(storage.putObject).not.toHaveBeenCalled()
182 })
183
184 it('passes an abort signal to fetch so oversized or stalled downloads are terminated', async () => {
185 const fetchMock = mockFetchWithMp4('moov', 'mdat')
186 mockExeca(probeResult('h264'))
187 const { service } = createService()
188
189 await service.ensureCompatibleVideo('https://cdn.example.test/video.mp4')
190
191 const init = fetchMock.mock.calls[0][1]
192 expect(init?.signal).toBeInstanceOf(AbortSignal)
193 })
194
195 it('throws when the download fails', async () => {
196 vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('nope', { status: 500 })))
197 const { service, storage } = createService()
198
199 await expect(service.ensureCompatibleVideo('https://cdn.example.test/video.mp4'))
200 .rejects
201 .toThrow('Failed to download video: HTTP 500')
202
203 expect(execaMock).not.toHaveBeenCalled()
204 expect(storage.putObject).not.toHaveBeenCalled()
205 })
206 })
207
208 describe('videoMetadataService.probeVideoMetadata', () => {
209 beforeEach(() => {
210 execaMock.mockReset()
211 })
212
213 it('rejects URLs that could inject ffmpeg options', async () => {
214 const { service } = createService()
215
216 await expect(service.probeVideoMetadata('-user_agent x'))
217 .rejects
218 .toThrow('Invalid video URL')
219 expect(execaMock).not.toHaveBeenCalled()
220 })
221
222 it('reports the last ffprobe error line when probing fails', async () => {
223 execaMock.mockRejectedValueOnce(Object.assign(new Error('Command failed'), {
224 stderr: 'https://cdn.example.test/video.mp4: Server returned 403 Forbidden (access denied)',
225 exitCode: 1,
226 timedOut: false,
227 }))
228 const { service } = createService()
229
230 await expect(service.probeVideoMetadata('https://cdn.example.test/video.mp4'))
231 .rejects
232 .toThrow('ffprobe failed: https://cdn.example.test/video.mp4: Server returned 403 Forbidden (access denied)')
233 })
234
235 it('reports ffprobe timeouts', async () => {
236 execaMock.mockRejectedValueOnce(Object.assign(new Error('Command timed out'), { stderr: '', timedOut: true }))
237 const { service } = createService()
238
239 await expect(service.probeVideoMetadata('https://cdn.example.test/video.mp4'))
240 .rejects
241 .toThrow('ffprobe timed out after 60s')
242 })
243
244 it('passes a fixed user agent to ffprobe', async () => {
245 execaMock.mockResolvedValueOnce({
246 stdout: JSON.stringify({
247 streams: [{ codec_type: 'video', width: 1920, height: 1080, r_frame_rate: '30/1' }],
248 format: { duration: '10', bit_rate: '1000' },
249 }),
250 })
251 const { service } = createService()
252
253 const metadata = await service.probeVideoMetadata('https://cdn.example.test/video.mp4')
254
255 expect(execaMock).toHaveBeenCalledWith(
256 'ffprobe',
257 expect.arrayContaining(['-user_agent', 'AiToEarn-MediaProbe/1.0', 'https://cdn.example.test/video.mp4']),
258 expect.objectContaining({ timeout: 60000 }),
259 )
260 expect(metadata).toMatchObject({ width: 1920, height: 1080, duration: 10 })
261 })
262 })
263
263 lines TYPESCRIPT