# All files / modules/tts tts.controller.ts

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

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

     import Router from '@koa/router';
    import { Context } from 'koa';
    import path from 'path';
    import fs from 'fs';
    import * as TtsService from './tts.service';
    import { BadRequestError, NotFoundError } from '../../middleware/errorHandler';
    import { optionalAuth } from '../../middleware/auth';
    import { usageLimitMiddleware, checkWordLimit } from '../../middleware/usageLimit';
    import { checkAudioQuota } from '../subscription/subscription.service';
    import { prisma } from '../../models';

    const router = new Router();

    // 获取可用音色列表
    router.get('/voices', async (ctx: Context) => {
      const voices = TtsService.getVoices();
      const baseUrl = `${ctx.protocol}://${ctx.host}`;

      // 为每个音色注入本地预览URL
      const result = voices.map(v => ({
        ...v,
        preview: fs.existsSync(path.join(process.cwd(), '..', 'voices', `${v.id}.mp3`))
          ? `${baseUrl}/tts/voices/${v.id}.mp3`
          : undefined,
      }));

      ctx.body = {
        code: 0,
        message: 'success',
        data: { voices: result },
      };
    });

    // 获取可用 TTS 服务商列表
    router.get('/providers', async (ctx: Context) => {
      const providers = TtsService.getAvailableProviders();

      ctx.body = {
        code: 0,
        message: 'success',
        data: { providers },
      };
    });

    // 测试 MySQL 连接
    router.get('/test-db', async (ctx: Context) => {
      try {
        const count = await prisma.book.count();
        ctx.body = {
          code: 0,
          message: 'success',
          data: { count, connectionState: 'connected' },
        };
      } catch (error: any) {
        ctx.body = {
          code: 500,
          message: 'error',
          data: { error: error.message },
        };
      }
    });

    // 生成音频（异步模式 - 复用有声书生成立逻辑）
    router.post(
      '/generate',
      optionalAuth,
      async (ctx: Context) => {
        const userId = ctx.state.user?.userId;
        const { text, voiceId, voiceParams, bookId, chapterTitle } = ctx.request.body as {
          text: string;
          voiceId: string;
          voiceParams?: { speed?: number; pitch?: number; volume?: number };
          bookId?: string;
          chapterTitle?: string;
        };

        // 调试日志
        console.log('📥 收到 TTS 请求:', { textLength: text?.length, voiceId, voiceParams, bookId, chapterTitle });

        // 参数验证
        if (!text || text.trim().length === 0) {
          throw new BadRequestError('请输入要转换的文本');
        }

        if (text.trim().length < 10) {
          throw new BadRequestError('文本过短，至少需要10个字符');
        }

        if (!voiceId) {
          throw new BadRequestError('请选择音色');
        }

        // 如果指定了 bookId，验证书籍是否存在
        if (bookId) {
          const book = await prisma.book.findUnique({ where: { id: parseInt(bookId) } });
          if (!book) {
            throw new NotFoundError('书籍不存在');
          }
        }

        // ========== 统一音频分钟配额检查 ==========
        const wordCount = text.length;
        const effectiveUserId = userId ? parseInt(userId) : null;

        if (effectiveUserId) {
          const audioQuota = await checkAudioQuota(effectiveUserId, wordCount);
          if (!audioQuota.allowed) {
            throw new BadRequestError(audioQuota.reason as string);
          }
        }

        // 默认参数
        const params = {
          speed: voiceParams?.speed || 1.0,
          pitch: voiceParams?.pitch || 0,
          volume: voiceParams?.volume || 50,
        };

        // 复用有声书生成立逻辑：创建章节 + 入队 TtsTask，立即返回
        const result = await TtsService.requestTtsGeneration(userId, text, voiceId, params, {
          bookId,
          chapterTitle,
        });

        ctx.body = {
          code: 0,
          message: '音频生成任务已创建，正在排队处理',
          data: result, // { chapterId, bookId }
        };
      }
    );

    // 获取音频生成状态
    router.get('/status/:audioId', async (ctx: Context) => {
      const { audioId } = ctx.params;
      const result = await TtsService.getAudioStatus(audioId);

      if (result.status === 'not_found') {
        throw new NotFoundError('音频不存在');
      }

      ctx.body = {
        code: 0,
        message: 'success',
        data: result,
      };
    });

    // 获取章节音频生成状态（供前端轮询）
    router.get('/chapter-status/:chapterId', async (ctx: Context) => {
      const { chapterId } = ctx.params;
      const id = parseInt(chapterId);

      if (isNaN(id)) {
        throw new BadRequestError('无效的章节ID');
      }

      const chapter = await prisma.bookChapter.findUnique({
        where: { id },
        select: {
          id: true,
          genStage: true,
          audioUrl: true,
          audioDuration: true,
          title: true,
        },
      });

      if (!chapter) {
        throw new NotFoundError('章节不存在');
      }

      ctx.body = {
        code: 0,
        message: 'success',
        data: {
          chapterId: chapter.id,
          genStage: chapter.genStage,
          audioUrl: chapter.audioUrl,
          audioDuration: chapter.audioDuration,
          title: chapter.title,
          isReady: chapter.genStage === 'audio_completed' || chapter.genStage === 'video_generating' || chapter.genStage === 'video_completed',
          isFailed: chapter.genStage === 'failed',
        },
      };
    });

    // 预览音色 - 优先使用本地样本文件，不存在时才调用API生成
    router.post('/preview', async (ctx: Context) => {
      const { voiceId } = ctx.request.body as {
        voiceId: string;
        voiceParams?: { speed?: number; pitch?: number; volume?: number };
      };

      if (!voiceId) {
        throw new BadRequestError('请选择音色');
      }

      const baseUrl = `${ctx.protocol}://${ctx.host}`;
      const localFile = `/tts/voices/${voiceId}.mp3`;
      const filePath = path.join(process.cwd(), '..', 'voices', `${voiceId}.mp3`);

      // 检查本地样本文件是否存在
      if (fs.existsSync(filePath)) {
        console.log(`🎵 [Preview] 使用本地样本: ${voiceId}`);
        ctx.body = {
          code: 0,
          message: 'success',
          data: {
            previewText: `${voiceId} 音色试听`,
            voiceId,
            audioUrl: `${baseUrl}${localFile}`,
          },
        };
        return;
      }

      // 本地不存在，降级到 API 生成
      console.log(`🔊 [Preview] 本地无样本，API生成: ${voiceId}`);
      const previewText = '你好，欢迎使用AI有声书';

      try {
        const result = await TtsService.generatePreview(voiceId, undefined, undefined);
        ctx.body = {
          code: 0,
          message: 'success',
          data: { previewText, voiceId, audioUrl: result.audioUrl },
        };
      } catch (error: any) {
        ctx.body = {
          code: 500,
          message: '预览生成失败：' + error.message,
          data: null,
        };
      }
    });

    // 获取音频下载信息
    router.get('/download/:audioId', async (ctx: Context) => {
      const { audioId } = ctx.params;

      try {
        const audioRecord = await prisma.audioRecord.findUnique({
          where: { id: parseInt(audioId) },
        });

        if (!audioRecord) {
          throw new NotFoundError('音频不存在');
        }

        // 检查是否有音频URL
        if (!audioRecord.audioUrl) {
          throw new NotFoundError('音频文件不存在');
        }

        // 返回下载信息（前端直接使用 URL 下载）
        ctx.body = {
          code: 0,
          message: 'success',
          data: {
            id: audioRecord.id,
            title: audioRecord.title,
            audioUrl: audioRecord.audioUrl,
            duration: audioRecord.audioDuration,
            size: audioRecord.audioSize,
            downloadUrl: audioRecord.audioUrl, // 直接使用音频URL下载
          },
        };
      } catch (error: any) {
        if (error instanceof NotFoundError) {
          throw error;
        }
        console.error('获取下载信息失败:', error);
        ctx.status = 500;
        ctx.body = { code: 500, message: '获取下载信息失败: ' + error.message };
      }
    });

    // 批量下载音频（获取下载链接列表）
    router.post('/download/batch', async (ctx: Context) => {
      const { audioIds } = ctx.request.body as { audioIds: string[] };

      if (!audioIds || audioIds.length === 0) {
        throw new BadRequestError('请选择要下载的音频');
      }

      if (audioIds.length > 50) {
        throw new BadRequestError('一次最多下载50个音频');
      }

      try {
        const audios = await prisma.audioRecord.findMany({
          where: {
            id: {
              in: audioIds.map(id => parseInt(id)),
            },
          },
          select: {
            id: true,
            title: true,
            audioUrl: true,
            audioDuration: true,
            audioSize: true,
          },
        });

        // 过滤出有音频URL的记录
        const validAudios = audios.filter(a => a.audioUrl);

        ctx.body = {
          code: 0,
          message: 'success',
          data: {
            total: validAudios.length,
            audios: validAudios.map(a => ({
              id: a.id,
              title: a.title,
              downloadUrl: a.audioUrl,
              duration: a.audioDuration,
              size: a.audioSize,
            })),
          },
        };
      } catch (error: any) {
        console.error('批量下载失败:', error);
        ctx.body = { code: 500, message: '批量下载失败: ' + error.message };
      }
    });

    export default router;