@iflyrpa/actions 4.0.9 → 4.1.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bundle.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /*! For license information please see bundle.js.LICENSE.txt */
2
2
 
3
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="1b1757c5-d32a-56c9-a781-bb1e22dcee63")}catch(e){}}();
3
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="51f3980f-4908-5c61-864e-675122bae629")}catch(e){}}();
4
4
  var __webpack_modules__ = {
5
5
  "../../node_modules/.pnpm/agent-base@7.1.4/node_modules/agent-base/dist/helpers.js": function(__unused_webpack_module, exports1, __webpack_require__) {
6
6
  "use strict";
@@ -12446,6 +12446,7 @@ var __webpack_exports__ = {};
12446
12446
  SessionCheckResultSchema: ()=>SessionCheckResultSchema,
12447
12447
  DouyinGetCommentReplyListParamsSchema: ()=>DouyinGetCommentReplyListParamsSchema,
12448
12448
  DouyinCreateCommentReplyParamsSchema: ()=>DouyinCreateCommentReplyParamsSchema,
12449
+ ShipinhaoPublishVideoParamsSchema: ()=>ShipinhaoPublishVideoParamsSchema,
12449
12450
  DouyinGetHotParamsSchema: ()=>DouyinGetHotParamsSchema,
12450
12451
  DouyinGetMusicParamsSchema: ()=>DouyinGetMusicParamsSchema,
12451
12452
  FetchArticlesDataSchema: ()=>FetchArticlesDataSchema,
@@ -12492,9 +12493,7 @@ var __webpack_exports__ = {};
12492
12493
  var package_namespaceObject = {
12493
12494
  i8: "0.1.2"
12494
12495
  };
12495
- var package_namespaceObject_0 = {
12496
- i8: "4.0.9"
12497
- };
12496
+ var package_namespaceObject_0 = JSON.parse('{"i8":"4.1.0-beta.1"}');
12498
12497
  const external_node_fs_namespaceObject = require("node:fs");
12499
12498
  var external_node_fs_default = /*#__PURE__*/ __webpack_require__.n(external_node_fs_namespaceObject);
12500
12499
  const external_node_http_namespaceObject = require("node:http");
@@ -12940,7 +12939,7 @@ var __webpack_exports__ = {};
12940
12939
  Number.MAX_VALUE
12941
12940
  ]
12942
12941
  };
12943
- function pick(schema, mask) {
12942
+ function dist_pick(schema, mask) {
12944
12943
  const currDef = schema._zod.def;
12945
12944
  const def = mergeDefs(schema._zod.def, {
12946
12945
  get shape () {
@@ -13310,7 +13309,7 @@ var __webpack_exports__ = {};
13310
13309
  const xid = /^[0-9a-vA-V]{20}$/;
13311
13310
  const ksuid = /^[A-Za-z0-9]{27}$/;
13312
13311
  const nanoid = /^[a-zA-Z0-9_-]{21}$/;
13313
- const duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
13312
+ const dist_duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
13314
13313
  const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;
13315
13314
  const dist_uuid = (version)=>{
13316
13315
  if (!version) return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;
@@ -13996,7 +13995,7 @@ var __webpack_exports__ = {};
13996
13995
  $ZodStringFormat.init(inst, def);
13997
13996
  });
13998
13997
  const $ZodISODuration = /*@__PURE__*/ $constructor("$ZodISODuration", (inst, def)=>{
13999
- def.pattern ?? (def.pattern = duration);
13998
+ def.pattern ?? (def.pattern = dist_duration);
14000
13999
  $ZodStringFormat.init(inst, def);
14001
14000
  });
14002
14001
  const $ZodIPv4 = /*@__PURE__*/ $constructor("$ZodIPv4", (inst, def)=>{
@@ -15794,7 +15793,7 @@ var __webpack_exports__ = {};
15794
15793
  inst.extend = (incoming)=>extend(inst, incoming);
15795
15794
  inst.safeExtend = (incoming)=>safeExtend(inst, incoming);
15796
15795
  inst.merge = (other)=>dist_merge(inst, other);
15797
- inst.pick = (mask)=>pick(inst, mask);
15796
+ inst.pick = (mask)=>dist_pick(inst, mask);
15798
15797
  inst.omit = (mask)=>omit(inst, mask);
15799
15798
  inst.partial = (...args)=>dist_partial(ZodOptional, inst, args[0]);
15800
15799
  inst.required = (...args)=>required(ZodNonOptional, inst, args[0]);
@@ -27041,6 +27040,130 @@ var __webpack_exports__ = {};
27041
27040
  axios.HttpStatusCode = helpers_HttpStatusCode;
27042
27041
  axios.default = axios;
27043
27042
  const lib_axios = axios;
27043
+ const USER_MESSAGE = {
27044
+ PROXY_UNAVAILABLE: "代理暂时不可用,请稍后重试或使用本地IP",
27045
+ NETWORK_ERROR: "网络异常,请稍后重试",
27046
+ SYSTEM_ERROR: "系统异常,请稍后重试或联系客服",
27047
+ PUBLISH_NETWORK: "发布失败,网络不稳定,请稍后重试",
27048
+ DOUYIN_ACCOUNT_FETCH_FAILED: "抖音数据获取失败,请稍后重试",
27049
+ SHIPINHAO_ACCOUNT_FETCH_FAILED: "视频号数据获取失败,请稍后重试",
27050
+ DOUYIN_POST_FETCH_FAILED: "抖音作品数据获取失败,请稍后重试",
27051
+ SHIPINHAO_POST_FETCH_FAILED: "视频号作品数据获取失败,请稍后重试",
27052
+ BJH_POST_FETCH_FAILED: "百家号作品数据获取失败,请稍后重试",
27053
+ TT_POST_FETCH_FAILED: "头条号作品数据获取失败,请稍后重试",
27054
+ QRCODE_FETCH_FAILED: "认证二维码获取失败,请稍后重试",
27055
+ IMAGE_UPLOAD_FAILED: "图片上传失败,请稍后重试或联系客服"
27056
+ };
27057
+ const NETWORK_CODES = [
27058
+ 500,
27059
+ 502,
27060
+ 503,
27061
+ 504
27062
+ ];
27063
+ function classifyPublishError(handledError) {
27064
+ const { code } = handledError;
27065
+ const isProxyRequest = handledError.extra?.isProxyRequest === true;
27066
+ if (!NETWORK_CODES.includes(code) && 599 !== code) return null;
27067
+ const category = 599 === code || isProxyRequest ? "代理错误" : "网络错误";
27068
+ return {
27069
+ category,
27070
+ userMessage: USER_MESSAGE.PUBLISH_NETWORK
27071
+ };
27072
+ }
27073
+ const RPA_ERROR_WEBHOOK_URL = "https://open.xfchat.iflytek.com/open-apis/bot/v2/hook/d202c0dc-5af5-40bc-83ed-abc677caa4a5";
27074
+ const ALARM_THROTTLE_MS = 60000;
27075
+ const lastSentAt = new Map();
27076
+ const THROTTLE_MAP_MAX_KEYS = 500;
27077
+ const pruneThrottleMap = (now)=>{
27078
+ if (lastSentAt.size < THROTTLE_MAP_MAX_KEYS) return;
27079
+ for (const [key, at] of lastSentAt)if (now - at >= ALARM_THROTTLE_MS) lastSentAt.delete(key);
27080
+ };
27081
+ const postFeishuWebhook = (webhookUrl, payload)=>lib_axios.post(webhookUrl, payload, {
27082
+ headers: {
27083
+ "Content-Type": "application/json"
27084
+ },
27085
+ timeout: 10000
27086
+ });
27087
+ const buildFeishuPostMessage = (report)=>{
27088
+ const content = [
27089
+ [
27090
+ {
27091
+ tag: "text",
27092
+ text: `平台:${report.platform || "未知平台"}`
27093
+ }
27094
+ ],
27095
+ [
27096
+ {
27097
+ tag: "text",
27098
+ text: `错误信息:${report.msg || "未知错误信息"}`
27099
+ }
27100
+ ],
27101
+ [
27102
+ {
27103
+ tag: "text",
27104
+ text: `错误类型:${report.errorType || "未知错误类型"}`
27105
+ }
27106
+ ],
27107
+ [
27108
+ {
27109
+ tag: "text",
27110
+ text: `阶段:${report.stage || "未知阶段"}`
27111
+ }
27112
+ ],
27113
+ [
27114
+ {
27115
+ tag: "text",
27116
+ text: `等级:${report.level}`
27117
+ }
27118
+ ],
27119
+ [
27120
+ {
27121
+ tag: "text",
27122
+ text: `来源:${report.source}`
27123
+ }
27124
+ ]
27125
+ ];
27126
+ if (void 0 !== report.code && null !== report.code) content.push([
27127
+ {
27128
+ tag: "text",
27129
+ text: `接口错误码:${report.code}`
27130
+ }
27131
+ ]);
27132
+ if (report.url) content.push([
27133
+ {
27134
+ tag: "text",
27135
+ text: `地址:${report.url}`
27136
+ }
27137
+ ]);
27138
+ if ("alarm" === report.level) content.push([
27139
+ {
27140
+ tag: "at",
27141
+ user_id: "all"
27142
+ }
27143
+ ]);
27144
+ return {
27145
+ msg_type: "post",
27146
+ content: {
27147
+ post: {
27148
+ zh_cn: {
27149
+ title: report.title || "RPA异常",
27150
+ content
27151
+ }
27152
+ }
27153
+ }
27154
+ };
27155
+ };
27156
+ const reportFeishuAlarm = (report)=>{
27157
+ try {
27158
+ const key = `${report.platform}|${report.source}|${report.stage}|${report.errorType}|${report.code ?? ""}`;
27159
+ const now = Date.now();
27160
+ const last = lastSentAt.get(key);
27161
+ if (last && now - last < ALARM_THROTTLE_MS) return;
27162
+ pruneThrottleMap(now);
27163
+ lastSentAt.set(key, now);
27164
+ postFeishuWebhook(RPA_ERROR_WEBHOOK_URL, buildFeishuPostMessage(report)).catch(()=>{});
27165
+ } catch {}
27166
+ };
27044
27167
  var dist = __webpack_require__("../../node_modules/.pnpm/socks-proxy-agent@8.0.4/node_modules/socks-proxy-agent/dist/index.js");
27045
27168
  const PROXY_CREDENTIALS = [
27046
27169
  {
@@ -27143,9 +27266,20 @@ var __webpack_exports__ = {};
27143
27266
  url: "https://fetdev.iflysec.com/ip-pool/pool/eip/proxy",
27144
27267
  data: params
27145
27268
  }).catch((err)=>{
27269
+ reportFeishuAlarm({
27270
+ level: "alarm",
27271
+ platform: "ip-pool",
27272
+ source: "proxy",
27273
+ stage: "POST /ip-pool/pool/eip/proxy",
27274
+ errorType: "PROXY_REQUEST_FAILED",
27275
+ code: err?.code,
27276
+ msg: `请求代理失败:${err.message},区域:${addr ?? "-"},AccountId:${accountId ?? "-"}`,
27277
+ url: "https://fetdev.iflysec.com/ip-pool/pool/eip/proxy",
27278
+ title: "代理异常"
27279
+ });
27146
27280
  throw {
27147
27281
  code: 414,
27148
- message: `请求代理失败:${err.message}`,
27282
+ message: USER_MESSAGE.PROXY_UNAVAILABLE,
27149
27283
  data: {}
27150
27284
  };
27151
27285
  });
@@ -27165,12 +27299,53 @@ var __webpack_exports__ = {};
27165
27299
  } : null;
27166
27300
  return proxyAgent;
27167
27301
  }
27302
+ const ALARM_STATUS = new Set([
27303
+ 401,
27304
+ 403,
27305
+ 429,
27306
+ 461,
27307
+ 471
27308
+ ]);
27309
+ const HTTP_STATUS_MESSAGE = {
27310
+ 400: "请求参数错误,请检查参数格式是否正确!",
27311
+ 401: "登录状态已失效,请重新登录后重试!",
27312
+ 403: "没有访问权限,账号可能受限或签名已失效!",
27313
+ 404: "请求的资源不存在,请检查接口地址!",
27314
+ 405: "请求方法不被允许,请检查接口调用方式!",
27315
+ 406: "服务端无法返回可接受的内容格式!",
27316
+ 407: "代理需要身份验证,请检查代理配置!",
27317
+ 408: "请求超时,请检查网络连接!",
27318
+ 409: "请求冲突,资源状态已变更,请刷新后重试!",
27319
+ 410: "请求的资源已被移除!",
27320
+ 412: "请求前置条件不满足,请刷新后重试!",
27321
+ 413: "提交内容过大,请压缩或分批后重试!",
27322
+ 414: "请求地址过长,请检查参数!",
27323
+ 415: "不支持的内容类型,请检查请求格式!",
27324
+ 422: "请求内容校验失败,请检查参数内容!",
27325
+ 423: "资源已被锁定,请稍后重试!",
27326
+ 429: "请求过于频繁,请稍后重试!",
27327
+ 431: "请求头过大,请清理 Cookie 后重试!",
27328
+ 451: "内容不合规或因法律原因被拒绝!",
27329
+ 461: "账号可能受限,请在网页上完成验证后重试!",
27330
+ 471: "账号可能受限,请在网页上完成验证后重试!",
27331
+ 500: "服务器内部错误,请稍后重试!",
27332
+ 501: "服务端不支持该请求,请稍后重试!",
27333
+ 502: "网关错误,请稍后重试!",
27334
+ 503: "服务暂时不可用,请稍后重试!",
27335
+ 504: "网关超时,请稍后重试!",
27336
+ 507: "服务端存储空间不足,请稍后重试!",
27337
+ 509: "服务带宽超限,请稍后重试!",
27338
+ 520: "服务端返回未知错误,请稍后重试!",
27339
+ 521: "源站拒绝连接,请稍后重试!",
27340
+ 522: "源站连接超时,请稍后重试!",
27341
+ 524: "源站响应超时,请稍后重试!"
27342
+ };
27168
27343
  class Http {
27169
27344
  static handleApiError(error) {
27170
27345
  if (error && "object" == typeof error && "code" in error && "message" in error) return error;
27171
27346
  return {
27172
27347
  code: 500,
27173
- message: error instanceof Error ? error.message : "未知错误",
27348
+ message: USER_MESSAGE.SYSTEM_ERROR,
27174
27349
  data: error
27175
27350
  };
27176
27351
  }
@@ -27225,6 +27400,18 @@ var __webpack_exports__ = {};
27225
27400
  const verifyDecision = error.response?.headers?.["x-tt-verify-passport-decision"];
27226
27401
  if (verifyDecision) this.logger?.warn(`[403 验证决策] x-tt-verify-passport-decision: ${verifyDecision}`);
27227
27402
  }
27403
+ if (error.response?.status === 461 || error.response?.status === 471) {
27404
+ const h = error.response?.headers ?? {};
27405
+ const pick = (name)=>h[name] ?? h[name.toLowerCase()];
27406
+ this.logger?.warn(`[${error.response.status} 风控验证] URL: ${error.config?.url} Verifytype: ${pick("Verifytype") ?? "-"} Verifyuuid: ${pick("Verifyuuid") ?? "-"} Verifybiz: ${pick("Verifybiz") ?? "-"}`);
27407
+ this.logger?.warn(`[${error.response.status} 响应头] ${JSON.stringify(h)}`);
27408
+ errorResponse.extra = {
27409
+ ...errorResponse.extra,
27410
+ verifyType: pick("Verifytype"),
27411
+ verifyUuid: pick("Verifyuuid"),
27412
+ verifyBiz: pick("Verifybiz")
27413
+ };
27414
+ }
27228
27415
  if (error.response?.data) {
27229
27416
  if ("object" == typeof error.response.data) {
27230
27417
  const serverError = error.response.data;
@@ -27255,11 +27442,17 @@ var __webpack_exports__ = {};
27255
27442
  _message = "DNS 查询超时,请稍后重试!";
27256
27443
  break;
27257
27444
  case "ERR_BAD_REQUEST":
27258
- _message = "请求出现错误,请检查请求参数!";
27259
- break;
27445
+ {
27446
+ const status = error.response?.status;
27447
+ _message = status && HTTP_STATUS_MESSAGE[status] || `请求失败,状态码${status ?? "unknown"}!`;
27448
+ break;
27449
+ }
27260
27450
  case "ERR_BAD_RESPONSE":
27261
- _message = `服务器响应异常 (${error.response?.status ?? "unknown"}),请稍后重试!`;
27262
- break;
27451
+ {
27452
+ const status = error.response?.status;
27453
+ _message = status && HTTP_STATUS_MESSAGE[status] || `服务器响应异常 (${status ?? "unknown"}),请稍后重试!`;
27454
+ break;
27455
+ }
27263
27456
  case "ERR_CANCELED":
27264
27457
  errorResponse.code = 414;
27265
27458
  _message = "请求连接超时,请稍候重试!";
@@ -27270,11 +27463,14 @@ var __webpack_exports__ = {};
27270
27463
  }
27271
27464
  break;
27272
27465
  default:
27273
- this.logger?.debug(`未处理的网络错误代码: ${error.code} ${error.message}`, {
27274
- errorString: stringifyError(error)
27275
- });
27276
- _message = `网络错误: ${error.message}`;
27277
- break;
27466
+ {
27467
+ this.logger?.debug(`未处理的网络错误代码: ${error.code} ${error.message}`, {
27468
+ errorString: stringifyError(error)
27469
+ });
27470
+ const status = error.response?.status;
27471
+ _message = status && HTTP_STATUS_MESSAGE[status] || USER_MESSAGE.NETWORK_ERROR;
27472
+ break;
27473
+ }
27278
27474
  }
27279
27475
  }
27280
27476
  if (error.code && !error.response?.data) errorResponse.message = _message || errorResponse.message;
@@ -27284,29 +27480,62 @@ var __webpack_exports__ = {};
27284
27480
  errorResponse.message = message;
27285
27481
  }
27286
27482
  if (error.message.includes("Proxy connection ended")) errorResponse.message = "所在区域代理连接超时,请更换区域或稍后重试!";
27483
+ errorResponse.extra = {
27484
+ ...errorResponse.extra,
27485
+ alarmStatus: error.response?.status,
27486
+ alarmErrorCode: error.code
27487
+ };
27287
27488
  throw errorResponse;
27288
27489
  });
27289
27490
  }
27491
+ reportRequestFailure(config, error, attempts) {
27492
+ const status = error.extra?.alarmStatus;
27493
+ const axiosCode = error.extra?.alarmErrorCode;
27494
+ const method = (config.method || "get").toUpperCase();
27495
+ const url = config.url || "-";
27496
+ const retriedSuffix = attempts > 0 ? `(已重试${attempts}次仍失败)` : "";
27497
+ reportFeishuAlarm({
27498
+ level: status && ALARM_STATUS.has(status) ? "alarm" : "warning",
27499
+ platform: this.platform || "unknown",
27500
+ source: "http",
27501
+ stage: `${method} ${url}`,
27502
+ errorType: status ? `HTTP_${status}` : axiosCode || "NETWORK_ERROR",
27503
+ code: error.code,
27504
+ msg: `${error.message}${retriedSuffix}`,
27505
+ url: config.url,
27506
+ title: "RPA接口异常"
27507
+ });
27508
+ }
27290
27509
  async api(config, options) {
27291
27510
  const retries = options?.retries ?? 0;
27292
27511
  const retryDelay = options?.retryDelay ?? 500;
27293
- const reqTimeout = options?.timeout ?? 30000;
27512
+ const reqTimeout = options?.timeout ?? 60000;
27513
+ const externalSignal = options?.signal;
27294
27514
  let agent;
27295
27515
  const sessionRt = async (Rtimes)=>{
27296
27516
  try {
27297
27517
  this.proxyInfo = agent ? `${agent.ip}:${agent.port}` : void 0;
27298
27518
  const controller = new AbortController();
27299
27519
  const timeoutId = setTimeout(()=>controller.abort(), reqTimeout + 500);
27520
+ const forwardAbort = ()=>controller.abort();
27521
+ if (externalSignal) {
27522
+ if (externalSignal.aborted) controller.abort();
27523
+ else externalSignal.addEventListener("abort", forwardAbort, {
27524
+ once: true
27525
+ });
27526
+ }
27300
27527
  const response = await this.apiClient({
27301
27528
  ...config,
27302
27529
  timeout: reqTimeout,
27303
27530
  signal: controller.signal,
27531
+ onUploadProgress: options?.onUploadProgress,
27304
27532
  ...agent ? {
27305
27533
  httpAgent: agent.agent,
27306
27534
  httpsAgent: agent.agent
27307
27535
  } : {}
27308
27536
  }).finally(()=>{
27309
27537
  clearTimeout(timeoutId);
27538
+ externalSignal?.removeEventListener("abort", forwardAbort);
27310
27539
  });
27311
27540
  return response.data;
27312
27541
  } catch (error) {
@@ -27321,10 +27550,12 @@ var __webpack_exports__ = {};
27321
27550
  ].includes(handledError.code);
27322
27551
  if (Rtimes < retries && isRetry) {
27323
27552
  const url = config.url || "";
27324
- this.logger?.warn(`进入第${Rtimes + 1}次重试!错误码: ${handledError.code}, 请求地址: ${url}`);
27325
- await new Promise((resolve)=>setTimeout(resolve, retryDelay));
27553
+ const backoff = Math.min(retryDelay * 2 ** Rtimes, 5000);
27554
+ this.logger?.warn(`进入第${Rtimes + 1}次重试!错误码: ${handledError.code}, 等待: ${backoff}ms, 请求地址: ${url}`);
27555
+ await new Promise((resolve)=>setTimeout(resolve, backoff));
27326
27556
  return sessionRt(Rtimes + 1);
27327
27557
  }
27558
+ this.reportRequestFailure(config, handledError, Rtimes);
27328
27559
  return Promise.reject(handledError);
27329
27560
  }
27330
27561
  };
@@ -32015,6 +32246,14 @@ var __webpack_exports__ = {};
32015
32246
  };
32016
32247
  return new schemas_ZodObject(def);
32017
32248
  }
32249
+ function looseObject(shape, params) {
32250
+ return new schemas_ZodObject({
32251
+ type: "object",
32252
+ shape,
32253
+ catchall: schemas_unknown(),
32254
+ ...util_normalizeParams(params)
32255
+ });
32256
+ }
32018
32257
  const schemas_ZodUnion = /*@__PURE__*/ core_$constructor("ZodUnion", (inst, def)=>{
32019
32258
  schemas_$ZodUnion.init(inst, def);
32020
32259
  schemas_ZodType.init(inst, def);
@@ -32711,6 +32950,13 @@ var __webpack_exports__ = {};
32711
32950
  data: ""
32712
32951
  };
32713
32952
  const image = await downloadImage(url, external_node_path_default().join(tmpCachePath, fileName));
32953
+ const stats = external_node_fs_default().statSync(image);
32954
+ const maxSize = 5242880;
32955
+ if (stats.size > maxSize) throw {
32956
+ code: 414,
32957
+ message: "百家号平台:单张图片不得超过 5MB",
32958
+ data: ""
32959
+ };
32714
32960
  const formData = new (form_data_default())();
32715
32961
  formData.append("org_file_name", fileName);
32716
32962
  formData.append("type", "image");
@@ -33381,7 +33627,8 @@ var __webpack_exports__ = {};
33381
33627
  },
33382
33628
  _task.logger,
33383
33629
  params.proxyLoc,
33384
- params.accountId
33630
+ params.accountId,
33631
+ "xiaohongshu"
33385
33632
  ];
33386
33633
  const http = new Http(...args);
33387
33634
  const fans = {
@@ -33395,8 +33642,8 @@ var __webpack_exports__ = {};
33395
33642
  url: "https://creator.xiaohongshu.com/api/galaxy/creator/home/personal_info"
33396
33643
  }, {
33397
33644
  retries: 3,
33398
- retryDelay: 20,
33399
- timeout: 3000
33645
+ retryDelay: 300,
33646
+ timeout: 30000
33400
33647
  });
33401
33648
  fans.fans_count = Number(res.data.fans_count);
33402
33649
  fans.digg_count = Number(res.data.faved_count);
@@ -34533,7 +34780,8 @@ var __webpack_exports__ = {};
34533
34780
  },
34534
34781
  _task.logger,
34535
34782
  params.proxyLoc,
34536
- params.accountId
34783
+ params.accountId,
34784
+ "xiaohongshu"
34537
34785
  ];
34538
34786
  const http = new Http(...args);
34539
34787
  http.addResponseInterceptor((response)=>{
@@ -34581,8 +34829,8 @@ var __webpack_exports__ = {};
34581
34829
  headers: loginBaseXsHeader
34582
34830
  }, {
34583
34831
  retries: 3,
34584
- retryDelay: 20,
34585
- timeout: 5000
34832
+ retryDelay: 300,
34833
+ timeout: 30000
34586
34834
  }).catch((e)=>{
34587
34835
  const clientTimestamp = Date.now();
34588
34836
  const serverDate = e?.extra?.serverDate;
@@ -34614,8 +34862,8 @@ var __webpack_exports__ = {};
34614
34862
  headers: webSessionXsHeader
34615
34863
  }, {
34616
34864
  retries: 3,
34617
- retryDelay: 20,
34618
- timeout: 5000
34865
+ retryDelay: 300,
34866
+ timeout: 30000
34619
34867
  });
34620
34868
  const [baseInfo, web_session] = await Promise.all([
34621
34869
  _baseInfo,
@@ -34707,6 +34955,10 @@ var __webpack_exports__ = {};
34707
34955
  };
34708
34956
  return success(data, message);
34709
34957
  };
34958
+ const extractEncFileKey = (downloadUrl)=>{
34959
+ if (!downloadUrl) return "";
34960
+ return downloadUrl.split("encfilekey=")[1]?.split("&")[0] || "";
34961
+ };
34710
34962
  const rid = ()=>`${Math.floor(Date.now() / 1e3).toString(16)}-${[
34711
34963
  ...Array(8)
34712
34964
  ].map(()=>Math.floor(16 * Math.random()).toString(16)).join("")}`;
@@ -36543,7 +36795,7 @@ var __webpack_exports__ = {};
36543
36795
  });
36544
36796
  const qrData = qrCodeResponse?.data;
36545
36797
  task.logger.info(`获取二维码响应: error_code=${qrData?.error_code}, message=${qrCodeResponse?.message}`);
36546
- if (qrData?.error_code !== 0) return utils_response(414, `获取二维码失败: error_code=${qrData?.error_code}`, "");
36798
+ if (qrData?.error_code !== 0) return utils_response(414, USER_MESSAGE.QRCODE_FETCH_FAILED, "");
36547
36799
  return utils_response(0, "获取二维码成功", {
36548
36800
  qrcode: qrData.qrcode,
36549
36801
  token: qrData.token,
@@ -36558,7 +36810,7 @@ var __webpack_exports__ = {};
36558
36810
  } catch (err) {
36559
36811
  const msg = err instanceof Error ? err.message : String(err);
36560
36812
  task.logger.warn(`[douyinGetVerifyQrCode] 获取二维码失败: ${msg}`);
36561
- return utils_response(500, `获取二维码失败: ${msg}`, "");
36813
+ return utils_response(500, USER_MESSAGE.QRCODE_FETCH_FAILED, "");
36562
36814
  }
36563
36815
  };
36564
36816
  const DouyinGetWorkListParamsSchema = ActionCommonParamsSchema.extend({
@@ -38332,6 +38584,11 @@ var __webpack_exports__ = {};
38332
38584
  }
38333
38585
  async getImageInfo(localPath) {
38334
38586
  const stats = external_node_fs_default().statSync(localPath);
38587
+ const maxSize = 52428800;
38588
+ if (stats.size > maxSize) {
38589
+ external_node_path_default().basename(localPath);
38590
+ throw new Error("抖音平台:单张图片不得超过 50MB");
38591
+ }
38335
38592
  let width = 1080;
38336
38593
  let height = 1920;
38337
38594
  try {
@@ -38812,18 +39069,10 @@ var __webpack_exports__ = {};
38812
39069
  });
38813
39070
  } catch (error) {
38814
39071
  const handledError = Http.handleApiError(error);
38815
- const isProxyOrNetworkError = [
38816
- 599,
38817
- 500,
38818
- 502,
38819
- 503,
38820
- 504
38821
- ].includes(handledError.code);
38822
- if (isProxyOrNetworkError) {
38823
- const isProxyRequest = handledError.extra?.isProxyRequest === true;
38824
- const errorType = 599 === handledError.code || isProxyRequest ? "代理错误" : "网络错误";
38825
- const message = `图文发布失败,${errorType}:${handledError.message}${task.debug ? ` ${http.proxyInfo}` : ""}`;
38826
- task.logger.error(`[douyinPublish] ${errorType},直接返回: ${message}`, stringifyError(handledError));
39072
+ const classified = classifyPublishError(handledError);
39073
+ if (classified) {
39074
+ const message = `${classified.userMessage}${task.debug ? ` ${http.proxyInfo}` : ""}`;
39075
+ task.logger.error(`[douyinPublish] ${classified.category},直接返回: ${handledError.message} (code=${handledError.code})`, stringifyError(handledError));
38827
39076
  await updateTaskState?.({
38828
39077
  state: types_TaskState.FAILED,
38829
39078
  error: message
@@ -40355,7 +40604,8 @@ var __webpack_exports__ = {};
40355
40604
  },
40356
40605
  _task.logger,
40357
40606
  params.proxyLoc,
40358
- params.accountId
40607
+ params.accountId,
40608
+ "xiaohongshu"
40359
40609
  ];
40360
40610
  const http = new Http(...args);
40361
40611
  let unreadCount = {
@@ -40384,8 +40634,8 @@ var __webpack_exports__ = {};
40384
40634
  headers: xsHeader
40385
40635
  }, {
40386
40636
  retries: 3,
40387
- retryDelay: 20,
40388
- timeout: 3000
40637
+ retryDelay: 300,
40638
+ timeout: 30000
40389
40639
  });
40390
40640
  const isSuccess = 0 === res.code;
40391
40641
  if (isSuccess) unreadCount = res.data;
@@ -40541,7 +40791,7 @@ var __webpack_exports__ = {};
40541
40791
  }
40542
40792
  const errMsg = error instanceof Error ? error.message : String(error);
40543
40793
  _task.logger.error(`抖音账号数据获取失败: ${errMsg}`);
40544
- return types_errorResponse(errMsg || "抖音账号数据获取失败");
40794
+ return types_errorResponse(USER_MESSAGE.DOUYIN_ACCOUNT_FETCH_FAILED);
40545
40795
  }
40546
40796
  }
40547
40797
  async function getShipinhaoData(_task, params) {
@@ -40672,7 +40922,7 @@ var __webpack_exports__ = {};
40672
40922
  }
40673
40923
  const errMsg = error instanceof Error ? error.message : String(error);
40674
40924
  _task.logger.error(`视频号账号数据获取失败: ${errMsg}`);
40675
- return types_errorResponse(errMsg || "视频号账号数据获取失败");
40925
+ return types_errorResponse(USER_MESSAGE.SHIPINHAO_ACCOUNT_FETCH_FAILED);
40676
40926
  }
40677
40927
  }
40678
40928
  async function getToutiaoData(_task, params) {
@@ -40798,7 +41048,8 @@ var __webpack_exports__ = {};
40798
41048
  },
40799
41049
  _task.logger,
40800
41050
  params.proxyLoc,
40801
- params.accountId
41051
+ params.accountId,
41052
+ "xiaohongshu"
40802
41053
  ];
40803
41054
  const http = new Http(...args);
40804
41055
  const xsEncrypt = new Xhshow();
@@ -40814,8 +41065,8 @@ var __webpack_exports__ = {};
40814
41065
  url: "https://creator.xiaohongshu.com/api/galaxy/creator/home/personal_info"
40815
41066
  }, {
40816
41067
  retries: 3,
40817
- retryDelay: 20,
40818
- timeout: 3000
41068
+ retryDelay: 300,
41069
+ timeout: 30000
40819
41070
  }),
40820
41071
  http.api({
40821
41072
  method: "get",
@@ -40824,8 +41075,8 @@ var __webpack_exports__ = {};
40824
41075
  headers: sevenDataXsHeader
40825
41076
  }, {
40826
41077
  retries: 3,
40827
- retryDelay: 20,
40828
- timeout: 3000
41078
+ retryDelay: 300,
41079
+ timeout: 30000
40829
41080
  })
40830
41081
  ]);
40831
41082
  const xhsData = {
@@ -41113,7 +41364,9 @@ var __webpack_exports__ = {};
41113
41364
  } : null
41114
41365
  }, "百家号文章数据获取成功");
41115
41366
  } catch (error) {
41116
- return searchPublishInfo_types_errorResponse(error instanceof Error ? error.message : "百家号文章数据获取失败");
41367
+ const errMsg = error instanceof Error ? error.message : String(error);
41368
+ _task.logger.error(`百家号文章数据获取失败: ${errMsg}`);
41369
+ return searchPublishInfo_types_errorResponse(USER_MESSAGE.BJH_POST_FETCH_FAILED);
41117
41370
  }
41118
41371
  }
41119
41372
  async function handleDouyinData(_task, params) {
@@ -41208,7 +41461,9 @@ var __webpack_exports__ = {};
41208
41461
  } : null
41209
41462
  }, "抖音数据获取成功");
41210
41463
  } catch (error) {
41211
- return searchPublishInfo_types_errorResponse(error instanceof Error ? error.message : "抖音数据获取失败");
41464
+ const errMsg = error instanceof Error ? error.message : String(error);
41465
+ _task.logger.error(`抖音作品数据获取失败: ${errMsg}`);
41466
+ return searchPublishInfo_types_errorResponse(USER_MESSAGE.DOUYIN_POST_FETCH_FAILED);
41212
41467
  }
41213
41468
  }
41214
41469
  async function handleShipinhaoData(_task, params) {
@@ -41373,8 +41628,9 @@ var __webpack_exports__ = {};
41373
41628
  }, "视频号数据获取成功");
41374
41629
  } catch (error) {
41375
41630
  const errMsg = error instanceof Error ? error.message : String(error);
41631
+ _task.logger.error(`视频号作品数据获取失败: ${errMsg}`);
41376
41632
  if (errMsg.startsWith("AUTH_ERROR:")) return searchPublishInfo_types_errorResponse("视频号数据获取失败,请检查账号状态", 414);
41377
- return searchPublishInfo_types_errorResponse(errMsg || "视频号数据获取失败");
41633
+ return searchPublishInfo_types_errorResponse(USER_MESSAGE.SHIPINHAO_POST_FETCH_FAILED);
41378
41634
  }
41379
41635
  }
41380
41636
  async function handleToutiaoData(_task, params) {
@@ -41459,7 +41715,9 @@ var __webpack_exports__ = {};
41459
41715
  } : null
41460
41716
  }, "头条号文章文章获取成功");
41461
41717
  } catch (error) {
41462
- return searchPublishInfo_types_errorResponse(error instanceof Error ? error.message : "头条号文章数据获取失败");
41718
+ const errMsg = error instanceof Error ? error.message : String(error);
41719
+ _task.logger.error(`头条号文章数据获取失败: ${errMsg}`);
41720
+ return searchPublishInfo_types_errorResponse(USER_MESSAGE.TT_POST_FETCH_FAILED);
41463
41721
  }
41464
41722
  }
41465
41723
  const external_node_vm_namespaceObject = require("node:vm");
@@ -43836,18 +44094,10 @@ var __webpack_exports__ = {};
43836
44094
  });
43837
44095
  } catch (error) {
43838
44096
  const handledError = Http.handleApiError(error);
43839
- const isProxyOrNetworkError = [
43840
- 599,
43841
- 500,
43842
- 502,
43843
- 503,
43844
- 504
43845
- ].includes(handledError.code);
43846
- if (isProxyOrNetworkError) {
43847
- const isProxyRequest = handledError.extra?.isProxyRequest === true;
43848
- const errorType = 599 === handledError.code || isProxyRequest ? "代理错误" : "网络错误";
43849
- const message = `图文发布失败,${errorType}:${handledError.message}${task.debug ? ` ${http.proxyInfo}` : ""}`;
43850
- task.logger.error(`[shipinhaoPublish] ${errorType},直接返回: ${message}`, stringifyError(handledError));
44097
+ const classified = classifyPublishError(handledError);
44098
+ if (classified) {
44099
+ const message = `${classified.userMessage}${task.debug ? ` ${http.proxyInfo}` : ""}`;
44100
+ task.logger.error(`[shipinhaoPublish] ${classified.category},直接返回: ${handledError.message} (code=${handledError.code})`, stringifyError(handledError));
43851
44101
  await updateTaskState?.({
43852
44102
  state: types_TaskState.FAILED,
43853
44103
  error: message
@@ -43865,7 +44115,7 @@ var __webpack_exports__ = {};
43865
44115
  const resultMsg = publishResult.data?.baseResp?.errmsg ?? publishResult.errMsg;
43866
44116
  if (0 === resultCode) {
43867
44117
  task.logger.info("[shipinhaoPublish] 发布成功");
43868
- const publishId = uploadedImages[0]?.thumbUrl?.split("encfilekey=")[1]?.split("&")[0] || "";
44118
+ const publishId = extractEncFileKey(uploadedImages[0]?.thumbUrl);
43869
44119
  await updateTaskState?.({
43870
44120
  state: types_TaskState.SUCCESS,
43871
44121
  result: {
@@ -44587,6 +44837,1594 @@ var __webpack_exports__ = {};
44587
44837
  if ("server" === params.actionType) return rpa_server_rpaAction_Server(task, params);
44588
44838
  return executeAction(shipinhaoPublish_mock_mockAction, rpa_server_rpaAction_Server)(task, params);
44589
44839
  };
44840
+ function auth_getTimeStamp(length) {
44841
+ return Date.now().toString().substring(0, length);
44842
+ }
44843
+ async function auth_getUserInfo(cookies, http) {
44844
+ return http.api({
44845
+ method: "post",
44846
+ url: "https://channels.weixin.qq.com/cgi-bin/mmfinderassistant-bin/auth/auth_data",
44847
+ data: {
44848
+ timestamp: auth_getTimeStamp(13),
44849
+ _log_finder_uin: "",
44850
+ _log_finder_id: "",
44851
+ rawKeyBuff: null,
44852
+ pluginSessionId: null,
44853
+ scene: 7,
44854
+ reqScene: 7
44855
+ },
44856
+ headers: {
44857
+ cookie: cookies,
44858
+ referer: "https://channels.weixin.qq.com",
44859
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
44860
+ },
44861
+ defaultErrorMsg: "获取用户信息失败"
44862
+ });
44863
+ }
44864
+ async function auth_getUploadAuthKey(cookies, finderUsername, http) {
44865
+ return http.api({
44866
+ method: "post",
44867
+ url: "https://channels.weixin.qq.com/cgi-bin/mmfinderassistant-bin/helper/helper_upload_params",
44868
+ data: {
44869
+ timestamp: auth_getTimeStamp(13),
44870
+ _log_finder_id: finderUsername,
44871
+ rawKeyBuff: null
44872
+ },
44873
+ headers: {
44874
+ cookie: cookies,
44875
+ referer: "https://channels.weixin.qq.com",
44876
+ Accept: "application/json, text/plain, */*",
44877
+ "Content-Type": "application/json",
44878
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
44879
+ },
44880
+ defaultErrorMsg: "获取上传认证密钥失败"
44881
+ });
44882
+ }
44883
+ class ShipinhaoAuthError extends Error {
44884
+ constructor(message, errCode){
44885
+ super(message), this.errCode = errCode;
44886
+ this.name = "ShipinhaoAuthError";
44887
+ }
44888
+ }
44889
+ async function getShipinhaoUploadAuth(cookies, http) {
44890
+ const userInfo = await auth_getUserInfo(cookies, http);
44891
+ if (0 !== userInfo.errCode || !userInfo.data?.finderUser) {
44892
+ const isLoginExpired = 300333 === userInfo.errCode || 300334 === userInfo.errCode;
44893
+ throw new ShipinhaoAuthError(isLoginExpired ? "登录失效" : userInfo.errMsg || "获取用户信息失败", userInfo.errCode || 500);
44894
+ }
44895
+ const finderUsername = userInfo.data.finderUser.finderUsername;
44896
+ const authKeyResponse = await auth_getUploadAuthKey(cookies, finderUsername, http);
44897
+ if (0 !== authKeyResponse.errCode || !authKeyResponse.data?.authKey) throw new ShipinhaoAuthError(`获取上传认证参数失败: ${authKeyResponse.errMsg}`, authKeyResponse.errCode || 500);
44898
+ const uin = authKeyResponse.data.uin;
44899
+ if (!uin) throw new ShipinhaoAuthError("获取用户 uin 失败", 500);
44900
+ const videoFileType = authKeyResponse.data.videoFileType || 20302;
44901
+ const pictureFileType = authKeyResponse.data.pictureFileType || 20304;
44902
+ return {
44903
+ uin,
44904
+ authKey: authKeyResponse.data.authKey,
44905
+ finderUsername,
44906
+ videoFileType,
44907
+ pictureFileType
44908
+ };
44909
+ }
44910
+ const MENTION_TEXT_SUFFIX = "\u0020";
44911
+ const MENTION_XML_SUFFIX = "\u2005";
44912
+ function payload_buildDescription(params) {
44913
+ let description = params.description || "";
44914
+ for (const topic of params.topics || [])description += `#${topic}`;
44915
+ for (const user of params.mentionedUsers || [])description += `@${user.nickname}${MENTION_TEXT_SUFFIX}`;
44916
+ return description;
44917
+ }
44918
+ function buildMentionedUser(mentionedUsers) {
44919
+ return (mentionedUsers || []).map((user)=>({
44920
+ nickname: `${user.nickname}${MENTION_TEXT_SUFFIX}`
44921
+ }));
44922
+ }
44923
+ function payload_buildTopicXml(params) {
44924
+ const values = [];
44925
+ let atIndex = null;
44926
+ if (params.description) values.push(`<![CDATA[${params.description}]]>`);
44927
+ for (const topic of params.topics || [])values.push(`<topic><![CDATA[#${topic}#]]></topic>`);
44928
+ for (const user of params.mentionedUsers || []){
44929
+ if (null === atIndex) atIndex = values.length;
44930
+ values.push(`<![CDATA[@${user.nickname}${MENTION_XML_SUFFIX}]]>`);
44931
+ }
44932
+ let xml = "<finder>";
44933
+ xml += "<version>1</version>";
44934
+ xml += `<valuecount>${values.length}</valuecount>`;
44935
+ xml += `<style><at>${atIndex ?? ""}</at></style>`;
44936
+ values.forEach((value, index)=>{
44937
+ xml += `<value${index}>${value}</value${index}>`;
44938
+ });
44939
+ xml += "</finder>";
44940
+ return xml;
44941
+ }
44942
+ function payload_buildLocation(location) {
44943
+ if (!location) return {
44944
+ latitude: 0,
44945
+ longitude: 0,
44946
+ city: "",
44947
+ poiName: "",
44948
+ address: "",
44949
+ poiClassifyId: ""
44950
+ };
44951
+ return {
44952
+ latitude: location.latitude,
44953
+ longitude: location.longitude,
44954
+ city: location.city,
44955
+ poiName: location.poiName || "",
44956
+ address: location.address || "",
44957
+ poiClassifyId: location.poiClassifyId || ""
44958
+ };
44959
+ }
44960
+ function buildTopic(params) {
44961
+ const topic = {
44962
+ finderTopicInfo: payload_buildTopicXml(params)
44963
+ };
44964
+ if (params.collection) {
44965
+ topic.collectionId = params.collection.collectionId;
44966
+ topic.collectionName = params.collection.collectionName;
44967
+ }
44968
+ return topic;
44969
+ }
44970
+ function buildEvent(event) {
44971
+ if (!event) return {};
44972
+ return {
44973
+ eventTopicId: event.eventTopicId,
44974
+ eventName: event.eventName,
44975
+ eventCreatorNickname: event.eventCreatorNickname || ""
44976
+ };
44977
+ }
44978
+ function buildExtReading(link) {
44979
+ if (!link) return {
44980
+ link: "",
44981
+ title: "",
44982
+ urlType: 1
44983
+ };
44984
+ return {
44985
+ link: link.link.replace(/[\s\u200b]/g, ""),
44986
+ title: link.title,
44987
+ urlType: link.urlType ?? 1
44988
+ };
44989
+ }
44990
+ function buildTagInfo(tagInfo, tagKey) {
44991
+ return {
44992
+ ...tagInfo,
44993
+ tagKey
44994
+ };
44995
+ }
44996
+ const CHUNK_SIZE = 8388608;
44997
+ const UPLOAD_STAGE_TIMEOUT = 180000;
44998
+ const DEFAULT_TUNING = {
44999
+ metaTimeout: UPLOAD_STAGE_TIMEOUT,
45000
+ partTimeout: UPLOAD_STAGE_TIMEOUT,
45001
+ partRetries: 3,
45002
+ completeTimeout: UPLOAD_STAGE_TIMEOUT
45003
+ };
45004
+ async function uploader_uploadFile(opts) {
45005
+ const { filePath, fileType, uin, authKey, http, logger, tuning } = opts;
45006
+ const stat = external_node_fs_default().statSync(filePath);
45007
+ const fileSize = stat.size;
45008
+ const fileName = filePath.split(/[\\/]/).pop() || "file";
45009
+ const metaTimeout = tuning?.metaTimeout ?? DEFAULT_TUNING.metaTimeout;
45010
+ const partTimeout = tuning?.partTimeout ?? DEFAULT_TUNING.partTimeout;
45011
+ const partRetries = tuning?.partRetries ?? DEFAULT_TUNING.partRetries;
45012
+ const completeTimeout = tuning?.completeTimeout ?? DEFAULT_TUNING.completeTimeout;
45013
+ logger?.info(`[shipinhaoPublishVideo] 开始上传: ${fileName} (${fileSize} B, filetype=${fileType})`);
45014
+ const fileMd5 = await computeFileMd5(filePath);
45015
+ const taskId = generateTaskId(fileName, fileSize, fileMd5);
45016
+ const baseUrl = "https://finderassistancea.video.qq.com";
45017
+ const headers = {
45018
+ Authorization: authKey
45019
+ };
45020
+ const xArgs = `apptype=251&filetype=${fileType}&weixinnum=${uin}&filekey=${encodeURIComponent(fileName)}&filesize=${fileSize}&taskid=${taskId}&scene=2`;
45021
+ const chunkCount = Math.ceil(fileSize / CHUNK_SIZE);
45022
+ const blockPartLength = [];
45023
+ for(let i = 0; i < chunkCount; i++)blockPartLength.push(Math.min((i + 1) * CHUNK_SIZE, fileSize));
45024
+ logger?.info(`[shipinhaoPublishVideo] 视频分片: ${chunkCount} 片`);
45025
+ const applyRes = await http.api({
45026
+ method: "PUT",
45027
+ url: `${baseUrl}/applyuploaddfs`,
45028
+ headers: {
45029
+ ...headers,
45030
+ "X-Arguments": xArgs
45031
+ },
45032
+ data: {
45033
+ BlockSum: chunkCount,
45034
+ BlockPartLength: blockPartLength
45035
+ }
45036
+ }, {
45037
+ timeout: metaTimeout,
45038
+ retries: 2,
45039
+ retryDelay: 2000
45040
+ });
45041
+ if (!applyRes.UploadID && !applyRes.ListPartsResult) throw new Error("申请 UploadID 失败: " + JSON.stringify(applyRes));
45042
+ let uploadId = applyRes.UploadID;
45043
+ const uploadedParts = new Set();
45044
+ if (applyRes.ListPartsResult) {
45045
+ const parts = Array.isArray(applyRes.ListPartsResult.Part) ? applyRes.ListPartsResult.Part : applyRes.ListPartsResult.Part ? [
45046
+ applyRes.ListPartsResult.Part
45047
+ ] : [];
45048
+ for (const p of parts)uploadedParts.add(p.PartNumber);
45049
+ const retryRes = await http.api({
45050
+ method: "PUT",
45051
+ url: `${baseUrl}/applyuploaddfs`,
45052
+ headers: {
45053
+ ...headers,
45054
+ "X-Arguments": xArgs
45055
+ },
45056
+ data: {
45057
+ BlockSum: chunkCount,
45058
+ BlockPartLength: blockPartLength
45059
+ }
45060
+ }, {
45061
+ timeout: metaTimeout,
45062
+ retries: 2,
45063
+ retryDelay: 2000
45064
+ });
45065
+ uploadId = retryRes.UploadID;
45066
+ if (!uploadId) throw new Error("续传获取 UploadID 失败");
45067
+ }
45068
+ const partInfo = [];
45069
+ const fd = external_node_fs_default().openSync(filePath, "r");
45070
+ try {
45071
+ for(let i = 0; i < chunkCount; i++){
45072
+ const partNumber = i + 1;
45073
+ if (uploadedParts.has(partNumber)) {
45074
+ const existing = applyRes.ListPartsResult.Part.find((p)=>p.PartNumber === partNumber);
45075
+ if (existing) {
45076
+ partInfo.push({
45077
+ PartNumber: partNumber,
45078
+ ETag: existing.ETag
45079
+ });
45080
+ continue;
45081
+ }
45082
+ }
45083
+ const start = i * CHUNK_SIZE;
45084
+ const end = Math.min(start + CHUNK_SIZE, fileSize);
45085
+ const chunkSize = end - start;
45086
+ const chunk = Buffer.alloc(chunkSize);
45087
+ external_node_fs_default().readSync(fd, chunk, 0, chunkSize, start);
45088
+ const chunkMd5 = external_node_crypto_default().createHash("md5").update(chunk).digest("hex");
45089
+ const partStart = Date.now();
45090
+ await http.api({
45091
+ method: "PUT",
45092
+ url: `${baseUrl}/uploadpartdfs?PartNumber=${partNumber}&UploadID=${encodeURIComponent(uploadId)}`,
45093
+ headers: {
45094
+ ...headers,
45095
+ "X-Arguments": xArgs.replace(/scene=2/, "scene=0"),
45096
+ "Content-MD5": chunkMd5
45097
+ },
45098
+ data: chunk
45099
+ }, {
45100
+ timeout: partTimeout,
45101
+ retries: partRetries,
45102
+ retryDelay: 2000
45103
+ });
45104
+ Date.now();
45105
+ partInfo.push({
45106
+ PartNumber: partNumber,
45107
+ ETag: `"${chunkMd5}"`
45108
+ });
45109
+ }
45110
+ } finally{
45111
+ external_node_fs_default().closeSync(fd);
45112
+ }
45113
+ const completeRes = await http.api({
45114
+ method: "POST",
45115
+ url: `${baseUrl}/completepartuploaddfs?UploadID=${encodeURIComponent(uploadId)}`,
45116
+ headers: {
45117
+ ...headers,
45118
+ "X-Arguments": xArgs
45119
+ },
45120
+ data: {
45121
+ TransFlag: "0_0",
45122
+ PartInfo: partInfo
45123
+ }
45124
+ }, {
45125
+ timeout: completeTimeout,
45126
+ retries: 1,
45127
+ retryDelay: 3000
45128
+ });
45129
+ if (!completeRes.DownloadURL) throw new Error("合并分片失败: " + JSON.stringify(completeRes));
45130
+ logger?.info(`[shipinhaoPublishVideo] ${fileName} 上传成功`);
45131
+ return {
45132
+ downloadUrl: completeRes.DownloadURL,
45133
+ md5: fileMd5,
45134
+ fileSize
45135
+ };
45136
+ }
45137
+ async function computeFileMd5(filePath) {
45138
+ return new Promise((resolve, reject)=>{
45139
+ const hash = external_node_crypto_default().createHash("md5");
45140
+ const stream = external_node_fs_default().createReadStream(filePath);
45141
+ stream.on("data", (chunk)=>hash.update(chunk));
45142
+ stream.on("end", ()=>resolve(hash.digest("hex")));
45143
+ stream.on("error", reject);
45144
+ });
45145
+ }
45146
+ function generateTaskId(fileName, fileSize, fileMd5) {
45147
+ const input = `${fileName}-${fileSize}-${fileMd5}`;
45148
+ return external_node_crypto_default().createHash("md5").update(input).digest("hex").slice(0, 32);
45149
+ }
45150
+ const MAX_METADATA_BOX_SIZE = 268435456;
45151
+ function readBoxHeader(fd, offset, limit) {
45152
+ if (offset + 8 > limit) return null;
45153
+ const head = Buffer.alloc(16);
45154
+ const read = external_node_fs_default().readSync(fd, head, 0, 16, offset);
45155
+ if (read < 8) return null;
45156
+ let size = head.readUInt32BE(0);
45157
+ const type = head.toString("latin1", 4, 8);
45158
+ let headerSize = 8;
45159
+ if (1 === size) {
45160
+ if (read < 16) return null;
45161
+ size = head.readUInt32BE(8) * 2 ** 32 + head.readUInt32BE(12);
45162
+ headerSize = 16;
45163
+ } else if (0 === size) size = limit - offset;
45164
+ if (size < headerSize || offset + size > limit) return null;
45165
+ return {
45166
+ type,
45167
+ size,
45168
+ headerSize
45169
+ };
45170
+ }
45171
+ function parseVideoMeta(filePath) {
45172
+ let fd;
45173
+ let fileSize;
45174
+ try {
45175
+ fd = external_node_fs_default().openSync(filePath, "r");
45176
+ } catch {
45177
+ return null;
45178
+ }
45179
+ try {
45180
+ fileSize = external_node_fs_default().fstatSync(fd).size;
45181
+ const state = {
45182
+ movie: null,
45183
+ tracks: [],
45184
+ trexDefaults: new Map(),
45185
+ fragmentDurations: new Map(),
45186
+ trafTrackId: 0,
45187
+ trafDefaultSampleDuration: 0
45188
+ };
45189
+ let offset = 0;
45190
+ while(offset + 8 <= fileSize){
45191
+ const header = readBoxHeader(fd, offset, fileSize);
45192
+ if (!header) break;
45193
+ if ("moov" === header.type || "moof" === header.type) {
45194
+ const bodyLength = header.size - header.headerSize;
45195
+ if (bodyLength > 0 && bodyLength <= MAX_METADATA_BOX_SIZE) {
45196
+ const body = Buffer.alloc(bodyLength);
45197
+ const read = external_node_fs_default().readSync(fd, body, 0, bodyLength, offset + header.headerSize);
45198
+ state.trafTrackId = 0;
45199
+ state.trafDefaultSampleDuration = 0;
45200
+ walkBoxes(body.subarray(0, read), 0, read, state);
45201
+ }
45202
+ }
45203
+ offset += header.size;
45204
+ }
45205
+ const { movie, tracks } = state;
45206
+ const video = tracks.find((t)=>"vide" === t.handler) || tracks.find((t)=>t.width > 0 && t.height > 0);
45207
+ if (!video) return null;
45208
+ let { width, height } = video;
45209
+ if (90 === video.rotation || 270 === video.rotation) [width, height] = [
45210
+ height,
45211
+ width
45212
+ ];
45213
+ return {
45214
+ width: Math.round(width),
45215
+ height: Math.round(height),
45216
+ duration: resolveDuration(movie, video, state.fragmentDurations),
45217
+ rotation: video.rotation,
45218
+ fileSize,
45219
+ codec: video.codec
45220
+ };
45221
+ } catch {
45222
+ return null;
45223
+ } finally{
45224
+ try {
45225
+ external_node_fs_default().closeSync(fd);
45226
+ } catch {}
45227
+ }
45228
+ }
45229
+ function walkBoxes(buf, start, end, state) {
45230
+ let off = start;
45231
+ while(off + 8 <= end){
45232
+ let size = buf.readUInt32BE(off);
45233
+ const type = buf.toString("latin1", off + 4, off + 8);
45234
+ let headerSize = 8;
45235
+ if (1 === size) {
45236
+ if (off + 16 > end) break;
45237
+ const hi = buf.readUInt32BE(off + 8);
45238
+ const lo = buf.readUInt32BE(off + 12);
45239
+ size = hi * 2 ** 32 + lo;
45240
+ headerSize = 16;
45241
+ } else if (0 === size) size = end - off;
45242
+ if (size < headerSize || off + size > end) break;
45243
+ const bodyStart = off + headerSize;
45244
+ const bodyEnd = off + size;
45245
+ switch(type){
45246
+ case "trak":
45247
+ case "mdia":
45248
+ case "minf":
45249
+ case "stbl":
45250
+ case "mvex":
45251
+ case "traf":
45252
+ walkBoxes(buf, bodyStart, bodyEnd, state);
45253
+ break;
45254
+ case "mvhd":
45255
+ state.movie = parseMvhd(buf, bodyStart, bodyEnd);
45256
+ break;
45257
+ case "tkhd":
45258
+ state.tracks.push({
45259
+ ...parseTkhd(buf, bodyStart, bodyEnd),
45260
+ handler: null,
45261
+ codec: null,
45262
+ timescale: 0,
45263
+ mdhdDuration: 0,
45264
+ sttsDuration: 0
45265
+ });
45266
+ break;
45267
+ case "mdhd":
45268
+ {
45269
+ const mdhd = parseMvhd(buf, bodyStart, bodyEnd);
45270
+ if (mdhd && state.tracks.length) {
45271
+ const track = state.tracks[state.tracks.length - 1];
45272
+ track.timescale = mdhd.timescale;
45273
+ track.mdhdDuration = mdhd.duration;
45274
+ }
45275
+ break;
45276
+ }
45277
+ case "hdlr":
45278
+ if (bodyEnd - bodyStart >= 12 && state.tracks.length) state.tracks[state.tracks.length - 1].handler = buf.toString("latin1", bodyStart + 8, bodyStart + 12);
45279
+ break;
45280
+ case "stsd":
45281
+ {
45282
+ const codec = parseStsdCodec(buf, bodyStart, bodyEnd);
45283
+ if (codec && state.tracks.length) state.tracks[state.tracks.length - 1].codec = codec;
45284
+ break;
45285
+ }
45286
+ case "stts":
45287
+ if (state.tracks.length) state.tracks[state.tracks.length - 1].sttsDuration = parseSttsDuration(buf, bodyStart, bodyEnd);
45288
+ break;
45289
+ case "trex":
45290
+ if (bodyStart + 20 > bodyEnd) break;
45291
+ state.trexDefaults.set(buf.readUInt32BE(bodyStart + 4), buf.readUInt32BE(bodyStart + 12));
45292
+ break;
45293
+ case "tfhd":
45294
+ {
45295
+ const tfhd = parseTfhd(buf, bodyStart, bodyEnd);
45296
+ state.trafTrackId = tfhd.trackId;
45297
+ state.trafDefaultSampleDuration = tfhd.defaultSampleDuration || state.trexDefaults.get(tfhd.trackId) || 0;
45298
+ break;
45299
+ }
45300
+ case "trun":
45301
+ {
45302
+ const duration = parseTrunDuration(buf, bodyStart, bodyEnd, state.trafDefaultSampleDuration);
45303
+ state.fragmentDurations.set(state.trafTrackId, (state.fragmentDurations.get(state.trafTrackId) || 0) + duration);
45304
+ break;
45305
+ }
45306
+ }
45307
+ off += size;
45308
+ }
45309
+ }
45310
+ const UNKNOWN_DURATION_32 = 0xffffffff;
45311
+ function isUsableDuration(duration) {
45312
+ return duration > 0 && duration !== UNKNOWN_DURATION_32;
45313
+ }
45314
+ function resolveDuration(movie, video, fragmentDurations) {
45315
+ if (movie && movie.timescale && isUsableDuration(movie.duration)) return movie.duration / movie.timescale;
45316
+ if (video.timescale) {
45317
+ if (isUsableDuration(video.mdhdDuration)) return video.mdhdDuration / video.timescale;
45318
+ if (video.sttsDuration > 0) return video.sttsDuration / video.timescale;
45319
+ const fragment = fragmentDurations.get(video.trackId) ?? (1 === fragmentDurations.size ? [
45320
+ ...fragmentDurations.values()
45321
+ ][0] : 0);
45322
+ if (fragment > 0) return fragment / video.timescale;
45323
+ }
45324
+ return 0;
45325
+ }
45326
+ function parseSttsDuration(buf, start, end) {
45327
+ if (start + 8 > end) return 0;
45328
+ const entryCount = buf.readUInt32BE(start + 4);
45329
+ let total = 0;
45330
+ for(let i = 0; i < entryCount; i++){
45331
+ const off = start + 8 + 8 * i;
45332
+ if (off + 8 > end) break;
45333
+ total += buf.readUInt32BE(off) * buf.readUInt32BE(off + 4);
45334
+ }
45335
+ return total;
45336
+ }
45337
+ function parseTfhd(buf, start, end) {
45338
+ if (start + 8 > end) return {
45339
+ trackId: 0,
45340
+ defaultSampleDuration: 0
45341
+ };
45342
+ const flags = buf.readUIntBE(start + 1, 3);
45343
+ const trackId = buf.readUInt32BE(start + 4);
45344
+ let off = start + 8;
45345
+ if (0x000001 & flags) off += 8;
45346
+ if (0x000002 & flags) off += 4;
45347
+ if (0x000008 & flags && off + 4 <= end) return {
45348
+ trackId,
45349
+ defaultSampleDuration: buf.readUInt32BE(off)
45350
+ };
45351
+ return {
45352
+ trackId,
45353
+ defaultSampleDuration: 0
45354
+ };
45355
+ }
45356
+ function parseTrunDuration(buf, start, end, defaultSampleDuration) {
45357
+ if (start + 8 > end) return 0;
45358
+ const flags = buf.readUIntBE(start + 1, 3);
45359
+ const sampleCount = buf.readUInt32BE(start + 4);
45360
+ let off = start + 8;
45361
+ if (0x000001 & flags) off += 4;
45362
+ if (0x000004 & flags) off += 4;
45363
+ const hasDuration = (0x000100 & flags) !== 0;
45364
+ if (!hasDuration) return sampleCount * defaultSampleDuration;
45365
+ const entrySize = 4 + ((0x000200 & flags) !== 0 ? 4 : 0) + ((0x000400 & flags) !== 0 ? 4 : 0) + ((0x000800 & flags) !== 0 ? 4 : 0);
45366
+ let total = 0;
45367
+ for(let i = 0; i < sampleCount; i++){
45368
+ const entryOff = off + i * entrySize;
45369
+ if (entryOff + 4 > end) break;
45370
+ total += buf.readUInt32BE(entryOff);
45371
+ }
45372
+ return total;
45373
+ }
45374
+ function parseStsdCodec(buf, start, end) {
45375
+ if (start + 16 > end) return null;
45376
+ if (0 === buf.readUInt32BE(start + 4)) return null;
45377
+ return buf.toString("latin1", start + 12, start + 16).toLowerCase();
45378
+ }
45379
+ function parseMvhd(buf, start, end) {
45380
+ const version = buf.readUInt8(start);
45381
+ if (1 === version) {
45382
+ if (start + 28 > end) return null;
45383
+ const timescale = buf.readUInt32BE(start + 20);
45384
+ const hi = buf.readUInt32BE(start + 24);
45385
+ const lo = buf.readUInt32BE(start + 28);
45386
+ return {
45387
+ timescale,
45388
+ duration: hi * 2 ** 32 + lo
45389
+ };
45390
+ }
45391
+ if (start + 20 > end) return null;
45392
+ return {
45393
+ timescale: buf.readUInt32BE(start + 12),
45394
+ duration: buf.readUInt32BE(start + 16)
45395
+ };
45396
+ }
45397
+ function parseTkhd(buf, start, end) {
45398
+ const version = buf.readUInt8(start);
45399
+ const afterDuration = 1 === version ? 36 : 24;
45400
+ const matrixOff = start + afterDuration + 16;
45401
+ const whOff = matrixOff + 36;
45402
+ const trackIdOff = start + (1 === version ? 20 : 12);
45403
+ const trackId = trackIdOff + 4 <= end ? buf.readUInt32BE(trackIdOff) : 0;
45404
+ if (whOff + 8 > end) return {
45405
+ trackId,
45406
+ width: 0,
45407
+ height: 0,
45408
+ rotation: 0
45409
+ };
45410
+ const width = buf.readUInt32BE(whOff) / 65536;
45411
+ const height = buf.readUInt32BE(whOff + 4) / 65536;
45412
+ const a = buf.readInt32BE(matrixOff) / 65536;
45413
+ const b = buf.readInt32BE(matrixOff + 4) / 65536;
45414
+ let rotation = 0;
45415
+ if (Math.abs(a) < 0.01 && Math.abs(b - 1) < 0.01) rotation = 90;
45416
+ else if (Math.abs(a + 1) < 0.01 && Math.abs(b) < 0.01) rotation = 180;
45417
+ else if (Math.abs(a) < 0.01 && Math.abs(b + 1) < 0.01) rotation = 270;
45418
+ return {
45419
+ trackId,
45420
+ width,
45421
+ height,
45422
+ rotation
45423
+ };
45424
+ }
45425
+ function parseVideoCodec(filePath) {
45426
+ return parseVideoMeta(filePath)?.codec ?? null;
45427
+ }
45428
+ function buildVideoMetaFromParams(filePath, metadata) {
45429
+ return {
45430
+ width: Math.round(metadata.width),
45431
+ height: Math.round(metadata.height),
45432
+ duration: metadata.duration,
45433
+ rotation: 0,
45434
+ fileSize: metadata.fileSize,
45435
+ codec: parseVideoCodec(filePath)
45436
+ };
45437
+ }
45438
+ const MAX_DURATION_SECONDS = 28800;
45439
+ const MAX_FILE_SIZE = 21474836480;
45440
+ const ALLOWED_EXTENSIONS = [
45441
+ ".mp4"
45442
+ ];
45443
+ const ALLOWED_CODECS = [
45444
+ "avc1",
45445
+ "avc3"
45446
+ ];
45447
+ const MIN_TITLE_LENGTH = 6;
45448
+ const MAX_TITLE_LENGTH = 16;
45449
+ function formatFileSize(bytes) {
45450
+ if (bytes < 1048576) return `${(bytes / 1024).toFixed(2)} KB`;
45451
+ if (bytes < 1073741824) return `${(bytes / 1024 / 1024).toFixed(2)} MB`;
45452
+ return `${(bytes / 1024 / 1024 / 1024).toFixed(2)} GB`;
45453
+ }
45454
+ function formatDuration(seconds) {
45455
+ const total = Math.round(seconds);
45456
+ const h = Math.floor(total / 3600);
45457
+ const m = Math.floor(total % 3600 / 60);
45458
+ const s = total % 60;
45459
+ if (h > 0) return `${h}小时${m}分${s}秒`;
45460
+ if (m > 0) return `${m}分${s}秒`;
45461
+ return `${s}秒`;
45462
+ }
45463
+ function validateShipinhaoVideo(filePath, meta) {
45464
+ const fileName = external_node_path_default().basename(filePath);
45465
+ const ext = external_node_path_default().extname(fileName).toLowerCase();
45466
+ if (!ALLOWED_EXTENSIONS.includes(ext)) return `视频格式不支持:${fileName}。视频号仅支持 MP4/H.264 格式,请转换后重试。`;
45467
+ if (meta.duration > MAX_DURATION_SECONDS) return `视频时长超过限制:${fileName}(${formatDuration(meta.duration)})。视频号视频时长不能超过 8 小时,请剪辑后重试。`;
45468
+ if (meta.fileSize > MAX_FILE_SIZE) return `视频大小超过限制:${fileName}(${formatFileSize(meta.fileSize)})。视频号视频不能超过 20GB,请压缩后重试。`;
45469
+ if (meta.codec && !ALLOWED_CODECS.includes(meta.codec)) return `视频编码不支持:${fileName}(${meta.codec})。视频号仅支持 H.264 编码,请转码后重试。`;
45470
+ return null;
45471
+ }
45472
+ function validateShipinhaoTitle(title) {
45473
+ if (void 0 === title) return null;
45474
+ const trimmed = title.trim();
45475
+ if ("" === trimmed) return null;
45476
+ const length = [
45477
+ ...trimmed
45478
+ ].length;
45479
+ if (length < MIN_TITLE_LENGTH || length > MAX_TITLE_LENGTH) return `视频号标题需要在 ${MIN_TITLE_LENGTH}-${MAX_TITLE_LENGTH} 个字符之间,当前 ${length} 个字符,请调整后重试。`;
45480
+ return null;
45481
+ }
45482
+ const POST_CREATE_PAGE_URL = "https://channels.weixin.qq.com/micro/content/post/create";
45483
+ const MICRO_CONTENT_BASE = "https://channels.weixin.qq.com/micro/content/cgi-bin/mmfinderassistant-bin";
45484
+ function resolveClientContext(params, fallbackUin) {
45485
+ const extra = params.extraParam || {};
45486
+ const deviceIdCookie = params.cookies.find((c)=>"device_id" === c.name || "finger_print_device_id" === c.name)?.value;
45487
+ return {
45488
+ aId: "string" == typeof extra.aId ? extra.aId : "",
45489
+ fingerPrintDeviceId: "string" == typeof extra.fingerPrintDeviceId ? extra.fingerPrintDeviceId : deviceIdCookie || "",
45490
+ uin: "string" == typeof extra.uin ? extra.uin : String(fallbackUin)
45491
+ };
45492
+ }
45493
+ function buildPublishHeaders(cookieString, client) {
45494
+ const headers = {
45495
+ cookie: cookieString,
45496
+ referer: POST_CREATE_PAGE_URL,
45497
+ origin: "https://channels.weixin.qq.com",
45498
+ "content-type": "application/json"
45499
+ };
45500
+ if (client.fingerPrintDeviceId) headers["finger-print-device-id"] = client.fingerPrintDeviceId;
45501
+ if (client.uin) headers["x-wechat-uin"] = client.uin;
45502
+ return headers;
45503
+ }
45504
+ function buildPublishQuery(client) {
45505
+ const query = {
45506
+ _rid: rid(),
45507
+ _pageUrl: POST_CREATE_PAGE_URL
45508
+ };
45509
+ if (client.aId) query._aid = client.aId;
45510
+ return query;
45511
+ }
45512
+ function buildCommonBody(finderUsername) {
45513
+ return {
45514
+ timestamp: String(Date.now()),
45515
+ _log_finder_uin: "",
45516
+ _log_finder_id: finderUsername,
45517
+ rawKeyBuff: "",
45518
+ pluginSessionId: null,
45519
+ scene: 7,
45520
+ reqScene: 7
45521
+ };
45522
+ }
45523
+ async function getTraceKey(auth, client, http, logger) {
45524
+ const res = await http.api({
45525
+ method: "POST",
45526
+ url: `${MICRO_CONTENT_BASE}/post/get-finder-post-trace-key`,
45527
+ params: buildPublishQuery(client),
45528
+ data: {
45529
+ objectId: "",
45530
+ ...buildCommonBody(auth.finderUsername)
45531
+ },
45532
+ defaultErrorMsg: "获取 traceKey 失败"
45533
+ });
45534
+ if (0 !== res.errCode || !res.data?.traceKey) {
45535
+ logger.error("[getTraceKey] 获取失败:", JSON.stringify(res));
45536
+ throw new Error(`获取 traceKey 失败: ${JSON.stringify(res)}`);
45537
+ }
45538
+ return res.data.traceKey;
45539
+ }
45540
+ async function getObjectTagKey(auth, client, http, logger) {
45541
+ try {
45542
+ const res = await http.api({
45543
+ method: "POST",
45544
+ url: `${MICRO_CONTENT_BASE}/post/finder_get_object_tag_list`,
45545
+ params: buildPublishQuery(client),
45546
+ data: {
45547
+ source: 1,
45548
+ ...buildCommonBody(auth.finderUsername)
45549
+ },
45550
+ defaultErrorMsg: "获取内容声明标注失败"
45551
+ });
45552
+ if (0 !== res.errCode || !res.data?.tagKey) {
45553
+ logger.warn(`[getObjectTagKey] 未取到 tagKey: ${JSON.stringify(res)}`);
45554
+ return null;
45555
+ }
45556
+ return res.data.tagKey;
45557
+ } catch (error) {
45558
+ logger.warn(`[getObjectTagKey] 获取 tagKey 异常: ${stringifyError(error)}`);
45559
+ return null;
45560
+ }
45561
+ }
45562
+ async function submitAndPollTranscode(opts) {
45563
+ const { videoUrl, videoMeta, traceKey, uploadStartTime, uploadEndTime, finderUsername, client, http, logger } = opts;
45564
+ const finderUrl = videoUrl.includes("wxapp.tc.qq.com") ? `https://finder.video.qq.com${videoUrl.split("qq.com")[1]}` : videoUrl;
45565
+ logger.info(`[submitAndPollTranscode] 视频尺寸: ${videoMeta.width}x${videoMeta.height}, 时长: ${videoMeta.duration}s`);
45566
+ const submitRes = await http.api({
45567
+ method: "POST",
45568
+ url: `${MICRO_CONTENT_BASE}/post/post_clip_video`,
45569
+ params: buildPublishQuery(client),
45570
+ data: {
45571
+ url: finderUrl,
45572
+ timeStart: 0,
45573
+ cropDuration: 0,
45574
+ height: videoMeta.height,
45575
+ width: videoMeta.width,
45576
+ x: 0,
45577
+ y: 0,
45578
+ clipOriginVideoInfo: {
45579
+ width: videoMeta.width,
45580
+ height: videoMeta.height,
45581
+ duration: videoMeta.duration,
45582
+ fileSize: videoMeta.fileSize
45583
+ },
45584
+ traceInfo: {
45585
+ traceKey,
45586
+ uploadCdnStart: uploadStartTime,
45587
+ uploadCdnEnd: uploadEndTime
45588
+ },
45589
+ targetWidth: videoMeta.width,
45590
+ targetHeight: videoMeta.height,
45591
+ type: 4,
45592
+ useAstraThumbCover: 1,
45593
+ ...buildCommonBody(finderUsername)
45594
+ },
45595
+ defaultErrorMsg: "提交转码失败"
45596
+ });
45597
+ if (0 !== submitRes.errCode || !submitRes.data?.clipKey) {
45598
+ logger.error("[submitAndPollTranscode] 提交转码失败:", JSON.stringify(submitRes));
45599
+ throw new Error(`提交转码失败: ${JSON.stringify(submitRes)}`);
45600
+ }
45601
+ const { clipKey, draftId } = submitRes.data;
45602
+ const pollInterval = 5000;
45603
+ const pollBudget = Math.min(1800000, 300000 + 1000 * Math.ceil(1.5 * videoMeta.duration));
45604
+ const maxPolls = Math.ceil(pollBudget / pollInterval);
45605
+ let pollCount = 0;
45606
+ while(pollCount < maxPolls){
45607
+ await mock_sleep(pollInterval);
45608
+ pollCount++;
45609
+ const pollRes = await http.api({
45610
+ method: "POST",
45611
+ url: `${MICRO_CONTENT_BASE}/post/post_clip_video_result`,
45612
+ params: buildPublishQuery(client),
45613
+ data: {
45614
+ clipKey,
45615
+ draftId,
45616
+ ...buildCommonBody(finderUsername)
45617
+ },
45618
+ defaultErrorMsg: "转码轮询失败"
45619
+ }, {
45620
+ timeout: 60000,
45621
+ retries: 2,
45622
+ retryDelay: 3000
45623
+ });
45624
+ if (0 !== pollRes.errCode) {
45625
+ logger.error(`[submitAndPollTranscode] 转码轮询失败 (poll ${pollCount}):`, JSON.stringify(pollRes));
45626
+ throw new Error(`转码轮询失败 (poll ${pollCount}): ${JSON.stringify(pollRes)}`);
45627
+ }
45628
+ const { flag, url, width, height, duration, md5, fileSize } = pollRes.data || {};
45629
+ if (1 === flag) {
45630
+ if (!url || !width || !height || !duration || !md5 || !fileSize) {
45631
+ logger.error("[submitAndPollTranscode] 转码完成但返回数据不完整:", JSON.stringify(pollRes.data));
45632
+ throw new Error(`转码完成但返回数据不完整: ${JSON.stringify(pollRes.data)}`);
45633
+ }
45634
+ logger.info(`[submitAndPollTranscode] 转码完成! 用时: ${pollCount * pollInterval / 1000}s`);
45635
+ return {
45636
+ clipKey,
45637
+ url,
45638
+ width,
45639
+ height,
45640
+ duration,
45641
+ md5,
45642
+ fileSize
45643
+ };
45644
+ }
45645
+ if (2 === flag) ;
45646
+ else {
45647
+ logger.error(`[submitAndPollTranscode] 转码失败,未知 flag=${flag}:`, JSON.stringify(pollRes.data));
45648
+ throw new Error(`转码失败,未知 flag=${flag}: ${JSON.stringify(pollRes.data)}`);
45649
+ }
45650
+ }
45651
+ logger.error(`[submitAndPollTranscode] 转码超时,已轮询 ${maxPolls} 次,用时: ${maxPolls * pollInterval / 1000}s`);
45652
+ throw new Error(`转码超时 (${maxPolls * pollInterval / 1000}s)`);
45653
+ }
45654
+ async function publishVideo(opts) {
45655
+ const { params, auth, client, clipResult, videoUpload, coverUpload, verticalCoverUpload, videoMeta, traceKey, tagKey, uploadStartTime, uploadEndTime, proxyHttp, logger } = opts;
45656
+ const toFinderUrl = (url)=>url.includes("wxapp.tc.qq.com") ? `https://finder.video.qq.com${url.split("qq.com")[1]}` : url;
45657
+ const thumbFinderUrl = toFinderUrl(coverUpload.downloadUrl);
45658
+ const coverFinderUrl = toFinderUrl(verticalCoverUpload.downloadUrl);
45659
+ const md5sumUuid = external_node_crypto_default().randomUUID();
45660
+ const description = params.description;
45661
+ const objectDesc = {
45662
+ mpTitle: "",
45663
+ description,
45664
+ extReading: buildExtReading(params.link),
45665
+ mediaType: 4,
45666
+ location: payload_buildLocation(params.location),
45667
+ topic: buildTopic({
45668
+ description: params.description,
45669
+ topics: params.topics,
45670
+ mentionedUsers: params.mentionedUsers,
45671
+ collection: params.collection
45672
+ }),
45673
+ event: buildEvent(params.event),
45674
+ mentionedUser: buildMentionedUser(params.mentionedUsers),
45675
+ media: [
45676
+ {
45677
+ url: clipResult.url,
45678
+ fileSize: clipResult.fileSize,
45679
+ thumbUrl: thumbFinderUrl,
45680
+ fullThumbUrl: thumbFinderUrl,
45681
+ coverUrl: coverFinderUrl,
45682
+ fullCoverUrl: coverFinderUrl,
45683
+ shareCoverUrl: coverFinderUrl,
45684
+ mediaType: 4,
45685
+ videoPlayLen: Math.round(clipResult.duration),
45686
+ width: clipResult.width,
45687
+ height: clipResult.height,
45688
+ md5sum: md5sumUuid,
45689
+ cardShowStyle: 2,
45690
+ urlCdnTaskId: clipResult.clipKey
45691
+ }
45692
+ ],
45693
+ shortTitle: params.title ? [
45694
+ {
45695
+ shortTitle: params.title
45696
+ }
45697
+ ] : [],
45698
+ member: {}
45699
+ };
45700
+ const publishData = {
45701
+ objectType: 0,
45702
+ longitude: 0,
45703
+ latitude: 0,
45704
+ feedLongitude: 0,
45705
+ feedLatitude: 0,
45706
+ originalFlag: params.originalFlag ?? 0,
45707
+ topics: params.topics || [],
45708
+ isFullPost: 1,
45709
+ handleFlag: 2,
45710
+ videoClipTaskId: clipResult.clipKey,
45711
+ traceInfo: {
45712
+ traceKey,
45713
+ uploadCdnStart: uploadStartTime,
45714
+ uploadCdnEnd: uploadEndTime
45715
+ },
45716
+ objectDesc,
45717
+ report: {
45718
+ clipKey: clipResult.clipKey,
45719
+ draftId: clipResult.clipKey,
45720
+ ...buildCommonBody(auth.finderUsername),
45721
+ height: videoMeta.height,
45722
+ width: videoMeta.width,
45723
+ duration: videoMeta.duration,
45724
+ fileSize: videoUpload.fileSize,
45725
+ uploadCost: (uploadEndTime - uploadStartTime) * 1000
45726
+ },
45727
+ postFlag: 0,
45728
+ mode: 1,
45729
+ clientid: external_node_crypto_default().randomUUID(),
45730
+ ...buildCommonBody(auth.finderUsername)
45731
+ };
45732
+ if (params.scheduledTime) publishData.effectiveTime = params.scheduledTime;
45733
+ if (params.tagInfo && tagKey) publishData.tagInfo = buildTagInfo(params.tagInfo, tagKey);
45734
+ const publishRes = await proxyHttp.api({
45735
+ method: "POST",
45736
+ url: `${MICRO_CONTENT_BASE}/post/post_create`,
45737
+ params: buildPublishQuery(client),
45738
+ data: publishData,
45739
+ defaultErrorMsg: "发布视频失败"
45740
+ });
45741
+ logger.info(`[publishVideo] 发布结果: errCode=${publishRes.errCode}, baseResp.errcode=${publishRes.data?.baseResp?.errcode}`);
45742
+ return publishRes;
45743
+ }
45744
+ function mock_sleep(ms) {
45745
+ return new Promise((resolve)=>setTimeout(resolve, ms));
45746
+ }
45747
+ async function resolveLocalCoverPath(coverPath, label, tmpCachePath, logger) {
45748
+ if (!/^https?:\/\//i.test(coverPath)) return coverPath;
45749
+ const fileName = getFilenameFromUrl(coverPath);
45750
+ const savePath = external_node_path_default().join(tmpCachePath, `${Date.now()}-${label}-${fileName}`);
45751
+ await downloadImage(coverPath, savePath);
45752
+ return savePath;
45753
+ }
45754
+ const shipinhaoPublishVideo_mock_mockAction = async (task, params)=>{
45755
+ const updateTaskState = task.taskStageStore?.update?.bind(task.taskStageStore, task.taskId || "");
45756
+ let currentStep = "初始化";
45757
+ try {
45758
+ currentStep = "解析认证信息";
45759
+ const cookieString = params.cookies.map((c)=>`${c.name}=${c.value}`).join("; ");
45760
+ const http = new Http({
45761
+ headers: {
45762
+ cookie: cookieString
45763
+ }
45764
+ });
45765
+ currentStep = "验证发布参数";
45766
+ if (!params.videoPath) return utils_response(414, "视频文件路径不能为空", "");
45767
+ if (!params.coverPath) return utils_response(414, "横屏封面图片路径不能为空", "");
45768
+ currentStep = "获取上传认证";
45769
+ const auth = await getShipinhaoUploadAuth(cookieString, http);
45770
+ const client = resolveClientContext(params, auth.uin);
45771
+ const publishHeaders = buildPublishHeaders(cookieString, client);
45772
+ const microHttp = new Http({
45773
+ headers: publishHeaders
45774
+ });
45775
+ const args = [
45776
+ {
45777
+ headers: publishHeaders
45778
+ },
45779
+ task.logger,
45780
+ params.proxyLoc,
45781
+ params.accountId,
45782
+ "shipinhao"
45783
+ ];
45784
+ const proxyHttp = new Http(...args);
45785
+ currentStep = "组装视频元数据";
45786
+ const videoMeta = buildVideoMetaFromParams(params.videoPath, params.videoMetadata);
45787
+ task.logger.info(`[shipinhaoPublishVideo] 视频: ${videoMeta.width}×${videoMeta.height}, ${videoMeta.duration.toFixed(2)}s, ${(videoMeta.fileSize / 1024 / 1024).toFixed(2)}MB, codec=${videoMeta.codec || "unknown"}`);
45788
+ currentStep = "校验视频限制";
45789
+ const validationError = validateShipinhaoVideo(params.videoPath, videoMeta);
45790
+ if (validationError) {
45791
+ await updateTaskState?.({
45792
+ state: types_TaskState.FAILED,
45793
+ error: validationError
45794
+ });
45795
+ return utils_response(414, validationError, "");
45796
+ }
45797
+ currentStep = "校验标题";
45798
+ const titleError = validateShipinhaoTitle(params.title);
45799
+ if (titleError) {
45800
+ await updateTaskState?.({
45801
+ state: types_TaskState.FAILED,
45802
+ error: titleError
45803
+ });
45804
+ return utils_response(414, titleError, "");
45805
+ }
45806
+ currentStep = "获取 traceKey";
45807
+ const traceKey = await getTraceKey(auth, client, microHttp, task.logger);
45808
+ let tagKey = null;
45809
+ if (params.tagInfo) {
45810
+ currentStep = "获取内容声明 tagKey";
45811
+ tagKey = await getObjectTagKey(auth, client, microHttp, task.logger);
45812
+ }
45813
+ const uploadStartTime = Math.floor(Date.now() / 1000);
45814
+ currentStep = "上传视频";
45815
+ const videoUpload = await uploader_uploadFile({
45816
+ filePath: params.videoPath,
45817
+ fileType: auth.videoFileType,
45818
+ uin: auth.uin,
45819
+ authKey: auth.authKey,
45820
+ http,
45821
+ logger: task.logger
45822
+ });
45823
+ const uploadEndTime = Math.floor(Date.now() / 1000);
45824
+ task.logger.info(`[shipinhaoPublishVideo] 耗时: ${uploadEndTime - uploadStartTime}s`);
45825
+ currentStep = "上传横屏封面";
45826
+ const localCoverPath = await resolveLocalCoverPath(params.coverPath, "横屏封面", task.getTmpPath(), task.logger);
45827
+ const coverUpload = await uploader_uploadFile({
45828
+ filePath: localCoverPath,
45829
+ fileType: auth.pictureFileType,
45830
+ uin: auth.uin,
45831
+ authKey: auth.authKey,
45832
+ http,
45833
+ logger: task.logger
45834
+ });
45835
+ let verticalCoverUpload = coverUpload;
45836
+ if (params.verticalCoverPath) {
45837
+ currentStep = "上传竖屏封面";
45838
+ const localVerticalPath = await resolveLocalCoverPath(params.verticalCoverPath, "竖屏封面", task.getTmpPath(), task.logger);
45839
+ verticalCoverUpload = await uploader_uploadFile({
45840
+ filePath: localVerticalPath,
45841
+ fileType: auth.pictureFileType,
45842
+ uin: auth.uin,
45843
+ authKey: auth.authKey,
45844
+ http,
45845
+ logger: task.logger
45846
+ });
45847
+ }
45848
+ currentStep = "提交转码";
45849
+ const clipResult = await submitAndPollTranscode({
45850
+ videoUrl: videoUpload.downloadUrl,
45851
+ videoMeta,
45852
+ traceKey,
45853
+ uploadStartTime,
45854
+ uploadEndTime,
45855
+ finderUsername: auth.finderUsername,
45856
+ client,
45857
+ http: microHttp,
45858
+ logger: task.logger
45859
+ });
45860
+ currentStep = "发布视频";
45861
+ let publishResult;
45862
+ try {
45863
+ publishResult = await publishVideo({
45864
+ params,
45865
+ auth,
45866
+ client,
45867
+ clipResult,
45868
+ videoUpload,
45869
+ coverUpload,
45870
+ verticalCoverUpload,
45871
+ videoMeta,
45872
+ traceKey,
45873
+ tagKey,
45874
+ uploadStartTime,
45875
+ uploadEndTime,
45876
+ proxyHttp,
45877
+ logger: task.logger
45878
+ });
45879
+ } catch (error) {
45880
+ const handledError = Http.handleApiError(error);
45881
+ task.logger.error(`[shipinhaoPublishVideo] 发布请求失败: ${handledError.message}`, stringifyError(handledError));
45882
+ const classified = classifyPublishError(handledError);
45883
+ if (classified) {
45884
+ const message = `${classified.userMessage}${task.debug ? ` ${http.proxyInfo}` : ""}`;
45885
+ await updateTaskState?.({
45886
+ state: types_TaskState.FAILED,
45887
+ error: message
45888
+ });
45889
+ return {
45890
+ code: 414,
45891
+ data: "",
45892
+ message
45893
+ };
45894
+ }
45895
+ throw error;
45896
+ }
45897
+ task.logger.info(`[shipinhaoPublishVideo] publishResult: ${JSON.stringify(publishResult)}`);
45898
+ const resultCode = publishResult.data?.baseResp?.errcode ?? publishResult.errCode;
45899
+ const resultMsg = publishResult.data?.baseResp?.errmsg ?? (0 === resultCode ? "发布成功" : `发布失败(errCode=${resultCode})`);
45900
+ if (0 === resultCode) {
45901
+ const publishId = extractEncFileKey(coverUpload.downloadUrl);
45902
+ if (!publishId) task.logger.error(`[shipinhaoPublishVideo] 封面 DownloadURL 中未解析到 encfilekey,关联 id 为空: ${coverUpload.downloadUrl}`);
45903
+ await updateTaskState?.({
45904
+ state: types_TaskState.SUCCESS,
45905
+ result: {
45906
+ response: resultMsg
45907
+ }
45908
+ });
45909
+ reportLogger({
45910
+ token: params.huiwenToken || "",
45911
+ enverionment: task.enverionment || "development",
45912
+ postId: params.articleId,
45913
+ eip: proxyHttp.proxyInfo,
45914
+ accountId: params.accountId,
45915
+ uid: params.uid,
45916
+ publishParams: {
45917
+ videoPath: params.videoPath,
45918
+ coverPath: params.coverPath,
45919
+ verticalCoverPath: params.verticalCoverPath,
45920
+ title: params.title,
45921
+ topics: params.topics,
45922
+ mentionedUsers: params.mentionedUsers,
45923
+ collection: params.collection,
45924
+ event: params.event,
45925
+ link: params.link,
45926
+ tagInfo: params.tagInfo,
45927
+ originalFlag: params.originalFlag,
45928
+ scheduledTime: params.scheduledTime
45929
+ },
45930
+ platform: "shipinhao"
45931
+ });
45932
+ return utils_response(0, "发布成功", publishId);
45933
+ }
45934
+ let errorMessage = resultMsg;
45935
+ if (-11224 === resultCode) errorMessage = "视频号管理员完成实名且绑定手机号后才可以发表";
45936
+ else if (300333 === resultCode || 300334 === resultCode) errorMessage = "登录失效";
45937
+ else if (300330 === resultCode) errorMessage = "未登录";
45938
+ else if (300002 === resultCode) errorMessage = "官方平台在校验音乐/位置/定时信息时失败了,请重新编辑后发布";
45939
+ task.logger.error(`[shipinhaoPublishVideo] 发布失败: ${errorMessage} (errCode=${resultCode})`);
45940
+ await updateTaskState?.({
45941
+ state: types_TaskState.FAILED,
45942
+ error: errorMessage
45943
+ });
45944
+ return utils_response(414, errorMessage, "");
45945
+ } catch (error) {
45946
+ const handledError = Http.handleApiError(error);
45947
+ const errorMsg = handledError.message || "发布失败,请稍后重试";
45948
+ task.logger.error(`[shipinhaoPublishVideo] 发布流程异常 [${currentStep}]: ${errorMsg}`, stringifyError(error), handledError.extra);
45949
+ await updateTaskState?.({
45950
+ state: types_TaskState.FAILED,
45951
+ error: errorMsg
45952
+ });
45953
+ return utils_response(414, errorMsg, "");
45954
+ }
45955
+ };
45956
+ const shipinhaoPublishVideo_rpa_rpaAction = async (task, params)=>{
45957
+ task.logger.info("开始微信视频号视频发布(RPA 模式)");
45958
+ const videoMeta = buildVideoMetaFromParams(params.videoPath, params.videoMetadata);
45959
+ task.logger.info(`视频: ${videoMeta.width}×${videoMeta.height}, ${videoMeta.duration.toFixed(2)}s, ${(videoMeta.fileSize / 1024 / 1024).toFixed(2)}MB, codec=${videoMeta.codec || "unknown"}`);
45960
+ if (!videoMeta.codec) task.logger.warn("未能读取视频编码格式,跳过 H.264 预检,交由服务端判断");
45961
+ const validationError = validateShipinhaoVideo(params.videoPath, videoMeta);
45962
+ if (validationError) {
45963
+ task.logger.error(`视频校验未通过: ${validationError}`);
45964
+ return utils_response(414, validationError, "");
45965
+ }
45966
+ task.logger.info("视频校验通过");
45967
+ const titleError = validateShipinhaoTitle(params.title);
45968
+ if (titleError) {
45969
+ task.logger.error(`标题校验未通过: ${titleError}`);
45970
+ return utils_response(414, titleError, "");
45971
+ }
45972
+ const unsupported = [
45973
+ params.verticalCoverPath && "verticalCoverPath",
45974
+ params.collection && "collection",
45975
+ params.originalFlag && "originalFlag",
45976
+ params.postWithMemberZoneLink && "postWithMemberZoneLink"
45977
+ ].filter(Boolean);
45978
+ if (unsupported.length) task.logger.warn(`RPA 模式不支持以下参数,将被忽略: ${unsupported.join("、")};如需生效请使用 mockApi 模式`);
45979
+ if (params.tagInfo && 5 === params.tagInfo.tagType) {
45980
+ const shootInfo = params.tagInfo.shootInfo;
45981
+ if (shootInfo && (shootInfo.provinceCode || shootInfo.cityCode)) task.logger.warn("tagInfo.tagType=5 在 RPA 模式下仅支持拍摄时间和国家选择,省市选择需要使用 mockApi 模式");
45982
+ }
45983
+ const tmpCachePath = task.getTmpPath();
45984
+ const page = await task.createPage({
45985
+ url: "https://channels.weixin.qq.com/platform/post/create",
45986
+ show: task.debug,
45987
+ cookies: params.cookies
45988
+ });
45989
+ try {
45990
+ const waitForElement = async (selector, timeout = 10000)=>{
45991
+ try {
45992
+ const element = page.locator(selector);
45993
+ await element.waitFor({
45994
+ state: "visible",
45995
+ timeout
45996
+ });
45997
+ return element;
45998
+ } catch {
45999
+ task.logger.warn(`元素未找到: ${selector}`);
46000
+ return null;
46001
+ }
46002
+ };
46003
+ const retryAction = async (action, maxRetries = 3, delay = 1000)=>{
46004
+ let lastError;
46005
+ for(let i = 0; i < maxRetries; i++)try {
46006
+ return await action();
46007
+ } catch (error) {
46008
+ lastError = error;
46009
+ task.logger.warn(`重试 ${i + 1}/${maxRetries}: ${lastError.message}`);
46010
+ if (i < maxRetries - 1) await page.waitForTimeout(delay);
46011
+ }
46012
+ throw lastError;
46013
+ };
46014
+ task.logger.info("等待页面加载...");
46015
+ task.logger.info("检查登录状态...");
46016
+ if (task.debug) {
46017
+ task.logger.info(`当前页面 URL: ${page.url()}`);
46018
+ const title = await page.title();
46019
+ task.logger.info(`页面标题: ${title}`);
46020
+ }
46021
+ try {
46022
+ await page.waitForSelector(".post-edit-wrap", {
46023
+ state: "visible",
46024
+ timeout: 30000
46025
+ });
46026
+ task.logger.info("✓ 登录状态正常,找到编辑器容器");
46027
+ } catch {
46028
+ task.logger.error("✗ 未找到编辑器,可能登录失效");
46029
+ return {
46030
+ code: 414,
46031
+ message: "登录失效或页面加载异常",
46032
+ data: page.url()
46033
+ };
46034
+ }
46035
+ task.logger.info("页面加载完成,开始填充内容");
46036
+ task.logger.info("开始上传视频");
46037
+ await retryAction(async ()=>{
46038
+ const videoUploadSelectors = [
46039
+ '.ant-upload-btn input[type="file"][accept*="video"]',
46040
+ '.upload input[type="file"][accept*="video"]',
46041
+ 'input[type="file"][accept*="video"]'
46042
+ ];
46043
+ let uploadInput = null;
46044
+ if (task.debug) {
46045
+ const allFileInputs = await page.locator('input[type="file"]').count();
46046
+ task.logger.info(`页面中共找到 ${allFileInputs} 个文件上传输入框`);
46047
+ }
46048
+ for (const selector of videoUploadSelectors){
46049
+ const input = page.locator(selector);
46050
+ const count = await input.count();
46051
+ if (count > 0) {
46052
+ uploadInput = input.first();
46053
+ task.logger.info(`找到视频上传输入框: ${selector}`);
46054
+ break;
46055
+ }
46056
+ }
46057
+ if (!uploadInput) {
46058
+ task.logger.warn("未找到视频上传输入框,等待 3 秒后重试...");
46059
+ await page.waitForTimeout(3000);
46060
+ const anyFileInput = page.locator('input[type="file"]');
46061
+ const inputCount = await anyFileInput.count();
46062
+ if (inputCount > 0) {
46063
+ uploadInput = anyFileInput.first();
46064
+ task.logger.info(`找到文件输入框(共 ${inputCount} 个)`);
46065
+ } else {
46066
+ if (task.debug) {
46067
+ const screenshotPath = external_node_path_default().join(tmpCachePath, `upload-error-${Date.now()}.png`);
46068
+ await page.screenshot({
46069
+ path: screenshotPath,
46070
+ fullPage: true
46071
+ });
46072
+ task.logger.error(`未找到上传输入框,已截图保存至: ${screenshotPath}`);
46073
+ }
46074
+ throw new Error("未找到视频上传输入框");
46075
+ }
46076
+ }
46077
+ await uploadInput.setInputFiles(params.videoPath);
46078
+ task.logger.info("视频上传成功");
46079
+ await page.waitForTimeout(5000);
46080
+ });
46081
+ if (params.coverPath) {
46082
+ task.logger.info("开始上传封面");
46083
+ await retryAction(async ()=>{
46084
+ const coverUploadBtn = await waitForElement(".cover-upload-btn", 10000);
46085
+ if (coverUploadBtn) {
46086
+ const coverInput = page.locator('.cover-upload-btn input[type="file"]');
46087
+ await coverInput.setInputFiles(params.coverPath);
46088
+ task.logger.info("封面上传成功");
46089
+ await page.waitForTimeout(2000);
46090
+ }
46091
+ });
46092
+ }
46093
+ const descriptionText = payload_buildDescription({
46094
+ description: params.description,
46095
+ topics: params.topics,
46096
+ mentionedUsers: params.mentionedUsers
46097
+ });
46098
+ if (descriptionText) {
46099
+ task.logger.info("填写视频描述");
46100
+ await retryAction(async ()=>{
46101
+ const descEditor = await waitForElement(".input-editor", 10000);
46102
+ if (!descEditor) throw new Error("未找到描述编辑器");
46103
+ await descEditor.click();
46104
+ await page.waitForTimeout(500);
46105
+ await descEditor.evaluate((el)=>{
46106
+ el.textContent = "";
46107
+ });
46108
+ await page.waitForTimeout(300);
46109
+ task.logger.info("已清空编辑器内容");
46110
+ await descEditor.pressSequentially(descriptionText, {
46111
+ delay: 10
46112
+ });
46113
+ await page.waitForTimeout(500);
46114
+ task.logger.info("描述填写完成");
46115
+ });
46116
+ }
46117
+ if (params.title) {
46118
+ task.logger.info(`填写标题: ${params.title}`);
46119
+ const title = params.title;
46120
+ await retryAction(async ()=>{
46121
+ const titleInput = await waitForElement("#container-wrap div.form-item-body.short-title-wrap input", 10000);
46122
+ if (!titleInput) throw new Error("未找到标题输入框");
46123
+ await titleInput.click();
46124
+ await titleInput.clear({
46125
+ timeout: 3000
46126
+ });
46127
+ await titleInput.fill(title, {
46128
+ timeout: 5000
46129
+ });
46130
+ task.logger.info("标题填写完成");
46131
+ });
46132
+ }
46133
+ if (params.location) {
46134
+ task.logger.info(`选择地点: ${params.location.city}`);
46135
+ const instance = page.locator(".position-display-wrap");
46136
+ await instance.click();
46137
+ await page.waitForTimeout(1000);
46138
+ await page.locator(".location-filter-wrap input").fill(params.location.city);
46139
+ await page.waitForTimeout(2000);
46140
+ const poperInstance = page.locator(".location-filter-wrap .common-option-list-wrap .option-item");
46141
+ await poperInstance.nth(1).waitFor();
46142
+ await poperInstance.nth(1).click();
46143
+ task.logger.info("地点选择完成");
46144
+ }
46145
+ if (params.collection) {
46146
+ task.logger.info(`选择合集: ${params.collection.collectionName}`);
46147
+ const instanceCollection = page.locator(".post-album-display-wrap");
46148
+ await instanceCollection.click();
46149
+ await page.waitForTimeout(1000);
46150
+ page.locator(".post-album-wrap .option-item").filter({
46151
+ hasText: params.collection.collectionName
46152
+ }).first().click({
46153
+ force: true
46154
+ });
46155
+ }
46156
+ if (params.link) {
46157
+ task.logger.info(`设置扩展阅读链接: ${params.link.title}`);
46158
+ await page.locator(".post-link-wrap .link-display-wrap").click();
46159
+ await page.waitForTimeout(300);
46160
+ const linkTypeText = 2 === params.link.urlType ? "红包封面" : "公众号文章";
46161
+ await page.locator(".link-option-item .title-wrap span").filter({
46162
+ hasText: linkTypeText
46163
+ }).click();
46164
+ await page.waitForTimeout(300);
46165
+ const placeholder = 2 === params.link.urlType ? "粘贴红包封面链接" : "粘贴公众号文章链接";
46166
+ await page.locator(`.link-input-wrap input[placeholder="${placeholder}"]`).fill(params.link.link);
46167
+ await page.waitForTimeout(500);
46168
+ task.logger.info(`已设置${linkTypeText}: ${params.link.link}`);
46169
+ }
46170
+ if (params.event) {
46171
+ task.logger.info(`选择活动: ${params.event.eventName}`);
46172
+ await page.locator(".post-activity-wrap .activity-display").click();
46173
+ await page.waitForTimeout(500);
46174
+ await page.locator(".activity-filter-wrap .weui-desktop-form__input[placeholder='搜索活动']").fill(params.event.eventName);
46175
+ await page.waitForTimeout(500);
46176
+ const searchLoading = page.locator(".search-loading");
46177
+ await searchLoading.waitFor({
46178
+ state: "hidden",
46179
+ timeout: 5000
46180
+ }).catch(()=>{
46181
+ task.logger.warn("活动搜索加载超时,继续尝试选择");
46182
+ });
46183
+ const activityItem = page.locator(".option-item .activity-item .activity-item-info .name").filter({
46184
+ hasText: params.event.eventName
46185
+ });
46186
+ const count = await activityItem.count();
46187
+ if (count > 0) {
46188
+ await activityItem.first().click();
46189
+ await page.waitForTimeout(300);
46190
+ task.logger.info(`已选择活动: ${params.event.eventName}`);
46191
+ } else {
46192
+ task.logger.warn(`未找到活动: ${params.event.eventName},将不参与活动`);
46193
+ await page.locator(".post-activity-wrap .activity-display").click();
46194
+ await page.waitForTimeout(300);
46195
+ }
46196
+ }
46197
+ if (params.scheduledTime) {
46198
+ task.logger.info("设置定时发布");
46199
+ const timingRadio = page.locator(".weui-desktop-form__check-label").filter({
46200
+ hasNotText: "不定时"
46201
+ }).first();
46202
+ await timingRadio.click();
46203
+ await page.waitForTimeout(500);
46204
+ const instance = page.locator(".weui-desktop-picker__date");
46205
+ await instance.click();
46206
+ const dateD = utils_TimeFormatter.format(1000 * params.scheduledTime, "d");
46207
+ const nowMonth = utils_TimeFormatter.format(Date.now(), "MM月");
46208
+ const nowMonthText = utils_TimeFormatter.format(Date.now(), "M月");
46209
+ const month = utils_TimeFormatter.format(1000 * params.scheduledTime, "MM月");
46210
+ const monthLocator = await page.locator("weui-desktop-picker__panel__label").filter({
46211
+ hasText: month
46212
+ }).first();
46213
+ if (!monthLocator) {
46214
+ await page.locator(".weui-desktop-picker__panel__label").filter({
46215
+ hasText: nowMonth
46216
+ }).first().click();
46217
+ await page.waitForTimeout(500);
46218
+ await page.locator(".weui-desktop-picker__table-row td a").filter({
46219
+ hasText: nowMonthText
46220
+ }).first().click();
46221
+ }
46222
+ await page.waitForTimeout(500);
46223
+ await page.locator(".weui-desktop-picker__table-row td a").filter({
46224
+ hasText: dateD
46225
+ }).first().click();
46226
+ await page.locator(".weui-desktop-form__input-wrp input[placeholder*='请选择时间']").fill(utils_TimeFormatter.format(1000 * params.scheduledTime, "hh:mm"));
46227
+ await page.locator("i.weui-desktop-icon__time").click();
46228
+ await page.locator(".post-time-wrap .form-item .label").filter({
46229
+ hasText: "发表时间"
46230
+ }).click();
46231
+ }
46232
+ if (params.tagInfo) {
46233
+ task.logger.info(`设置视频标注: tagType=${params.tagInfo.tagType}`);
46234
+ await page.locator(".mark-tag-select").click();
46235
+ await page.waitForTimeout(300);
46236
+ const tagTypeTextMap = {
46237
+ 0: "无需标注",
46238
+ 1: "含AI生成内容",
46239
+ 2: "内容包含营销广告",
46240
+ 3: "内容为虚构剧情,仅供娱乐",
46241
+ 5: "内容为自行拍摄",
46242
+ 7: "内容为转载",
46243
+ 8: "个人观点,仅供参考"
46244
+ };
46245
+ const tagText = tagTypeTextMap[params.tagInfo.tagType];
46246
+ if (tagText) {
46247
+ await page.locator(".mark-tag-option .option-main").filter({
46248
+ hasText: tagText
46249
+ }).click();
46250
+ await page.waitForTimeout(300);
46251
+ if (5 === params.tagInfo.tagType) {
46252
+ const shootInfo = params.tagInfo.shootInfo;
46253
+ if (shootInfo) {
46254
+ task.logger.info("填写拍摄时间和地点...");
46255
+ await page.waitForTimeout(500);
46256
+ if (shootInfo.postTimestamp) {
46257
+ task.logger.info(`设置拍摄时间: ${shootInfo.postTimestamp}`);
46258
+ const timestamp = 1000 * parseInt(shootInfo.postTimestamp, 10);
46259
+ const date = new Date(timestamp);
46260
+ await page.locator(".original-dialog-content .weui-desktop-picker__date input[placeholder*='请选择拍摄时间']").click();
46261
+ await page.waitForTimeout(300);
46262
+ const dayNum = date.getDate();
46263
+ await page.locator(".weui-desktop-picker__table a").filter({
46264
+ hasText: new RegExp(`^\\s*${dayNum}\\s*$`)
46265
+ }).first().click();
46266
+ await page.waitForTimeout(300);
46267
+ }
46268
+ if (shootInfo.countryCode || shootInfo.provinceCode || shootInfo.cityCode) {
46269
+ task.logger.info("设置拍摄地点...");
46270
+ await page.locator(".original-dialog-content .weui-desktop-form__dropdowncascade .weui-desktop-form__dropdowncascade__dt").click();
46271
+ await page.waitForTimeout(300);
46272
+ if (1156 === shootInfo.countryCode) {
46273
+ await page.locator(".weui-desktop-dropdown__list-ele .weui-desktop-dropdown__list-ele__text").filter({
46274
+ hasText: "中国"
46275
+ }).click();
46276
+ await page.waitForTimeout(300);
46277
+ task.logger.warn("RPA 模式下暂不支持选择具体省份和城市,仅选择了国家");
46278
+ } else task.logger.warn(`不支持的国家代码: ${shootInfo.countryCode},跳过地点设置`);
46279
+ }
46280
+ const confirmBtn = await waitForElement(".weui-desktop-dialog .weui-desktop-btn_primary");
46281
+ if (confirmBtn) {
46282
+ await confirmBtn.click();
46283
+ await page.waitForTimeout(300);
46284
+ }
46285
+ } else task.logger.warn("tagType=5 需要提供 shootInfo 字段(拍摄时间和地点)");
46286
+ }
46287
+ if (7 === params.tagInfo.tagType) {
46288
+ const repostSource = params.tagInfo.repostSource;
46289
+ if (repostSource) {
46290
+ task.logger.info(`填写转载来源: ${repostSource}`);
46291
+ await page.waitForTimeout(500);
46292
+ await page.locator(".repost-dialog-content .repost-textarea").fill(repostSource);
46293
+ await page.waitForTimeout(300);
46294
+ const confirmBtn = await waitForElement(".weui-desktop-dialog .weui-desktop-btn_primary");
46295
+ if (confirmBtn) {
46296
+ await confirmBtn.click();
46297
+ await page.waitForTimeout(300);
46298
+ }
46299
+ } else task.logger.warn("tagType=7 需要提供 repostSource 字段(转载来源)");
46300
+ }
46301
+ } else task.logger.warn(`未知的 tagType: ${params.tagInfo.tagType},跳过标注设置`);
46302
+ }
46303
+ task.logger.info("准备发布...");
46304
+ await page.waitForTimeout(500);
46305
+ let videoId = "";
46306
+ const handleResponse = async (response)=>{
46307
+ const url = response.url();
46308
+ if (url.includes("/post/post_create")) {
46309
+ const jsonResponse = await response.json();
46310
+ page.off("response", handleResponse);
46311
+ videoId = jsonResponse.object?.id || jsonResponse.data?.objectId || "";
46312
+ }
46313
+ };
46314
+ page.on("response", handleResponse);
46315
+ task._timerRecord.PrePublish = Date.now();
46316
+ const MEDIA_OPR_SELECTOR = "#container-wrap > div.container-center > div > div > div.main-body-wrap.post-create > div.main-body > div > div.post-edit-wrap.material-edit-wrap > div.material > div.preview > div > div.media-opr > div > span > div > div > div";
46317
+ task.logger.info("等待视频上传完成(预览区媒体操作栏出现)...");
46318
+ const uploadTimeout = 600000;
46319
+ const uploadWaitStart = Date.now();
46320
+ let lastProgressLog = 0;
46321
+ while(true){
46322
+ const ready = await page.evaluate((selector)=>{
46323
+ const host = document.querySelector("#container-wrap > div.container-center > div > wujie-app");
46324
+ const root = host?.shadowRoot;
46325
+ if (!root) return false;
46326
+ return !!root.querySelector(selector);
46327
+ }, MEDIA_OPR_SELECTOR);
46328
+ if (ready) break;
46329
+ const elapsed = Date.now() - uploadWaitStart;
46330
+ if (elapsed > uploadTimeout) throw new Error(`视频上传超时,预览区未就绪(已等待 ${Math.round(elapsed / 1000)}s)`);
46331
+ if (elapsed - lastProgressLog >= 15000) {
46332
+ lastProgressLog = elapsed;
46333
+ task.logger.info(`视频仍在上传中... 已等待 ${Math.round(elapsed / 1000)}s`);
46334
+ }
46335
+ await page.waitForTimeout(1000);
46336
+ }
46337
+ task.logger.info(`视频上传完成(等待 ${Math.round((Date.now() - uploadWaitStart) / 1000)}s)`);
46338
+ const clicked = await page.evaluate(()=>{
46339
+ const host = document.querySelector("#container-wrap > div.container-center > div > wujie-app");
46340
+ const root = host?.shadowRoot;
46341
+ if (!root) return "未找到 wujie-app shadowRoot";
46342
+ const btns = Array.from(root.querySelectorAll(".form-btns .weui-desktop-btn"));
46343
+ const target = btns.find((el)=>(el.textContent || "").includes("发表"));
46344
+ if (!target) return "未找到发表按钮";
46345
+ if (target.classList.contains("weui-desktop-btn_disabled")) return "发表按钮仍处于禁用状态";
46346
+ target.click();
46347
+ return null;
46348
+ });
46349
+ if (clicked) throw new Error(clicked);
46350
+ task.logger.info("已点击发布按钮,等待响应...");
46351
+ try {
46352
+ await page.waitForURL((url)=>url.href !== page.url(), {
46353
+ timeout: 30000
46354
+ });
46355
+ task.logger.info(`发布成功,页面已跳转: ${page.url()}`);
46356
+ } catch {
46357
+ task.logger.warn("等待页面跳转超时,可能发布失败或网络慢,继续关闭页面");
46358
+ }
46359
+ await page.close();
46360
+ return success(videoId, "发布成功");
46361
+ } catch (error) {
46362
+ let errorMsg = error instanceof Error ? error.message : String(error);
46363
+ if (errorMsg.includes("context or browser has been closed")) errorMsg = "浏览器上下文已被关闭";
46364
+ task.logger.error(`微信视频号视频发布失败: ${errorMsg}`);
46365
+ return utils_response(414, `微信视频号视频发布失败: ${errorMsg}`, "");
46366
+ }
46367
+ };
46368
+ const ShipinhaoPublishVideoParamsSchema = ActionCommonParamsSchema.extend({
46369
+ videoPath: classic_schemas_string().min(1),
46370
+ videoMetadata: classic_schemas_object({
46371
+ duration: classic_schemas_number().positive(),
46372
+ width: classic_schemas_number().int().positive(),
46373
+ height: classic_schemas_number().int().positive(),
46374
+ fileSize: classic_schemas_number().int().positive(),
46375
+ path: classic_schemas_string().min(1).optional(),
46376
+ fileName: classic_schemas_string().min(1)
46377
+ }),
46378
+ coverPath: classic_schemas_string().min(1),
46379
+ verticalCoverPath: classic_schemas_string().min(1).optional(),
46380
+ description: classic_schemas_string(),
46381
+ title: classic_schemas_string().optional(),
46382
+ scheduledTime: classic_schemas_number().int().positive().optional(),
46383
+ isImmediatelyPublish: classic_schemas_boolean().optional(),
46384
+ topics: classic_schemas_array(classic_schemas_string()).optional(),
46385
+ mentionedUsers: classic_schemas_array(classic_schemas_object({
46386
+ nickname: classic_schemas_string()
46387
+ })).optional(),
46388
+ collection: classic_schemas_object({
46389
+ collectionId: classic_schemas_string(),
46390
+ collectionName: classic_schemas_string()
46391
+ }).optional(),
46392
+ event: classic_schemas_object({
46393
+ eventTopicId: classic_schemas_string(),
46394
+ eventName: classic_schemas_string(),
46395
+ eventCreatorNickname: classic_schemas_string().optional()
46396
+ }).optional(),
46397
+ link: classic_schemas_object({
46398
+ link: classic_schemas_string(),
46399
+ title: classic_schemas_string(),
46400
+ urlType: classic_schemas_number().int().default(1)
46401
+ }).optional(),
46402
+ tagInfo: looseObject({
46403
+ tagType: classic_schemas_number().int()
46404
+ }).optional(),
46405
+ originalFlag: schemas_union([
46406
+ literal(0),
46407
+ literal(1)
46408
+ ]).optional(),
46409
+ postWithMemberZoneLink: schemas_union([
46410
+ literal(0),
46411
+ literal(1)
46412
+ ]).optional(),
46413
+ location: classic_schemas_object({
46414
+ latitude: classic_schemas_number(),
46415
+ longitude: classic_schemas_number(),
46416
+ city: classic_schemas_string(),
46417
+ poiName: classic_schemas_string().optional(),
46418
+ address: classic_schemas_string().optional(),
46419
+ poiClassifyId: classic_schemas_string().optional()
46420
+ }).optional()
46421
+ });
46422
+ const shipinhaoPublishVideo = async (task, params)=>{
46423
+ task.logger.info(`[shipinhaoPublishVideo] actionType: ${params.actionType}`);
46424
+ if ("rpa" === params.actionType) return shipinhaoPublishVideo_rpa_rpaAction(task, params);
46425
+ if ("mockApi" === params.actionType) return shipinhaoPublishVideo_mock_mockAction(task, params);
46426
+ return executeAction(shipinhaoPublishVideo_mock_mockAction, shipinhaoPublishVideo_rpa_rpaAction)(task, params);
46427
+ };
44590
46428
  const ShipinhaoSendMsgParamsSchema = ActionCommonParamsSchema.extend({
44591
46429
  toUsername: classic_schemas_string().min(1, "接收者用户名不能为空"),
44592
46430
  sessionId: classic_schemas_string().min(1, "会话ID不能为空"),
@@ -44601,7 +46439,7 @@ var __webpack_exports__ = {};
44601
46439
  pathOrUrl: classic_schemas_string().min(1, "图片路径或URL不能为空")
44602
46440
  }).optional()
44603
46441
  });
44604
- const CHUNK_SIZE = 524288;
46442
+ const shipinhaoSendMsg_CHUNK_SIZE = 524288;
44605
46443
  async function shipinhaoSendMsg_getUserInfo(cookieStr, http) {
44606
46444
  const url = `https://channels.weixin.qq.com/cgi-bin/mmfinderassistant-bin/auth/auth_data?_rid=${rid()}`;
44607
46445
  const headers = {
@@ -44679,15 +46517,16 @@ var __webpack_exports__ = {};
44679
46517
  imageBuffer = Buffer.from(await external_node_fs_default().promises.readFile(filePath));
44680
46518
  }
44681
46519
  } catch (err) {
44682
- return utils_response(414, `读取图片失败: ${err instanceof Error ? err.message : String(err)}`, void 0);
46520
+ _task.logger.error(`读取图片失败: ${err instanceof Error ? err.message : String(err)}`);
46521
+ return utils_response(414, USER_MESSAGE.IMAGE_UPLOAD_FAILED, void 0);
44683
46522
  }
44684
46523
  const md5 = (0, external_node_crypto_namespaceObject.createHash)("md5").update(imageBuffer).digest("hex");
44685
46524
  const timestamp = Date.now().toString();
44686
- const totalChunks = Math.ceil(imageBuffer.length / CHUNK_SIZE);
46525
+ const totalChunks = Math.ceil(imageBuffer.length / shipinhaoSendMsg_CHUNK_SIZE);
44687
46526
  console.log(`分片上传md5${md5}`);
44688
46527
  let lastRes;
44689
46528
  for(let i = 0; i < totalChunks; i++){
44690
- const chunkBuffer = imageBuffer.slice(i * CHUNK_SIZE, (i + 1) * CHUNK_SIZE);
46529
+ const chunkBuffer = imageBuffer.slice(i * shipinhaoSendMsg_CHUNK_SIZE, (i + 1) * shipinhaoSendMsg_CHUNK_SIZE);
44691
46530
  const requestData = {
44692
46531
  content: `data:application/octet-stream;base64,${chunkBuffer.toString("base64")}`,
44693
46532
  chunk: i,
@@ -45140,6 +46979,13 @@ var __webpack_exports__ = {};
45140
46979
  const uploadImages = async (images)=>await Promise.all(images.map(async (url)=>{
45141
46980
  const fileName = getFilenameFromUrl(url);
45142
46981
  const image = await downloadImage(url, external_node_path_default().join(tmpCachePath, fileName));
46982
+ const stats = external_node_fs_default().statSync(image);
46983
+ const maxSize = 20971520;
46984
+ if (stats.size > maxSize) throw {
46985
+ code: 414,
46986
+ message: "头条号平台:单张图片不得超过 20MB",
46987
+ data: ""
46988
+ };
45143
46989
  const formData = new (form_data_default())();
45144
46990
  formData.append("image", external_node_fs_default().createReadStream(image));
45145
46991
  const response = await http.api({
@@ -47190,18 +49036,10 @@ var __webpack_exports__ = {};
47190
49036
  });
47191
49037
  } catch (error) {
47192
49038
  const handledError = Http.handleApiError(error);
47193
- const isProxyOrNetworkError = [
47194
- 599,
47195
- 500,
47196
- 502,
47197
- 503,
47198
- 504
47199
- ].includes(handledError.code);
47200
- if (isProxyOrNetworkError) {
47201
- const isProxyRequest = handledError.extra?.isProxyRequest === true;
47202
- const errorType = 599 === handledError.code || isProxyRequest ? "代理错误" : "网络错误";
47203
- const message = `文章发布失败,${errorType}:${handledError.message}${task.debug ? ` ${http.proxyInfo}` : ""}`;
47204
- task.logger.error(`[weixinPublish] ${errorType},直接返回: ${message}`, stringifyError(handledError));
49039
+ const classified = classifyPublishError(handledError);
49040
+ if (classified) {
49041
+ const message = `${classified.userMessage}${task.debug ? ` ${http.proxyInfo}` : ""}`;
49042
+ task.logger.error(`[weixinPublish] ${classified.category},直接返回: ${handledError.message} (code=${handledError.code})`, stringifyError(handledError));
47205
49043
  await updateTaskState?.({
47206
49044
  state: types_TaskState.FAILED,
47207
49045
  error: message
@@ -48431,6 +50269,12 @@ var __webpack_exports__ = {};
48431
50269
  const fileName = getFilenameFromUrl(url);
48432
50270
  const localUrl = await downloadImage(url, external_node_path_default().join(tmpCachePath, fileName));
48433
50271
  const fileBuffer = external_node_fs_default().readFileSync(localUrl);
50272
+ const maxSize = 33554432;
50273
+ if (fileBuffer.byteLength > maxSize) throw {
50274
+ code: 414,
50275
+ message: "小红书平台:单张图片不得超过 32MB",
50276
+ data: ""
50277
+ };
48434
50278
  let width = 0;
48435
50279
  let height = 0;
48436
50280
  try {
@@ -48669,6 +50513,7 @@ var __webpack_exports__ = {};
48669
50513
  });
48670
50514
  return success(data, message);
48671
50515
  }
50516
+ task.logger.info(`[xiaohongshuPublish] publishData: ${JSON.stringify(publishData)} `);
48672
50517
  let publishResult;
48673
50518
  try {
48674
50519
  publishResult = await proxyHttp.api({
@@ -48679,23 +50524,15 @@ var __webpack_exports__ = {};
48679
50524
  defaultErrorMsg: "文章发布异常,请稍后重试。"
48680
50525
  }, {
48681
50526
  retries: 2,
48682
- retryDelay: 500,
48683
- timeout: 12000
50527
+ retryDelay: 3000,
50528
+ timeout: 30000
48684
50529
  });
48685
50530
  } catch (error) {
48686
50531
  const handledError = Http.handleApiError(error);
48687
- const isProxyOrNetworkError = [
48688
- 599,
48689
- 500,
48690
- 502,
48691
- 503,
48692
- 504
48693
- ].includes(handledError.code);
48694
- if (isProxyOrNetworkError) {
48695
- const isProxyRequest = handledError.extra?.isProxyRequest === true;
48696
- const errorType = 599 === handledError.code || isProxyRequest ? "代理错误" : "网络错误";
48697
- const message = `文章发布失败,${errorType}:${handledError.message}${task.debug ? ` ${http.proxyInfo}` : ""}`;
48698
- task.logger.error(`[xiaohongshuPublish] ${errorType},直接返回: ${message}`, stringifyError(handledError));
50532
+ const classified = classifyPublishError(handledError);
50533
+ if (classified) {
50534
+ const message = `${classified.userMessage}${task.debug ? ` ${http.proxyInfo}` : ""}`;
50535
+ task.logger.error(`[xiaohongshuPublish] ${classified.category},直接返回: ${handledError.message} (code=${handledError.code})`, stringifyError(handledError));
48699
50536
  await updateTaskState?.({
48700
50537
  state: types_TaskState.FAILED,
48701
50538
  error: message
@@ -50391,6 +52228,14 @@ var __webpack_exports__ = {};
50391
52228
  this.task = task;
50392
52229
  this.task.logger.info(`当前包版本:Share=>${package_namespaceObject.i8} Action=>${package_namespaceObject_0.i8}`);
50393
52230
  }
52231
+ getActionVersionMarker() {
52232
+ return {
52233
+ version: package_namespaceObject_0.i8,
52234
+ shareVersion: package_namespaceObject.i8,
52235
+ marker: `Action_${package_namespaceObject_0.i8}_${package_namespaceObject.i8}`,
52236
+ timestamp: new Date().toLocaleString()
52237
+ };
52238
+ }
50394
52239
  async bindTask(func, params) {
50395
52240
  let responseData;
50396
52241
  this.task.isBeta = this.task?.isFeatOn ? this.task?.isFeatOn(BetaFlag) : false;
@@ -50614,6 +52459,9 @@ var __webpack_exports__ = {};
50614
52459
  shipinhaoPublish(params) {
50615
52460
  return this.bindTask(shipinhaoPublish, params);
50616
52461
  }
52462
+ shipinhaoPublishVideo(params) {
52463
+ return this.bindTask(shipinhaoPublishVideo, params);
52464
+ }
50617
52465
  douyinGetTopics(params) {
50618
52466
  return this.bindTask(douyinGetTopics, params);
50619
52467
  }
@@ -50674,4 +52522,4 @@ if (__webpack_exports__.__esModule) Object.defineProperty(__webpack_export_targe
50674
52522
  });
50675
52523
 
50676
52524
  //# sourceMappingURL=bundle.js.map
50677
- //# debugId=1b1757c5-d32a-56c9-a781-bb1e22dcee63
52525
+ //# debugId=51f3980f-4908-5c61-864e-675122bae629