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

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

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

     /**
     * 视频发布模块 - API 路由控制器
     */

    import Router from '@koa/router';
    import { authMiddleware } from '../../middleware/auth';
    import {
      savePlatformAccount,
      getPlatformAccount,
      getUserPlatformAccounts,
      deletePlatformAccount,
      validateAccount,
      createPublishTask,
      getPublishTasks,
      getPublishTask,
      updatePublishTask,
      publishToDouyin,
      publishToBilibili,
      getVideoProjectForPublish,
    } from './publish.service';

    const router = new Router();

    // 所有路由需要登录（挂载时会加上 /api/publish 前缀）
    router.use(authMiddleware);

    // 辅助：从 ctx.state.user 提取数字 userId（JWT 里是字符串，转为 number）
    function getUserId(ctx: any): number {
      return Number(ctx.state.user?.userId);
    }

    // ============ 平台账号管理 ============

    /**
     * GET /api/publish/accounts
     * 获取用户已绑定的平台账号
     */
    router.get('/accounts', async (ctx) => {
      const userId = getUserId(ctx);
      if (!userId) {
        ctx.status = 401;
        ctx.body = { success: false, error: '请先登录' };
        return;
      }

      const accounts = await getUserPlatformAccounts(userId);
      ctx.body = {
        success: true,
        data: accounts.map((a) => ({
          platform: a.platform,
          nickname: a.nickname,
          avatar: a.avatar,
          isValid: a.isValid,
          createdAt: a.createdAt,
        })),
      };
    });

    /**
     * POST /api/publish/accounts
     * 绑定平台账号（保存登录凭证）
     */
    router.post('/accounts', async (ctx) => {
      const userId = getUserId(ctx);
      if (!userId) {
        ctx.status = 401;
        ctx.body = { success: false, error: '请先登录' };
        return;
      }

      const body = ctx.request.body as any;
      const { platform, cookies, headers, nickname, avatar, expireTime } = body;

      if (!platform || !cookies) {
        ctx.status = 400;
        ctx.body = { success: false, error: '缺少必要参数' };
        return;
      }

      if (!['douyin', 'kuaishou', 'bilibili'].includes(platform)) {
        ctx.status = 400;
        ctx.body = { success: false, error: '不支持的平台' };
        return;
      }

      const account = await savePlatformAccount(userId, platform, {
        cookies,
        headers,
        nickname,
        avatar,
        expireTime: expireTime ? new Date(expireTime) : undefined,
      });

      ctx.body = {
        success: true,
        data: {
          platform: account.platform,
          nickname: account.nickname,
          avatar: account.avatar,
          isValid: account.isValid,
        },
      };
    });

    /**
     * DELETE /api/publish/accounts/:platform
     * 解绑平台账号
     */
    router.delete('/accounts/:platform', async (ctx) => {
      const userId = getUserId(ctx);
      if (!userId) {
        ctx.status = 401;
        ctx.body = { success: false, error: '请先登录' };
        return;
      }

      const platform = ctx.params.platform;
      const success = await deletePlatformAccount(userId, platform);

      if (!success) {
        ctx.status = 404;
        ctx.body = { success: false, error: '账号不存在' };
        return;
      }

      ctx.body = { success: true };
    });

    /**
     * POST /api/publish/accounts/:platform/validate
     * 验证账号凭证是否有效
     */
    router.post('/accounts/:platform/validate', async (ctx) => {
      const userId = getUserId(ctx);
      if (!userId) {
        ctx.status = 401;
        ctx.body = { success: false, error: '请先登录' };
        return;
      }

      const platform = ctx.params.platform;
      const result = await validateAccount(userId, platform);

      ctx.body = { success: true, data: result };
    });

    // ============ 发布任务 ============

    /**
     * GET /api/publish/tasks
     * 获取发布任务列表
     */
    router.get('/tasks', async (ctx) => {
      const userId = getUserId(ctx);
      if (!userId) {
        ctx.status = 401;
        ctx.body = { success: false, error: '请先登录' };
        return;
      }

      const { platform, status, page, pageSize } = ctx.query;
      const result = await getPublishTasks(userId, {
        platform: platform as string,
        status: status as string,
        page: page ? Number(page) : 1,
        pageSize: pageSize ? Number(pageSize) : 20,
      });

      ctx.body = {
        success: true,
        data: {
          items: result.items,
          total: result.total,
        },
      };
    });

    /**
     * GET /api/publish/tasks/:id
     * 获取单个发布任务
     */
    router.get('/tasks/:id', async (ctx) => {
      const userId = getUserId(ctx);
      if (!userId) {
        ctx.status = 401;
        ctx.body = { success: false, error: '请先登录' };
        return;
      }

      const id = Number(ctx.params.id);
      const task = await getPublishTask(id);

      if (!task || task.userId !== userId) {
        ctx.status = 404;
        ctx.body = { success: false, error: '任务不存在' };
        return;
      }

      ctx.body = { success: true, data: task };
    });

    /**
     * POST /api/publish/tasks
     * 创建发布任务并开始发布
     */
    router.post('/tasks', async (ctx) => {
      const userId = getUserId(ctx);
      if (!userId) {
        ctx.status = 401;
        ctx.body = { success: false, error: '请先登录' };
        return;
      }

      const body = ctx.request.body as any;
      const { videoProjectId, videoUrl, platform, title, description, tags, coverUrl } = body;

      if (!platform || !title) {
        ctx.status = 400;
        ctx.body = { success: false, error: '缺少必要参数' };
        return;
      }

      // 支持两种方式：1. 使用 videoProjectId  2. 直接使用 videoUrl
      let finalVideoUrl = videoUrl;
      let finalDescription = description || '';
      let finalCoverUrl = coverUrl;

      if (videoProjectId) {
        // 方式1：通过 videoProjectId 获取视频信息
        const projectInfo = await getVideoProjectForPublish(videoProjectId);
        if (!projectInfo) {
          ctx.status = 404;
          ctx.body = { success: false, error: '视频项目不存在或未生成视频' };
          return;
        }
        finalVideoUrl = projectInfo.videoUrl;
        finalDescription = description || projectInfo.description;
        finalCoverUrl = coverUrl || projectInfo.coverUrl;
      } else if (!videoUrl) {
        // 两种方式都没有
        ctx.status = 400;
        ctx.body = { success: false, error: '请提供 videoProjectId 或 videoUrl' };
        return;
      }

      // 创建发布任务
      const task = await createPublishTask(userId, {
        videoProjectId: videoProjectId || 0, // 如果没有 projectId 则用 0
        platform,
        title,
        description: finalDescription,
        tags,
        coverUrl: finalCoverUrl,
      });

      // 更新视频URL
      await updatePublishTask(task.id!, { videoUrl: finalVideoUrl });

      // 根据平台执行发布
      let result: { success: boolean; publishedUrl?: string; error?: string };

      if (platform === 'douyin') {
        result = await publishToDouyin(userId, task.id!);
      } else if (platform === 'bilibili') {
        result = await publishToBilibili(userId, task.id!);
      } else {
        result = { success: false, error: '该平台暂不支持自动发布' };
      }

      ctx.body = {
        success: true,
        data: {
          taskId: task.id,
          ...result,
        },
      };
    });

    /**
     * POST /api/publish/tasks/:id/publish
     * 重新发布某个任务
     */
    router.post('/tasks/:id/publish', async (ctx) => {
      const userId = getUserId(ctx);
      if (!userId) {
        ctx.status = 401;
        ctx.body = { success: false, error: '请先登录' };
        return;
      }

      const taskId = Number(ctx.params.id);
      const task = await getPublishTask(taskId);

      if (!task || task.userId !== userId) {
        ctx.status = 404;
        ctx.body = { success: false, error: '任务不存在' };
        return;
      }

      let result: { success: boolean; publishedUrl?: string; error?: string };

      if (task.platform === 'douyin') {
        result = await publishToDouyin(userId, taskId);
      } else if (task.platform === 'bilibili') {
        result = await publishToBilibili(userId, taskId);
      } else {
        result = { success: false, error: '该平台暂不支持' };
      }

      ctx.body = { success: true, data: result };
    });

    // ============ 辅助接口 ============

    /**
     * GET /api/publish/video/:projectId/preview
     * 获取视频发布预览信息
     */
    router.get('/video/:projectId/preview', async (ctx) => {
      const projectId = Number(ctx.params.projectId);
      const projectInfo = await getVideoProjectForPublish(projectId);

      if (!projectInfo) {
        ctx.status = 404;
        ctx.body = { success: false, error: '视频不存在' };
        return;
      }

      ctx.body = { success: true, data: projectInfo };
    });

    export default router;