# Code coverage report for modules/video-generator/video-generator.service.ts

# All files / modules/video-generator video-generator.service.ts

0% Statements 0/368
0% Branches 0/1
0% Functions 0/1
0% Lines 0/368

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526
    527
    528
    529
    530
    531
    532
    533
    534
    535
    536
    537
    538
    539
    540
    541
    542
    543
    544
    545
    546
    547
    548
    549
    550
    551
    552
    553
    554

     /**
     * 视频生成模块 - 业务逻辑
     * 处理视频项目的增删改查和生成逻辑
     */

    import { prisma } from '../../models';
    import path from 'path';
    import { v4 as uuidv4 } from 'uuid';
    import {
      VideoConfig,
      VideoProjectStatus,
      CreateVideoProjectRequest,
      UpdateVideoProjectRequest,
      GetVideoProjectsQuery,
      VideoProjectResponse,
      VideoMaterialResponse,
      GetMaterialsQuery,
      parseConfig,
      serializeConfig,
      parseTags,
      serializeTags,
      PRESET_VIDEO_CONFIGS,
    } from './video-generator.types';
    import { generateVideo, generateVideoWithBgm, generateSlideshow } from './video-generator.ffmpeg';

    // ============ 视频项目管理 ============

    /**
     * 创建视频项目
     */
    export async function createVideoProject(
      data: CreateVideoProjectRequest,
      userId?: number
    ): Promise<VideoProjectResponse> {
      const config = data.config || PRESET_VIDEO_CONFIGS.portrait;

      const project = await prisma.videoProject.create({
        data: {
          userId: userId,
          title: data.title,
          description: data.description,
          coverUrl: data.coverUrl,
          configJson: serializeConfig(config),
          bookId: data.bookId,
          chapterId: data.chapterId, // 直接关联章节
          status: 'draft',
          progress: 0,
        },
      });

      return {
        ...project,
        config,
      } as VideoProjectResponse;
    }

    /**
     * 获取视频项目列表
     */
    export async function getVideoProjects(query: GetVideoProjectsQuery): Promise<{
      items: VideoProjectResponse[];
      total: number;
      page: number;
      pageSize: number;
    }> {
      const page = query.page || 1;
      const pageSize = query.pageSize || 10;
      const skip = (page - 1) * pageSize;

      const where: any = {};
      if (query.userId) where.userId = query.userId;
      if (query.status) where.status = query.status;

      const [items, total] = await Promise.all([
        prisma.videoProject.findMany({
          where,
          orderBy: { createdAt: 'desc' },
          skip,
          take: pageSize,
        }),
        prisma.videoProject.count({ where }),
      ]);

      return {
        items: items.map((item) => ({
          ...item,
          config: parseConfig(item.configJson),
        })) as VideoProjectResponse[],
        total,
        page,
        pageSize,
      };
    }

    /**
     * 获取视频项目详情
     */
    export async function getVideoProject(id: number): Promise<VideoProjectResponse | null> {
      const project = await prisma.videoProject.findUnique({
        where: { id },
      });

      if (!project) return null;

      return {
        ...project,
        config: parseConfig(project.configJson),
      } as VideoProjectResponse;
    }

    /**
     * 更新视频项目
     */
    export async function updateVideoProject(
      id: number,
      data: UpdateVideoProjectRequest
    ): Promise<VideoProjectResponse | null> {
      const updateData: any = {};

      if (data.title !== undefined) updateData.title = data.title;
      if (data.description !== undefined) updateData.description = data.description;
      if (data.coverUrl !== undefined) updateData.coverUrl = data.coverUrl;
      if (data.config !== undefined) updateData.configJson = serializeConfig(data.config);

      const project = await prisma.videoProject.update({
        where: { id },
        data: updateData,
      });

      return {
        ...project,
        config: parseConfig(project.configJson),
      } as VideoProjectResponse;
    }

    /**
     * 删除视频项目
     */
    export async function deleteVideoProject(id: number): Promise<boolean> {
      try {
        await prisma.videoProject.delete({
          where: { id },
        });
        return true;
      } catch {
        return false;
      }
    }

    // ============ 视频生成 ============

    /**
     * 生成视频
     */
    export async function generateVideoForProject(projectId: number): Promise<{
      success: boolean;
      outputUrl?: string;
      duration?: number;
      fileSize?: number;
      error?: string;
    }> {
      // 1. 获取项目
      const project = await getVideoProject(projectId);
      if (!project) {
        return { success: false, error: '项目不存在' };
      }

      // 2. 检查状态
      if (project.status === 'processing') {
        return { success: false, error: '项目正在生成中' };
      }

      // 3. 更新状态为处理中
      await prisma.videoProject.update({
        where: { id: projectId },
        data: { status: 'processing', progress: 0 },
      });

      try {
        // 4. 获取配置
        const config = project.config;
        if (!config) {
          throw new Error('缺少视频配置');
        }

        // 5. 如果有 chapterId，优先从章节获取音频
        let audioPath = config.audio?.url;
        let textContent = '';

        if (project.chapterId) {
          const chapter = await prisma.bookChapter.findUnique({
            where: { id: project.chapterId },
          });
          if (chapter?.audioUrl) {
            audioPath = chapter.audioUrl;
          }
          if (chapter?.content) {
            textContent = chapter.content;
          }
        }

        if (!audioPath || !config.images?.[0]?.url) {
          throw new Error('缺少必要的素材：音频或图片');
        }

        // 转换URL为本地文件路径
        const fs = await import('fs');

        // 获取 server 目录路径
        const serverDir = process.cwd();

        // 处理图片路径
        let imagePath = config.images[0].url;
        // 统一处理：所有非绝对路径都加上 server 目录和 public 前缀
        if (!imagePath.match(/^[A-Za-z]:/)) {
          // Windows 或 Unix 相对路径
          imagePath = path.join(serverDir, 'public', imagePath.replace(/^\//, ''));
        }

        // 处理音频路径
        if (!audioPath.match(/^[A-Za-z]:/)) {
          audioPath = path.join(serverDir, audioPath.replace(/^\//, ''));
        }

        // 检查文件是否存在
        if (!fs.existsSync(imagePath)) {
          throw new Error('图片文件不存在: ' + imagePath);
        }
        if (!fs.existsSync(audioPath)) {
          throw new Error('音频文件不存在: ' + audioPath);
        }

        // 6. 生成输出路径
        const outputFileName = `video_${projectId}_${uuidv4()}.mp4`;
        const outputPath = path.join(process.cwd(), 'public', 'videos', outputFileName);

        // 7. 更新进度
        await prisma.videoProject.update({
          where: { id: projectId },
          data: { progress: 30 },
        });

        // 8. 生成视频
        let result: { duration: number; fileSize: number };

        if (config.bgm?.url) {
          // 带背景音乐
          const bgmPath = await downloadFile(config.bgm.url, 'audio');
          result = await generateVideoWithBgm(imagePath, audioPath, bgmPath, outputPath, config);
        } else {
          // 不带背景音乐
          result = await generateVideo(imagePath, audioPath, outputPath, config);
        }

        // 9. 更新项目状态
        const outputUrl = `/videos/${outputFileName}`;
        await prisma.videoProject.update({
          where: { id: projectId },
          data: {
            status: 'completed',
            progress: 100,
            outputUrl,
            duration: result.duration,
            fileSize: result.fileSize,
          },
        });

        // 10. 如果有章节关联，更新章节的视频URL
        if (project.chapterId) {
          await prisma.bookChapter.update({
            where: { id: project.chapterId },
            data: {
              videoUrl: outputUrl,
              videoDuration: result.duration,
            },
          });

          // 推送 WebSocket 事件（视频生成完成）
          const { pushVideoGenerationComplete } = await import('../../services/websocket.service.js');
          pushVideoGenerationComplete(String(project.bookId), project.chapterId, 'completed');
        }

        return {
          success: true,
          outputUrl,
          duration: result.duration,
          fileSize: result.fileSize,
        };
      } catch (error: any) {
        // 生成失败，更新状态
        await prisma.videoProject.update({
          where: { id: projectId },
          data: {
            status: 'failed',
            errorMsg: error.message,
          },
        });

        // 推送 WebSocket 事件（视频生成失败）
        if (project.chapterId) {
          const { pushVideoGenerationComplete } = await import('../../services/websocket.service.js');
          pushVideoGenerationComplete(String(project.bookId), project.chapterId, 'failed');
        }

        return {
          success: false,
          error: error.message,
        };
      }
    }

    /**
     * 获取生成进度
     */
    export async function getGenerateProgress(projectId: number): Promise<{
      status: VideoProjectStatus;
      progress: number;
      outputUrl?: string;
      duration?: number;
      fileSize?: number;
      errorMsg?: string;
    }> {
      const project = await prisma.videoProject.findUnique({
        where: { id: projectId },
        select: {
          status: true,
          progress: true,
          outputUrl: true,
          duration: true,
          fileSize: true,
          errorMsg: true,
        },
      });

      if (!project) {
        return { status: 'failed', progress: 0, errorMsg: '项目不存在' };
      }

      return project as any;
    }

    // ============ 素材管理 ============

    /**
     * 获取素材列表
     */
    export async function getMaterials(query: GetMaterialsQuery): Promise<{
      items: VideoMaterialResponse[];
      total: number;
    }> {
      const page = query.page || 1;
      const pageSize = query.pageSize || 20;
      const skip = (page - 1) * pageSize;

      const where: any = {
        OR: [{ userId: null }, { userId: query.userId || 0 }],
      };
      if (query.type) where.type = query.type;
      if (query.category) where.category = query.category;

      const [items, total] = await Promise.all([
        prisma.videoMaterial.findMany({
          where,
          orderBy: { createdAt: 'desc' },
          skip,
          take: pageSize,
        }),
        prisma.videoMaterial.count({ where }),
      ]);

      return {
        items: items.map((item) => ({
          ...item,
          tags: parseTags(item.tags),
        })) as VideoMaterialResponse[],
        total,
      };
    }

    /**
     * 上传素材
     */
    export async function uploadMaterial(
      data: {
        type: string;
        name: string;
        url: string;
        thumbnail?: string;
        tags?: string[];
        category?: string;
        duration?: number;
        size?: number;
        width?: number;
        height?: number;
      },
      userId?: number
    ): Promise<VideoMaterialResponse> {
      const material = await prisma.videoMaterial.create({
        data: {
          userId: userId,
          type: data.type,
          name: data.name,
          url: data.url,
          thumbnail: data.thumbnail,
          tags: serializeTags(data.tags || []),
          category: data.category,
          duration: data.duration,
          size: data.size,
          width: data.width,
          height: data.height,
        },
      });

      return {
        ...material,
        tags: parseTags(material.tags),
      } as VideoMaterialResponse;
    }

    /**
     * 删除素材
     */
    export async function deleteMaterial(id: number): Promise<boolean> {
      try {
        await prisma.videoMaterial.delete({
          where: { id },
        });
        return true;
      } catch {
        return false;
      }
    }

    // ============ 辅助函数 ============

    /**
     * 下载文件到临时目录
     */
    async function downloadFile(url: string, type: 'images' | 'audio'): Promise<string> {
      const https = await import('https');
      const http = await import('http');
      const fs = await import('fs');

      const tempDir = path.join(process.cwd(), 'temp', type);
      if (!fs.existsSync(tempDir)) {
        fs.mkdirSync(tempDir, { recursive: true });
      }

      const ext = path.extname(url) || (type === 'images' ? '.jpg' : '.mp3');
      const filePath = path.join(tempDir, `${uuidv4()}${ext}`);

      return new Promise((resolve, reject) => {
        const protocol = url.startsWith('https') ? https : http;
        const file = fs.createWriteStream(filePath);

        protocol.get(url, (response) => {
          if (response.statusCode === 301 || response.statusCode === 302) {
            // 重定向
            const redirectUrl = response.headers.location;
            if (!redirectUrl) {
              file.close();
              reject(new Error('重定向但没有 location header'));
              return;
            }
            const redirectProtocol = redirectUrl.startsWith('https') ? https : http;
            redirectProtocol.get(redirectUrl, (redirectResponse) => {
              redirectResponse.pipe(file);
              file.on('finish', () => resolve(filePath));
            });
          } else {
            response.pipe(file);
            file.on('finish', () => resolve(filePath));
          }
        }).on('error', reject);
      });
    }

    /**
     * 清理临时文件
     */
    async function cleanupTempFiles(...filePaths: string[]): Promise<void> {
      const fs = await import('fs');
      for (const filePath of filePaths) {
        try {
          if (fs.existsSync(filePath)) {
            fs.unlinkSync(filePath);
          }
        } catch (error) {
          console.error(`清理文件失败: ${filePath}`, error);
        }
      }
    }

    /**
     * 从书籍生成视频项目（基于指定章节）
     */
    export async function createVideoProjectFromBook(bookId: number, chapterId?: number, userId?: number): Promise<VideoProjectResponse | null> {
      // 获取书籍信息
      const book = await prisma.book.findUnique({
        where: { id: bookId },
        include: { chapters: { orderBy: { number: 'asc' } } },
      });

      if (!book) return null;

      // 如果没有指定章节，使用第一个有音频的章节
      let targetChapter = book.chapters.find(c => c.audioUrl) || book.chapters[0];
      if (chapterId) {
        const found = book.chapters.find(c => c.id === chapterId);
        if (found) targetChapter = found;
      }

      if (!targetChapter) return null;

      // 如果章节没有音频，返回错误
      if (!targetChapter.audioUrl) {
        console.error(`章节 ${targetChapter.number} 没有音频`);
        return null;
      }

      // 创建视频项目，直接关联到章节
      const project = await createVideoProject(
        {
          title: `《${book.title}》第${targetChapter.number}章 视频`,
          description: targetChapter.summary || book.description,
          bookId: book.id,
          chapterId: targetChapter.id,
          config: {
            ...PRESET_VIDEO_CONFIGS.portrait,
            audio: {
              url: targetChapter.audioUrl,
              volume: 1,
            },
            images: [
              {
                url: '/images/default-cover.jpg',
                duration: 5,
                transition: 'fade',
              },
            ],
            subtitle: {
              text: targetChapter.title,
              position: 'bottom',
              fontSize: 28,
              fontColor: 'white',
            },
          },
        },
        userId
      );

      return project;
    }