# All files / modules/book-generator album-controller.ts

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

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

     /**
     * 专辑/书籍管理 - API 路由
     */

    import Router from '@koa/router';
    import { Context } from 'koa';
    import path from 'path';
    import { bookStore } from './book-generator.store';
    import { optionalAuth } from '../../middleware/auth';
    import { prisma } from '../../models';

    // 开发环境测试用户ID
    const TEST_USER_ID = '1';

    const router = new Router();

    /**
     * GET /api/book-generator/albums
     * 获取专辑列表
     */
    router.get('/albums', async (ctx: Context) => {
      try {
        const books = await bookStore.getAllByUser();
        // 只返回基本信息
        const albums = books.map(book => ({
          id: book.id,
          title: book.title,
          description: book.description,
          totalChapters: book.totalChapters,
          genStage: book.genStage,
          progress: book.progress,
          createdAt: book.createdAt,
        }));
        ctx.body = { code: 0, message: 'success', data: { albums } };
      } catch (error) {
        console.error('查询失败:', error);
        ctx.status = 500;
        ctx.body = { code: 1, message: error instanceof Error ? error.message : '查询失败' };
      }
    });

    /**
     * GET /api/book-generator/list
     * 获取书籍列表（带分页和日期过滤）
     */
    router.get('/list', optionalAuth, async (ctx: Context) => {
      try {
        const { startDate, pageSize = '100' } = ctx.query as { startDate?: string; pageSize?: string };
        const userId = ctx.state.user?.userId || TEST_USER_ID;

        const pageSizeNum = parseInt(pageSize) || 100;
        const where: any = {
          OR: [
            { userId: parseInt(userId) },
            { userId: null }, // 兼容旧数据
          ],
        };

        if (startDate) {
          const start = new Date(startDate);
          where.createdAt = { gte: start };
        }

        // 获取总数
        const total = await prisma.book.count({ where });

        // 获取列表
        const books = await prisma.book.findMany({
          where,
          include: { chapters: true },
          orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
          take: pageSizeNum,
        });

        // 转换为前端需要的格式
        const list = books.map(book => ({
          id: book.id,
          title: book.title,
          description: book.description,
          totalChapters: book.totalChapters,
          genStage: book.genStage,
          progress: book.progress,
          createdAt: book.createdAt,
          updatedAt: book.updatedAt,
          chapters: book.chapters.map(ch => ({
            id: ch.id,
            title: ch.title,
            genStage: ch.genStage,
            audioUrl: ch.audioUrl,
            videoUrl: ch.videoUrl,
          })),
        }));

        ctx.body = {
          code: 0,
          message: 'success',
          data: { list, total },
        };
      } catch (error) {
        console.error('查询书籍列表失败:', error);
        ctx.status = 500;
        ctx.body = { code: 1, message: error instanceof Error ? error.message : '查询失败' };
      }
    });

    /**
     * POST /api/book-generator/albums
     * 创建专辑
     */
    router.post('/albums', async (ctx: Context) => {
      try {
        const body = ctx.request.body as {
          title: string;
          description?: string;
        };

        if (!body.title || body.title.trim().length === 0) {
          ctx.status = 400;
          ctx.body = { code: 1, message: '请输入专辑名称' };
          return;
        }

        const book = await bookStore.create({
          title: body.title.trim(),
          description: body.description || '',
          totalChapters: 0, // 初始为 0，等待添加章节
        });

        ctx.body = {
          code: 0,
          message: '专辑创建成功',
          data: {
            id: book.id,
            title: book.title,
            description: book.description,
          },
        };
      } catch (error) {
        console.error('创建失败:', error);
        ctx.status = 500;
        ctx.body = { code: 1, message: error instanceof Error ? error.message : '创建失败' };
      }
    });

    /**
     * GET /api/book-generator/albums/:id/chapters
     * 获取专辑章节列表
     * 返回章（level=1）的列表，每个章包含其下所有小节的合并音频
     * 过滤规则：公开的音频 + 当前用户自己的音频
     */
    router.get('/albums/:id/chapters', optionalAuth, async (ctx: Context) => {
      try {
        const bookId = ctx.params.id as string;
        const userId = ctx.state.user?.userId || TEST_USER_ID;

        // 获取专辑信息
        const book = await prisma.book.findUnique({
          where: { id: parseInt(bookId) },
        });

        if (!book) {
          ctx.status = 404;
          ctx.body = { code: 1, message: '专辑不存在' };
          return;
        }

        // 判断是否为所有者（userId为null时也视为所有者，这样无需登录也能访问自己的音频）
        const isOwner = book.userId === null || book.userId === parseInt(userId);

        // 获取所有章节
        const allChapters = await prisma.bookChapter.findMany({
          where: { bookId: parseInt(bookId) },
          orderBy: { number: 'asc' },
        });

        // 构建章(1) -> 节(2) -> 小节(3) 的树形结构
        const chapterMap = new Map<number, any>();
        const sectionMap = new Map<number, any>();

        // 先遍历，构建映射
        allChapters.forEach(c => {
          if (c.level === 1) {
            chapterMap.set(c.id, {
              id: String(c.id),
              bookId: String(c.bookId),
              number: c.number,
              title: c.title,
              wordCount: c.wordCount || 0,
              genStage: c.genStage || null,
              audioUrl: c.audioUrl || null,
              audioDuration: c.audioDuration || 0,
              videoUrl: c.videoUrl || null,
              videoDuration: c.videoDuration || 0,
              isPublic: c.isPublic,
              level: c.level,
              subsections: [], // 节和小节列表
            });
          } else if (c.level === 2) {
            sectionMap.set(c.id, {
              id: String(c.id),
              number: c.number,
              title: c.title,
              subsections: [],
            });
          }
        });

        // 收集所有小节及其音频，按章分组
        const subsectionsByChapter = new Map<number, { audioUrl: string; audioDuration: number; title: string; isPublic: boolean }[]>();

        // 先把3级小节挂到2级节下
        const sectionSubsections = new Map<number, { audioUrl: string; audioDuration: number; title: string; isPublic: boolean }[]>();
        allChapters.forEach(c => {
          if (c.level === 3 && c.parentId && c.audioUrl && c.audioUrl.trim() !== '') {
            if (!sectionSubsections.has(c.parentId)) {
              sectionSubsections.set(c.parentId, []);
            }
            sectionSubsections.get(c.parentId)!.push({
              audioUrl: c.audioUrl,
              audioDuration: c.audioDuration || 0,
              title: c.title,
              isPublic: c.isPublic || false,
            });
          }
        });

        // 把2级节挂到1级章下，并收集小节音频
        chapterMap.forEach((chapter, chapterId) => {
          subsectionsByChapter.set(chapterId, []);
        });

        allChapters.forEach(c => {
          if (c.level === 2 && c.parentId) {
            const chapter = chapterMap.get(c.parentId);
            const sectionData = sectionMap.get(c.id);
            if (chapter && sectionData) {
              // 获取这个小节的所有小节音频
              const subs = sectionSubsections.get(c.id) || [];
              chapter.subsections.push({ ...sectionData, subsections: subs });
              // 把小节音频按章汇总
              subs.forEach(s => {
                subsectionsByChapter.get(c.parentId)!.push(s);
              });
            }
          }
        });

        // 为每个章设置audioUrl
        // 优先级：1. 章自身已有的合并音频（_merged） > 2. 章自身的audioUrl > 3. 仅汇总子节时长
        // 注意：不再用 subs[0].audioUrl 覆盖章的 audioUrl，因为章的合并音频已在 mergeChapterAudios 中正确写入
        chapterMap.forEach((chapter, chapterId) => {
          const subs = subsectionsByChapter.get(chapterId) || [];
          if (subs.length > 0 && (!chapter.audioUrl || chapter.audioUrl.trim() === '')) {
            // 章自身没有音频（短文章以外的情况），仅汇总子节时长，不覆盖audioUrl
            // 前端播放章级别时会通过 player 接口自动触发合并
            chapter.audioDuration = subs.reduce((acc, s) => acc + s.audioDuration, 0);
          } else if (subs.length > 0) {
            // 章已有音频（可能是合并后的 _merged 音频），保留它，只汇总时长
            chapter.audioDuration = subs.reduce((acc, s) => acc + s.audioDuration, 0);
          }
          // 否则保持章自己的audioUrl（短文章直接生成在章上）
        });

        // 转换为数组并应用过滤规则
        let chapters = Array.from(chapterMap.values());

        // 应用公开过滤（只影响非所有者）
        if (!isOwner) {
          chapters = chapters.map(chapter => {
            // 检查是否有公开的小节音频
            const hasPublicSubsection = chapter.subsections?.some((s: any) =>
              s.subsections?.some((sub: any) => sub.isPublic === true && sub.audioUrl)
            );
            // 检查章节本身是否有公开音频
            const hasOwnPublicAudio = chapter.audioUrl &&
              chapter.audioUrl.trim() !== '' &&
              chapter.isPublic === true;
            if (!hasPublicSubsection && !hasOwnPublicAudio) {
              return {
                ...chapter,
                audioUrl: null,
              };
            }
            return chapter;
          });
        }

        ctx.body = {
          code: 0,
          message: 'success',
          data: {
            chapters,
            isOwner,
          },
        };
      } catch (error) {
        console.error('查询失败:', error);
        ctx.status = 500;
        ctx.body = { code: 1, message: error instanceof Error ? error.message : '查询失败' };
      }
    });

    /**
     * POST /api/book-generator/albums/:id/chapters/:chapterId/merge-audio
     * 合并章下所有小节音频为单个文件
     */
    router.post('/albums/:id/chapters/:chapterId/merge-audio', optionalAuth, async (ctx: Context) => {
      try {
        const bookId = ctx.params.id as string;
        const chapterId = parseInt(ctx.params.chapterId as string);

        // 获取章信息
        const chapter = await prisma.bookChapter.findFirst({
          where: { id: chapterId, level: 1 },
        });

        if (!chapter) {
          ctx.status = 404;
          ctx.body = { code: 1, message: '章节不存在' };
          return;
        }

        // 获取这个章下所有的2级节
        const sections = await prisma.bookChapter.findMany({
          where: { parentId: chapterId, level: 2 },
          orderBy: { number: 'asc' },
        });

        // 获取每个节下所有有音频的小节
        const allAudioUrls: string[] = [];
        for (const section of sections) {
          const subsections = await prisma.bookChapter.findMany({
            where: { parentId: section.id, level: 3, audioUrl: { not: '' } },
            orderBy: { number: 'asc' },
          });
          subsections.forEach(sub => {
            if (sub.audioUrl) {
              allAudioUrls.push(sub.audioUrl);
            }
          });
        }

        if (allAudioUrls.length === 0) {
          ctx.status = 400;
          ctx.body = { code: 1, message: '没有可合并的音频' };
          return;
        }

        // 生成合并后的文件路径
        const outputDir = path.join(process.cwd(), 'uploads', 'merged', bookId);
        const outputPath = path.join(outputDir, `chapter_${chapterId}_merged.mp3`);

        // 确保目录存在
        const fs = require('fs');
        if (!fs.existsSync(outputDir)) {
          fs.mkdirSync(outputDir, { recursive: true });
        }

        // 合并音频
        const { AudioMerger } = await import('../tts/audio-merger.js');
        const mergedPath = await AudioMerger.merge(allAudioUrls, outputPath);

        // 获取合并后的时长
        const duration = await AudioMerger.getDuration(mergedPath);

        // 更新章的合并音频字段
        await prisma.bookChapter.update({
          where: { id: chapterId },
          data: {
            audioUrl: `/uploads/merged/${bookId}/chapter_${chapterId}_merged.mp3`,
            audioDuration: Math.round(duration),
          },
        });

        ctx.body = {
          code: 0,
          message: '音频合并成功',
          data: {
            audioUrl: `/uploads/merged/${bookId}/chapter_${chapterId}_merged.mp3`,
            duration: Math.round(duration),
          },
        };
      } catch (error) {
        console.error('合并音频失败:', error);
        ctx.status = 500;
        ctx.body = { code: 1, message: error instanceof Error ? error.message : '合并音频失败' };
      }
    });

    /**
     * GET /api/book-generator/albums/chapters/:id
     * 获取单个章节详情
     */
    router.get('/albums/chapters/:id', optionalAuth, async (ctx: Context) => {
      try {
        const chapterId = parseInt(ctx.params.id as string);

        // 获取章节详情
        const chapter = await prisma.bookChapter.findUnique({
          where: { id: chapterId },
        });

        if (!chapter) {
          ctx.status = 404;
          ctx.body = { code: 1, message: '章节不存在' };
          return;
        }

        ctx.body = {
          code: 0,
          message: 'success',
          data: {
            id: String(chapter.id),
            bookId: String(chapter.bookId),
            parentId: chapter.parentId ? String(chapter.parentId) : null,
            number: chapter.number,
            title: chapter.title,
            content: chapter.content || '',
            genStage: chapter.genStage || null,
            level: chapter.level,
            audioUrl: chapter.audioUrl || null,
            audioDuration: chapter.audioDuration || 0,
            videoUrl: chapter.videoUrl || null,
            videoDuration: chapter.videoDuration || 0,
            wordCount: chapter.wordCount || 0,
            isPublic: chapter.isPublic || false,
          },
        };
      } catch (error) {
        console.error('查询章节详情失败:', error);
        ctx.status = 500;
        ctx.body = { code: 1, message: error instanceof Error ? error.message : '查询失败' };
      }
    });

    export default router;