# All files / modules/player player.service.ts

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

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

     import { prisma } from '../../models';
    import { AudioMerger } from '../tts/audio-merger';
    import path from 'path';

    /**
     * 获取用户播放记录
     */
    export async function getPlayProgress(userId: string, chapterId?: number) {
      const userIdNum = parseInt(userId);
      const where: any = { userId: userIdNum };
      if (chapterId) {
        where.chapterId = chapterId;
      }

      const records = await prisma.playRecord.findMany({
        where,
        include: {
          chapter: {
            select: {
              id: true,
              number: true,
              title: true,
              audioUrl: true,
              audioDuration: true,
            },
          },
        },
        orderBy: { updatedAt: 'desc' },
      });

      return records;
    }

    /**
     * 保存播放进度
     */
    export async function savePlayProgress(
      userId: string,
      chapterId: number,
      progress: number,
      duration: number
    ) {
      const userIdNum = parseInt(userId);
      // 使用 upsert 语义：如果不存在则创建，存在则更新
      const existing = await prisma.playRecord.findUnique({
        where: {
          userId_chapterId: {
            userId: userIdNum,
            chapterId,
          },
        },
      });

      if (existing) {
        // 更新
        return await prisma.playRecord.update({
          where: {
            userId_chapterId: {
              userId: userIdNum,
              chapterId,
            },
          },
          data: {
            progress,
            duration,
          },
        });
      } else {
        // 创建
        return await prisma.playRecord.create({
          data: {
            userId: userIdNum,
            chapterId,
            progress,
            duration,
          },
        });
      }
    }

    /**
     * 删除播放记录
     */
    export async function deletePlayRecord(userId: string, chapterId: number) {
      const userIdNum = parseInt(userId);
      return await prisma.playRecord.delete({
        where: {
          userId_chapterId: {
            userId: userIdNum,
            chapterId,
          },
        },
      });
    }

    /**
     * 更新播放进度
     */
    export async function updatePlayProgress(
      userId: string,
      chapterId: number,
      progress: number,
      duration?: number
    ) {
      const userIdNum = parseInt(userId);
      const data: any = { progress };
      if (duration !== undefined) {
        data.duration = duration;
      }

      return await prisma.playRecord.update({
        where: {
          userId_chapterId: {
            userId: userIdNum,
            chapterId,
          },
        },
        data,
      });
    }

    /**
     * 获取单个章节的播放进度
     */
    export async function getSingleProgress(userId: string, chapterId: number) {
      const userIdNum = parseInt(userId);
      const record = await prisma.playRecord.findUnique({
        where: {
          userId_chapterId: {
            userId: userIdNum,
            chapterId,
          },
        },
      });

      return record;
    }

    /**
     * 合并章节的所有小节音频
     * 当播放章（level=1）时，自动合并其下所有小节（level=3）的音频
     * @param chapterId 章的ID (level=1)
     * @returns 合并后的音频URL
     */
    export async function mergeChapterAudios(chapterId: number): Promise<string | null> {
      // 获取章节信息
      let chapter = await prisma.bookChapter.findUnique({
        where: { id: chapterId },
      });

      if (!chapter) {
        console.error(`❌ 章节 ${chapterId} 不存在`);
        return null;
      }

      // 如果不是1级章，向上追溯到1级章（兼容调用方传入节/section的ID）
      let effectiveChapterId = chapterId;
      if (chapter.level !== 1) {
        console.log(`[MergeAudio] 当前节点 level=${chapter.level}，向上追溯1级章...`);
        let currentLevel = chapter.level;
        let currentId = chapter.id;
        let currentParentId = chapter.parentId;

        while (currentLevel > 1 && currentParentId) {
          const parent = await prisma.bookChapter.findUnique({
            where: { id: currentParentId },
            select: { id: true, level: true, parentId: true },
          });
          if (!parent) break;
          currentLevel = parent.level;
          currentId = parent.id;
          currentParentId = parent.parentId;
        }

        if (currentLevel !== 1) {
          console.log(`[MergeAudio] ⏭️ 无法找到1级章，当前追溯结果 level=${currentLevel}`);
          return null;
        }

        console.log(`[MergeAudio] 追溯到1级章 id=${currentId}，重新查询完整信息`);
        chapter = await prisma.bookChapter.findUnique({
          where: { id: currentId },
        });
        if (!chapter) {
          console.error(`❌ 追溯到的1级章 ${currentId} 不存在`);
          return null;
        }
        effectiveChapterId = chapter.id;
      }

      // 如果已经有合并后的音频（audioUrl存在且是合并后的），直接返回
      if (chapter.audioUrl && chapter.audioUrl.includes('_merged')) {
        console.log(`✅ 章节 ${chapterId} 已有合并音频: ${chapter.audioUrl}`);
        return chapter.audioUrl;
      }

      // 1. 找到所有节（level=2，parentId=章ID）
      const sections = await prisma.bookChapter.findMany({
        where: {
          parentId: effectiveChapterId,
          level: 2,
        },
        orderBy: { number: 'asc' },
      });

      if (sections.length === 0) {
        console.log(`⏭️ 章 ${effectiveChapterId} 没有子节`);
        return null;
      }

      // 2. 收集待合并的音频URL
      // 先尝试查找 level=3 小节（3层树：章→节→小节）
      const sectionIds = sections.map(s => s.id);
      const subsections = await prisma.bookChapter.findMany({
        where: {
          parentId: { in: sectionIds },
          level: 3,
          audioUrl: { not: '' },
        },
        orderBy: { number: 'asc' },
      });

      let audioFiles: string[];
      if (subsections.length > 0) {
        // 3层树：合并所有 level=3 小节音频
        audioFiles = subsections
          .map(s => s.audioUrl)
          .filter((url): url is string => !!url);
        console.log(`🔄 合并章 ${effectiveChapterId} 下 ${audioFiles.length} 个小节(level=3)音频...`);
      } else {
        // 2层树：直接合并 level=2 的节音频
        audioFiles = sections
          .filter(s => s.audioUrl && s.audioUrl !== '')
          .map(s => s.audioUrl!);
        console.log(`🔄 合并章 ${effectiveChapterId} 下 ${audioFiles.length} 个节(level=2)音频...`);
      }

      if (audioFiles.length === 0) {
        console.log(`⏭️ 章 ${effectiveChapterId} 下没有音频可合并`);
        return null;
      }

      // 3. 生成合并后的输出路径
      const uploadsDir = path.join(process.cwd(), 'uploads');
      const outputFileName = `chapter_${effectiveChapterId}_merged_${Date.now()}.mp3`;
      const outputPath = path.join(uploadsDir, outputFileName);

      // 4. 转换路径：OSS远程URL保持原样，本地路径转为绝对路径
      const absoluteAudioFiles = audioFiles.map(f => {
        if (f.startsWith('http')) return f; // OSS URL 保持原样，AudioMerger 会检测并远程处理
        const relativePath = f.replace(/^\//, '');
        return path.join(process.cwd(), relativePath);
      });

      try {
        // 5. 合并音频，捕获返回值（OSS模式返回OSS URL，本地模式返回本地路径）
        const mergeResult = await AudioMerger.merge(absoluteAudioFiles, outputPath);

        // 6. 更新章节的 audioUrl
        // 本地合并返回绝对路径需转为相对URL，OSS合并直接返回远程URL
        let mergedAudioUrl: string;
        if (mergeResult.startsWith('http')) {
          mergedAudioUrl = mergeResult; // OSS URL
        } else {
          // 本地绝对路径 → 相对URL
          const cwd = process.cwd().replace(/\\/g, '/');
          const normalized = mergeResult.replace(/\\/g, '/');
          mergedAudioUrl = normalized.startsWith(cwd)
            ? normalized.substring(cwd.length)
            : `/uploads/${outputFileName}`;
        }

        // 获取合并后音频的时长
        const mergedDuration = await AudioMerger.getDuration(mergeResult);

        await prisma.bookChapter.update({
          where: { id: effectiveChapterId },
          data: {
            audioUrl: mergedAudioUrl,
            audioDuration: mergedDuration || 0,
          },
        });

        console.log(`✅ 章节 ${effectiveChapterId} 音频合并完成: ${mergedAudioUrl}, 时长: ${mergedDuration}s`);
        return mergedAudioUrl;
      } catch (error) {
        console.error(`❌ 章节 ${effectiveChapterId} 音频合并失败:`, error);
        return null;
      }
    }

    /**
     * 获取章节音频URL（如果是章则自动合并小节音频）
     * @param chapterId 章节ID
     */
    export async function getChapterAudioUrl(chapterId: number): Promise<string | null> {
      return await mergeChapterAudios(chapterId);
    }

    /**
     * 获取用户最近播放记录
     * @param userId 用户ID
     * @param limit 返回数量限制，默认10条
     * @returns 最近播放记录列表
     */
    export async function getRecentPlayRecords(userId: string, limit: number = 10) {
      const userIdNum = parseInt(userId);

      const records = await prisma.playRecord.findMany({
        where: { userId: userIdNum },
        include: {
          chapter: {
            include: {
              book: {
                select: {
                  id: true,
                  title: true,
                  coverUrl: true,
                },
              },
            },
          },
        },
        orderBy: { updatedAt: 'desc' },
        take: limit,
      });

      return records.map((record) => ({
        id: record.chapterId.toString(),
        title: record.chapter?.book?.title || record.chapter?.title || '',
        coverUrl: record.chapter?.book?.coverUrl || '',
        progress: Math.round((record.progress / (record.duration || 1)) * 100),
        updatedAt: record.updatedAt.toISOString(),
      }));
    }