All files / dingtalk-openclaw-connector/src/services/media chunk-upload.ts

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

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
/**
 * 钉钉文件分块上传模块
 * 支持大文件(>20MB)的分块上传
 * 
 * API 文档:
 * - 开启事务:https://open.dingtalk.com/document/development/enable-upload-transaction
 * - 上传块:https://open.dingtalk.com/document/development/upload-file-blocks
 * - 提交事务:https://open.dingtalk.com/document/development/submit-a-file-upload-transaction
 */
 
import axios from 'axios';
import * as fs from 'fs';
import * as path from 'path';
import { createLogger } from '../../utils/logger.ts';
 
const DINGTALK_OAPI = 'https://oapi.dingtalk.com';
 
/** 分块上传配置 */
export const CHUNK_CONFIG = {
  MIN_CHUNK_SIZE: 100 * 1024, // 最小分块 100KB
  MAX_CHUNK_SIZE: 8 * 1024 * 1024, // 最大分块 8MB
  DEFAULT_CHUNK_SIZE: 5 * 1024 * 1024, // 默认分块 5MB
  SIZE_THRESHOLD: 20 * 1024 * 1024, // 超过 20MB 使用分块上传
};
 
/** 开启上传事务响应 */
interface UploadTransactionResponse {
  errcode: number;
  errmsg: string;
  upload_id: string;
}
 
/** 上传文件块响应 */
interface UploadBlockResponse {
  errcode: number;
  errmsg: string;
}
 
/** 提交上传事务响应 */
interface SubmitTransactionResponse {
  errcode: number;
  errmsg: string;
  file_id?: string;
  download_code?: string;
}
 
/**
 * 步骤一:开启分块上传事务
 * @param oapiToken 钉钉 access_token
 * @param fileName 文件名
 * @param fileSize 文件大小(字节)
 * @param log 日志对象
 */
export async function enableUploadTransaction(
  oapiToken: string,
  fileName: string,
  fileSize: number,
  debug: boolean = false,
): Promise<string | null> {
  const log = createLogger(debug, 'DingTalk][ChunkUpload');
  
  try {
    log.info(`开启上传事务:${fileName}, 大小:${(fileSize / 1024 / 1024).toFixed(2)}MB`);
 
    const FormData = (await import('form-data')).default;
    const form = new FormData();
    form.append('file_name', fileName);
    form.append('file_size', fileSize.toString());
 
    const resp = await axios.post<UploadTransactionResponse>(
      `${DINGTALK_OAPI}/file/upload/transaction/enabled`,
      form,
      {
        params: {
          access_token: oapiToken,
        },
        headers: form.getHeaders(),
        timeout: 30_000,
      }
    );
 
    if (resp.data.errcode === 0) {
      log.info(`事务开启成功,upload_id: ${resp.data.upload_id}`);
      return resp.data.upload_id;
    } else {
      log.error(`开启事务失败:${resp.data.errmsg}`);
      return null;
    }
  } catch (err: any) {
    log.error(`开启事务异常:${err.message}`);
    console.error(`开启事务异常详情:`, err.response?.data || err);
    return null;
  }
}
 
/**
 * 步骤二:上传文件块
 * @param oapiToken 钉钉 access_token
 * @param uploadId 上传事务 ID
 * @param chunkData 文件块数据
 * @param chunkNumber 块编号(从 1 开始)
 * @param totalChunks 总块数
 * @param log 日志对象
 */
export async function uploadFileBlock(
  oapiToken: string,
  uploadId: string,
  chunkData: Buffer,
  chunkNumber: number,
  totalChunks: number,
  debug: boolean = false,
): Promise<boolean> {
  const log = createLogger(debug, 'DingTalk][ChunkUpload');
  
  try {
    log.info(`上传块 ${chunkNumber}/${totalChunks}, 大小:${(chunkData.length / 1024).toFixed(2)}KB`);
 
    const FormData = (await import('form-data')).default;
    const form = new FormData();
    form.append('upload_id', uploadId);
    form.append('chunk_number', chunkNumber.toString());
    form.append('total_chunks', totalChunks.toString());
    form.append('file', chunkData, {
      filename: `chunk_${chunkNumber}`,
      contentType: 'application/octet-stream',
    });
 
    const resp = await axios.post<UploadBlockResponse>(
      `${DINGTALK_OAPI}/file/upload/block`,
      form,
      {
        params: { access_token: oapiToken },
        headers: form.getHeaders(),
        timeout: 120_000, // 大块上传需要更长时间
      }
    );
 
    if (resp.data.errcode === 0) {
      log.info(`块 ${chunkNumber} 上传成功`);
      return true;
    } else {
      log.error(`块 ${chunkNumber} 上传失败:${resp.data.errmsg}`);
      return false;
    }
  } catch (err: any) {
    log.error(`块 ${chunkNumber} 上传异常:${err.message}`);
    return false;
  }
}
 
/**
 * 步骤三:提交分块上传事务
 * @param oapiToken 钉钉 access_token
 * @param uploadId 上传事务 ID
 * @param fileName 文件名
 * @param log 日志对象
 */
export async function submitUploadTransaction(
  oapiToken: string,
  uploadId: string,
  fileName: string,
  debug: boolean = false,
): Promise<{ fileId?: string; downloadCode?: string } | null> {
  const log = createLogger(debug, 'DingTalk][ChunkUpload');
  
  try {
    log.info(`提交上传事务:${uploadId}`);
 
    const resp = await axios.get<SubmitTransactionResponse>(
      `${DINGTALK_OAPI}/file/upload/transaction/submit`,
      {
        params: {
          access_token: oapiToken,
          upload_id: uploadId,
          file_name: fileName,
        },
        timeout: 60_000,
      }
    );
 
    if (resp.data.errcode === 0) {
      log.info(`事务提交成功,file_id: ${resp.data.file_id}, download_code: ${resp.data.download_code}`);
      return {
        fileId: resp.data.file_id,
        downloadCode: resp.data.download_code,
      };
    } else {
      log.error(`事务提交失败:${resp.data.errmsg}`);
      return null;
    }
  } catch (err: any) {
    log.error(`事务提交异常:${err.message}`);
    return null;
  }
}
 
/**
 * 计算分块参数
 */
function calculateChunkParams(fileSize: number): { chunkSize: number; totalChunks: number } {
  // 根据文件大小动态调整分块大小
  let chunkSize = CHUNK_CONFIG.DEFAULT_CHUNK_SIZE;
  
  if (fileSize > 100 * 1024 * 1024) {
    // >100MB,使用最大分块 8MB
    chunkSize = CHUNK_CONFIG.MAX_CHUNK_SIZE;
  } else if (fileSize > 50 * 1024 * 1024) {
    // >50MB,使用 6MB 分块
    chunkSize = 6 * 1024 * 1024;
  }
  
  const totalChunks = Math.ceil(fileSize / chunkSize);
  return { chunkSize, totalChunks };
}
 
/**
 * 分块上传大文件(>20MB)
 * @param filePath 文件路径
 * @param mediaType 媒体类型:video, file
 * @param oapiToken 钉钉 access_token
 * @param log 日志对象
 * @returns download_code 或 null
 */
export async function uploadLargeFileByChunks(
  filePath: string,
  mediaType: 'video' | 'file',
  oapiToken: string,
  debug: boolean = false,
): Promise<string | null> {
  const log = createLogger(debug, 'DingTalk][ChunkUpload');
  
  try {
    const absPath = path.resolve(filePath);
    if (!fs.existsSync(absPath)) {
      log.warn(`文件不存在:${absPath}`);
      return null;
    }
 
    const stats = fs.statSync(absPath);
    const fileSize = stats.size;
    const fileName = path.basename(absPath);
    const fileSizeMB = (fileSize / 1024 / 1024).toFixed(2);
 
    log.info(`开始分块上传:${fileName}, 大小:${fileSizeMB}MB, 类型:${mediaType}`);
 
    // 步骤一:开启上传事务
    const uploadId = await enableUploadTransaction(oapiToken, fileName, fileSize, debug);
    if (!uploadId) {
      log.error(`开启事务失败,终止上传`);
      return null;
    }
 
    // 计算分块参数
    const { chunkSize, totalChunks } = calculateChunkParams(fileSize);
    log.info(`分块参数:chunkSize=${(chunkSize / 1024 / 1024).toFixed(2)}MB, totalChunks=${totalChunks}`);
 
    // 步骤二:分块上传
    const fileBuffer = fs.readFileSync(absPath);
    let successCount = 0;
 
    for (let i = 0; i < totalChunks; i++) {
      const start = i * chunkSize;
      const end = Math.min(start + chunkSize, fileSize);
      const chunkData = fileBuffer.slice(start, end);
 
      const success = await uploadFileBlock(
        oapiToken,
        uploadId,
        chunkData,
        i + 1, // chunkNumber 从 1 开始
        totalChunks,
        debug
      );
 
      if (!success) {
        log.error(`块 ${i + 1} 上传失败,终止上传`);
        return null;
      }
 
      successCount++;
      log.info(`进度:${successCount}/${totalChunks} (${((successCount / totalChunks) * 100).toFixed(1)}%)`);
    }
 
    // 步骤三:提交上传事务
    const result = await submitUploadTransaction(oapiToken, uploadId, fileName, debug);
    if (!result || !result.downloadCode) {
      log.error(`提交事务失败`);
      return null;
    }
 
    log.info(`分块上传完成:${fileName}, download_code: ${result.downloadCode}`);
    return result.downloadCode;
  } catch (err: any) {
    log.error(`分块上传异常:${err.message}`);
    return null;
  }
}