@iflyrpa/actions 4.0.9 → 4.1.0-beta.0

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]="6fdb1841-1467-5c52-bdfa-6acbd4df3bcb")}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.0"}');
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,124 @@ 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 postFeishuWebhook = (webhookUrl, payload)=>lib_axios.post(webhookUrl, payload, {
27077
+ headers: {
27078
+ "Content-Type": "application/json"
27079
+ },
27080
+ timeout: 10000
27081
+ });
27082
+ const buildFeishuPostMessage = (report)=>{
27083
+ const content = [
27084
+ [
27085
+ {
27086
+ tag: "text",
27087
+ text: `平台:${report.platform || "未知平台"}`
27088
+ }
27089
+ ],
27090
+ [
27091
+ {
27092
+ tag: "text",
27093
+ text: `错误信息:${report.msg || "未知错误信息"}`
27094
+ }
27095
+ ],
27096
+ [
27097
+ {
27098
+ tag: "text",
27099
+ text: `错误类型:${report.errorType || "未知错误类型"}`
27100
+ }
27101
+ ],
27102
+ [
27103
+ {
27104
+ tag: "text",
27105
+ text: `阶段:${report.stage || "未知阶段"}`
27106
+ }
27107
+ ],
27108
+ [
27109
+ {
27110
+ tag: "text",
27111
+ text: `等级:${report.level}`
27112
+ }
27113
+ ],
27114
+ [
27115
+ {
27116
+ tag: "text",
27117
+ text: `来源:${report.source}`
27118
+ }
27119
+ ]
27120
+ ];
27121
+ if (void 0 !== report.code && null !== report.code) content.push([
27122
+ {
27123
+ tag: "text",
27124
+ text: `接口错误码:${report.code}`
27125
+ }
27126
+ ]);
27127
+ if (report.url) content.push([
27128
+ {
27129
+ tag: "text",
27130
+ text: `地址:${report.url}`
27131
+ }
27132
+ ]);
27133
+ if ("alarm" === report.level) content.push([
27134
+ {
27135
+ tag: "at",
27136
+ user_id: "all"
27137
+ }
27138
+ ]);
27139
+ return {
27140
+ msg_type: "post",
27141
+ content: {
27142
+ post: {
27143
+ zh_cn: {
27144
+ title: report.title || "RPA异常",
27145
+ content
27146
+ }
27147
+ }
27148
+ }
27149
+ };
27150
+ };
27151
+ const reportFeishuAlarm = (report)=>{
27152
+ try {
27153
+ const key = `${report.platform}|${report.source}|${report.errorType}|${report.code ?? ""}`;
27154
+ const now = Date.now();
27155
+ const last = lastSentAt.get(key);
27156
+ if (last && now - last < ALARM_THROTTLE_MS) return;
27157
+ lastSentAt.set(key, now);
27158
+ postFeishuWebhook(RPA_ERROR_WEBHOOK_URL, buildFeishuPostMessage(report)).catch(()=>{});
27159
+ } catch {}
27160
+ };
27044
27161
  var dist = __webpack_require__("../../node_modules/.pnpm/socks-proxy-agent@8.0.4/node_modules/socks-proxy-agent/dist/index.js");
27045
27162
  const PROXY_CREDENTIALS = [
27046
27163
  {
@@ -27143,9 +27260,20 @@ var __webpack_exports__ = {};
27143
27260
  url: "https://fetdev.iflysec.com/ip-pool/pool/eip/proxy",
27144
27261
  data: params
27145
27262
  }).catch((err)=>{
27263
+ reportFeishuAlarm({
27264
+ level: "alarm",
27265
+ platform: "ip-pool",
27266
+ source: "proxy",
27267
+ stage: "POST /ip-pool/pool/eip/proxy",
27268
+ errorType: "PROXY_REQUEST_FAILED",
27269
+ code: err?.code,
27270
+ msg: `请求代理失败:${err.message},区域:${addr ?? "-"},AccountId:${accountId ?? "-"}`,
27271
+ url: "https://fetdev.iflysec.com/ip-pool/pool/eip/proxy",
27272
+ title: "代理异常"
27273
+ });
27146
27274
  throw {
27147
27275
  code: 414,
27148
- message: `请求代理失败:${err.message}`,
27276
+ message: USER_MESSAGE.PROXY_UNAVAILABLE,
27149
27277
  data: {}
27150
27278
  };
27151
27279
  });
@@ -27165,12 +27293,53 @@ var __webpack_exports__ = {};
27165
27293
  } : null;
27166
27294
  return proxyAgent;
27167
27295
  }
27296
+ const ALARM_STATUS = new Set([
27297
+ 401,
27298
+ 403,
27299
+ 429,
27300
+ 461,
27301
+ 471
27302
+ ]);
27303
+ const HTTP_STATUS_MESSAGE = {
27304
+ 400: "请求参数错误,请检查参数格式是否正确!",
27305
+ 401: "登录状态已失效,请重新登录后重试!",
27306
+ 403: "没有访问权限,账号可能受限或签名已失效!",
27307
+ 404: "请求的资源不存在,请检查接口地址!",
27308
+ 405: "请求方法不被允许,请检查接口调用方式!",
27309
+ 406: "服务端无法返回可接受的内容格式!",
27310
+ 407: "代理需要身份验证,请检查代理配置!",
27311
+ 408: "请求超时,请检查网络连接!",
27312
+ 409: "请求冲突,资源状态已变更,请刷新后重试!",
27313
+ 410: "请求的资源已被移除!",
27314
+ 412: "请求前置条件不满足,请刷新后重试!",
27315
+ 413: "提交内容过大,请压缩或分批后重试!",
27316
+ 414: "请求地址过长,请检查参数!",
27317
+ 415: "不支持的内容类型,请检查请求格式!",
27318
+ 422: "请求内容校验失败,请检查参数内容!",
27319
+ 423: "资源已被锁定,请稍后重试!",
27320
+ 429: "请求过于频繁,请稍后重试!",
27321
+ 431: "请求头过大,请清理 Cookie 后重试!",
27322
+ 451: "内容不合规或因法律原因被拒绝!",
27323
+ 461: "账号可能受限,请在网页上完成验证后重试!",
27324
+ 471: "账号可能受限,请在网页上完成验证后重试!",
27325
+ 500: "服务器内部错误,请稍后重试!",
27326
+ 501: "服务端不支持该请求,请稍后重试!",
27327
+ 502: "网关错误,请稍后重试!",
27328
+ 503: "服务暂时不可用,请稍后重试!",
27329
+ 504: "网关超时,请稍后重试!",
27330
+ 507: "服务端存储空间不足,请稍后重试!",
27331
+ 509: "服务带宽超限,请稍后重试!",
27332
+ 520: "服务端返回未知错误,请稍后重试!",
27333
+ 521: "源站拒绝连接,请稍后重试!",
27334
+ 522: "源站连接超时,请稍后重试!",
27335
+ 524: "源站响应超时,请稍后重试!"
27336
+ };
27168
27337
  class Http {
27169
27338
  static handleApiError(error) {
27170
27339
  if (error && "object" == typeof error && "code" in error && "message" in error) return error;
27171
27340
  return {
27172
27341
  code: 500,
27173
- message: error instanceof Error ? error.message : "未知错误",
27342
+ message: USER_MESSAGE.SYSTEM_ERROR,
27174
27343
  data: error
27175
27344
  };
27176
27345
  }
@@ -27225,6 +27394,18 @@ var __webpack_exports__ = {};
27225
27394
  const verifyDecision = error.response?.headers?.["x-tt-verify-passport-decision"];
27226
27395
  if (verifyDecision) this.logger?.warn(`[403 验证决策] x-tt-verify-passport-decision: ${verifyDecision}`);
27227
27396
  }
27397
+ if (error.response?.status === 461 || error.response?.status === 471) {
27398
+ const h = error.response?.headers ?? {};
27399
+ const pick = (name)=>h[name] ?? h[name.toLowerCase()];
27400
+ this.logger?.warn(`[${error.response.status} 风控验证] URL: ${error.config?.url} Verifytype: ${pick("Verifytype") ?? "-"} Verifyuuid: ${pick("Verifyuuid") ?? "-"} Verifybiz: ${pick("Verifybiz") ?? "-"}`);
27401
+ this.logger?.warn(`[${error.response.status} 响应头] ${JSON.stringify(h)}`);
27402
+ errorResponse.extra = {
27403
+ ...errorResponse.extra,
27404
+ verifyType: pick("Verifytype"),
27405
+ verifyUuid: pick("Verifyuuid"),
27406
+ verifyBiz: pick("Verifybiz")
27407
+ };
27408
+ }
27228
27409
  if (error.response?.data) {
27229
27410
  if ("object" == typeof error.response.data) {
27230
27411
  const serverError = error.response.data;
@@ -27255,11 +27436,17 @@ var __webpack_exports__ = {};
27255
27436
  _message = "DNS 查询超时,请稍后重试!";
27256
27437
  break;
27257
27438
  case "ERR_BAD_REQUEST":
27258
- _message = "请求出现错误,请检查请求参数!";
27259
- break;
27439
+ {
27440
+ const status = error.response?.status;
27441
+ _message = status && HTTP_STATUS_MESSAGE[status] || `请求失败,状态码${status ?? "unknown"}!`;
27442
+ break;
27443
+ }
27260
27444
  case "ERR_BAD_RESPONSE":
27261
- _message = `服务器响应异常 (${error.response?.status ?? "unknown"}),请稍后重试!`;
27262
- break;
27445
+ {
27446
+ const status = error.response?.status;
27447
+ _message = status && HTTP_STATUS_MESSAGE[status] || `服务器响应异常 (${status ?? "unknown"}),请稍后重试!`;
27448
+ break;
27449
+ }
27263
27450
  case "ERR_CANCELED":
27264
27451
  errorResponse.code = 414;
27265
27452
  _message = "请求连接超时,请稍候重试!";
@@ -27270,11 +27457,14 @@ var __webpack_exports__ = {};
27270
27457
  }
27271
27458
  break;
27272
27459
  default:
27273
- this.logger?.debug(`未处理的网络错误代码: ${error.code} ${error.message}`, {
27274
- errorString: stringifyError(error)
27275
- });
27276
- _message = `网络错误: ${error.message}`;
27277
- break;
27460
+ {
27461
+ this.logger?.debug(`未处理的网络错误代码: ${error.code} ${error.message}`, {
27462
+ errorString: stringifyError(error)
27463
+ });
27464
+ const status = error.response?.status;
27465
+ _message = status && HTTP_STATUS_MESSAGE[status] || USER_MESSAGE.NETWORK_ERROR;
27466
+ break;
27467
+ }
27278
27468
  }
27279
27469
  }
27280
27470
  if (error.code && !error.response?.data) errorResponse.message = _message || errorResponse.message;
@@ -27284,29 +27474,51 @@ var __webpack_exports__ = {};
27284
27474
  errorResponse.message = message;
27285
27475
  }
27286
27476
  if (error.message.includes("Proxy connection ended")) errorResponse.message = "所在区域代理连接超时,请更换区域或稍后重试!";
27477
+ const status = error.response?.status;
27478
+ reportFeishuAlarm({
27479
+ level: status && ALARM_STATUS.has(status) ? "alarm" : "warning",
27480
+ platform: this.platform || "unknown",
27481
+ source: "http",
27482
+ stage: `${(error.config?.method || "get").toUpperCase()} ${error.config?.url || "-"}`,
27483
+ errorType: status ? `HTTP_${status}` : error.code || "NETWORK_ERROR",
27484
+ code: errorResponse.code,
27485
+ msg: errorResponse.message,
27486
+ url: error.config?.url,
27487
+ title: "RPA接口异常"
27488
+ });
27287
27489
  throw errorResponse;
27288
27490
  });
27289
27491
  }
27290
27492
  async api(config, options) {
27291
27493
  const retries = options?.retries ?? 0;
27292
27494
  const retryDelay = options?.retryDelay ?? 500;
27293
- const reqTimeout = options?.timeout ?? 30000;
27495
+ const reqTimeout = options?.timeout ?? 60000;
27496
+ const externalSignal = options?.signal;
27294
27497
  let agent;
27295
27498
  const sessionRt = async (Rtimes)=>{
27296
27499
  try {
27297
27500
  this.proxyInfo = agent ? `${agent.ip}:${agent.port}` : void 0;
27298
27501
  const controller = new AbortController();
27299
27502
  const timeoutId = setTimeout(()=>controller.abort(), reqTimeout + 500);
27503
+ const forwardAbort = ()=>controller.abort();
27504
+ if (externalSignal) {
27505
+ if (externalSignal.aborted) controller.abort();
27506
+ else externalSignal.addEventListener("abort", forwardAbort, {
27507
+ once: true
27508
+ });
27509
+ }
27300
27510
  const response = await this.apiClient({
27301
27511
  ...config,
27302
27512
  timeout: reqTimeout,
27303
27513
  signal: controller.signal,
27514
+ onUploadProgress: options?.onUploadProgress,
27304
27515
  ...agent ? {
27305
27516
  httpAgent: agent.agent,
27306
27517
  httpsAgent: agent.agent
27307
27518
  } : {}
27308
27519
  }).finally(()=>{
27309
27520
  clearTimeout(timeoutId);
27521
+ externalSignal?.removeEventListener("abort", forwardAbort);
27310
27522
  });
27311
27523
  return response.data;
27312
27524
  } catch (error) {
@@ -32015,6 +32227,14 @@ var __webpack_exports__ = {};
32015
32227
  };
32016
32228
  return new schemas_ZodObject(def);
32017
32229
  }
32230
+ function looseObject(shape, params) {
32231
+ return new schemas_ZodObject({
32232
+ type: "object",
32233
+ shape,
32234
+ catchall: schemas_unknown(),
32235
+ ...util_normalizeParams(params)
32236
+ });
32237
+ }
32018
32238
  const schemas_ZodUnion = /*@__PURE__*/ core_$constructor("ZodUnion", (inst, def)=>{
32019
32239
  schemas_$ZodUnion.init(inst, def);
32020
32240
  schemas_ZodType.init(inst, def);
@@ -32711,6 +32931,13 @@ var __webpack_exports__ = {};
32711
32931
  data: ""
32712
32932
  };
32713
32933
  const image = await downloadImage(url, external_node_path_default().join(tmpCachePath, fileName));
32934
+ const stats = external_node_fs_default().statSync(image);
32935
+ const maxSize = 5242880;
32936
+ if (stats.size > maxSize) throw {
32937
+ code: 414,
32938
+ message: "百家号平台:单张图片不得超过 5MB",
32939
+ data: ""
32940
+ };
32714
32941
  const formData = new (form_data_default())();
32715
32942
  formData.append("org_file_name", fileName);
32716
32943
  formData.append("type", "image");
@@ -36543,7 +36770,7 @@ var __webpack_exports__ = {};
36543
36770
  });
36544
36771
  const qrData = qrCodeResponse?.data;
36545
36772
  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}`, "");
36773
+ if (qrData?.error_code !== 0) return utils_response(414, USER_MESSAGE.QRCODE_FETCH_FAILED, "");
36547
36774
  return utils_response(0, "获取二维码成功", {
36548
36775
  qrcode: qrData.qrcode,
36549
36776
  token: qrData.token,
@@ -36558,7 +36785,7 @@ var __webpack_exports__ = {};
36558
36785
  } catch (err) {
36559
36786
  const msg = err instanceof Error ? err.message : String(err);
36560
36787
  task.logger.warn(`[douyinGetVerifyQrCode] 获取二维码失败: ${msg}`);
36561
- return utils_response(500, `获取二维码失败: ${msg}`, "");
36788
+ return utils_response(500, USER_MESSAGE.QRCODE_FETCH_FAILED, "");
36562
36789
  }
36563
36790
  };
36564
36791
  const DouyinGetWorkListParamsSchema = ActionCommonParamsSchema.extend({
@@ -38332,6 +38559,11 @@ var __webpack_exports__ = {};
38332
38559
  }
38333
38560
  async getImageInfo(localPath) {
38334
38561
  const stats = external_node_fs_default().statSync(localPath);
38562
+ const maxSize = 52428800;
38563
+ if (stats.size > maxSize) {
38564
+ external_node_path_default().basename(localPath);
38565
+ throw new Error("抖音平台:单张图片不得超过 50MB");
38566
+ }
38335
38567
  let width = 1080;
38336
38568
  let height = 1920;
38337
38569
  try {
@@ -38812,18 +39044,10 @@ var __webpack_exports__ = {};
38812
39044
  });
38813
39045
  } catch (error) {
38814
39046
  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));
39047
+ const classified = classifyPublishError(handledError);
39048
+ if (classified) {
39049
+ const message = `${classified.userMessage}${task.debug ? ` ${http.proxyInfo}` : ""}`;
39050
+ task.logger.error(`[douyinPublish] ${classified.category},直接返回: ${handledError.message} (code=${handledError.code})`, stringifyError(handledError));
38827
39051
  await updateTaskState?.({
38828
39052
  state: types_TaskState.FAILED,
38829
39053
  error: message
@@ -40541,7 +40765,7 @@ var __webpack_exports__ = {};
40541
40765
  }
40542
40766
  const errMsg = error instanceof Error ? error.message : String(error);
40543
40767
  _task.logger.error(`抖音账号数据获取失败: ${errMsg}`);
40544
- return types_errorResponse(errMsg || "抖音账号数据获取失败");
40768
+ return types_errorResponse(USER_MESSAGE.DOUYIN_ACCOUNT_FETCH_FAILED);
40545
40769
  }
40546
40770
  }
40547
40771
  async function getShipinhaoData(_task, params) {
@@ -40672,7 +40896,7 @@ var __webpack_exports__ = {};
40672
40896
  }
40673
40897
  const errMsg = error instanceof Error ? error.message : String(error);
40674
40898
  _task.logger.error(`视频号账号数据获取失败: ${errMsg}`);
40675
- return types_errorResponse(errMsg || "视频号账号数据获取失败");
40899
+ return types_errorResponse(USER_MESSAGE.SHIPINHAO_ACCOUNT_FETCH_FAILED);
40676
40900
  }
40677
40901
  }
40678
40902
  async function getToutiaoData(_task, params) {
@@ -41113,7 +41337,9 @@ var __webpack_exports__ = {};
41113
41337
  } : null
41114
41338
  }, "百家号文章数据获取成功");
41115
41339
  } catch (error) {
41116
- return searchPublishInfo_types_errorResponse(error instanceof Error ? error.message : "百家号文章数据获取失败");
41340
+ const errMsg = error instanceof Error ? error.message : String(error);
41341
+ _task.logger.error(`百家号文章数据获取失败: ${errMsg}`);
41342
+ return searchPublishInfo_types_errorResponse(USER_MESSAGE.BJH_POST_FETCH_FAILED);
41117
41343
  }
41118
41344
  }
41119
41345
  async function handleDouyinData(_task, params) {
@@ -41208,7 +41434,9 @@ var __webpack_exports__ = {};
41208
41434
  } : null
41209
41435
  }, "抖音数据获取成功");
41210
41436
  } catch (error) {
41211
- return searchPublishInfo_types_errorResponse(error instanceof Error ? error.message : "抖音数据获取失败");
41437
+ const errMsg = error instanceof Error ? error.message : String(error);
41438
+ _task.logger.error(`抖音作品数据获取失败: ${errMsg}`);
41439
+ return searchPublishInfo_types_errorResponse(USER_MESSAGE.DOUYIN_POST_FETCH_FAILED);
41212
41440
  }
41213
41441
  }
41214
41442
  async function handleShipinhaoData(_task, params) {
@@ -41373,8 +41601,9 @@ var __webpack_exports__ = {};
41373
41601
  }, "视频号数据获取成功");
41374
41602
  } catch (error) {
41375
41603
  const errMsg = error instanceof Error ? error.message : String(error);
41604
+ _task.logger.error(`视频号作品数据获取失败: ${errMsg}`);
41376
41605
  if (errMsg.startsWith("AUTH_ERROR:")) return searchPublishInfo_types_errorResponse("视频号数据获取失败,请检查账号状态", 414);
41377
- return searchPublishInfo_types_errorResponse(errMsg || "视频号数据获取失败");
41606
+ return searchPublishInfo_types_errorResponse(USER_MESSAGE.SHIPINHAO_POST_FETCH_FAILED);
41378
41607
  }
41379
41608
  }
41380
41609
  async function handleToutiaoData(_task, params) {
@@ -41459,7 +41688,9 @@ var __webpack_exports__ = {};
41459
41688
  } : null
41460
41689
  }, "头条号文章文章获取成功");
41461
41690
  } catch (error) {
41462
- return searchPublishInfo_types_errorResponse(error instanceof Error ? error.message : "头条号文章数据获取失败");
41691
+ const errMsg = error instanceof Error ? error.message : String(error);
41692
+ _task.logger.error(`头条号文章数据获取失败: ${errMsg}`);
41693
+ return searchPublishInfo_types_errorResponse(USER_MESSAGE.TT_POST_FETCH_FAILED);
41463
41694
  }
41464
41695
  }
41465
41696
  const external_node_vm_namespaceObject = require("node:vm");
@@ -43836,18 +44067,10 @@ var __webpack_exports__ = {};
43836
44067
  });
43837
44068
  } catch (error) {
43838
44069
  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));
44070
+ const classified = classifyPublishError(handledError);
44071
+ if (classified) {
44072
+ const message = `${classified.userMessage}${task.debug ? ` ${http.proxyInfo}` : ""}`;
44073
+ task.logger.error(`[shipinhaoPublish] ${classified.category},直接返回: ${handledError.message} (code=${handledError.code})`, stringifyError(handledError));
43851
44074
  await updateTaskState?.({
43852
44075
  state: types_TaskState.FAILED,
43853
44076
  error: message
@@ -44587,6 +44810,1645 @@ var __webpack_exports__ = {};
44587
44810
  if ("server" === params.actionType) return rpa_server_rpaAction_Server(task, params);
44588
44811
  return executeAction(shipinhaoPublish_mock_mockAction, rpa_server_rpaAction_Server)(task, params);
44589
44812
  };
44813
+ function auth_getTimeStamp(length) {
44814
+ return Date.now().toString().substring(0, length);
44815
+ }
44816
+ async function auth_getUserInfo(cookies, http) {
44817
+ return http.api({
44818
+ method: "post",
44819
+ url: "https://channels.weixin.qq.com/cgi-bin/mmfinderassistant-bin/auth/auth_data",
44820
+ data: {
44821
+ timestamp: auth_getTimeStamp(13),
44822
+ _log_finder_uin: "",
44823
+ _log_finder_id: "",
44824
+ rawKeyBuff: null,
44825
+ pluginSessionId: null,
44826
+ scene: 7,
44827
+ reqScene: 7
44828
+ },
44829
+ headers: {
44830
+ cookie: cookies,
44831
+ referer: "https://channels.weixin.qq.com",
44832
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
44833
+ },
44834
+ defaultErrorMsg: "获取用户信息失败"
44835
+ });
44836
+ }
44837
+ async function auth_getUploadAuthKey(cookies, finderUsername, http) {
44838
+ return http.api({
44839
+ method: "post",
44840
+ url: "https://channels.weixin.qq.com/cgi-bin/mmfinderassistant-bin/helper/helper_upload_params",
44841
+ data: {
44842
+ timestamp: auth_getTimeStamp(13),
44843
+ _log_finder_id: finderUsername,
44844
+ rawKeyBuff: null
44845
+ },
44846
+ headers: {
44847
+ cookie: cookies,
44848
+ referer: "https://channels.weixin.qq.com",
44849
+ Accept: "application/json, text/plain, */*",
44850
+ "Content-Type": "application/json",
44851
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
44852
+ },
44853
+ defaultErrorMsg: "获取上传认证密钥失败"
44854
+ });
44855
+ }
44856
+ class ShipinhaoAuthError extends Error {
44857
+ constructor(message, errCode){
44858
+ super(message), this.errCode = errCode;
44859
+ this.name = "ShipinhaoAuthError";
44860
+ }
44861
+ }
44862
+ async function getShipinhaoUploadAuth(cookies, http) {
44863
+ const userInfo = await auth_getUserInfo(cookies, http);
44864
+ if (0 !== userInfo.errCode || !userInfo.data?.finderUser) {
44865
+ const isLoginExpired = 300333 === userInfo.errCode || 300334 === userInfo.errCode;
44866
+ throw new ShipinhaoAuthError(isLoginExpired ? "登录失效" : userInfo.errMsg || "获取用户信息失败", userInfo.errCode || 500);
44867
+ }
44868
+ const finderUsername = userInfo.data.finderUser.finderUsername;
44869
+ const authKeyResponse = await auth_getUploadAuthKey(cookies, finderUsername, http);
44870
+ if (0 !== authKeyResponse.errCode || !authKeyResponse.data?.authKey) throw new ShipinhaoAuthError(`获取上传认证参数失败: ${authKeyResponse.errMsg}`, authKeyResponse.errCode || 500);
44871
+ const uin = authKeyResponse.data.uin;
44872
+ if (!uin) throw new ShipinhaoAuthError("获取用户 uin 失败", 500);
44873
+ const videoFileType = authKeyResponse.data.videoFileType || 20302;
44874
+ const pictureFileType = authKeyResponse.data.pictureFileType || 20304;
44875
+ return {
44876
+ uin,
44877
+ authKey: authKeyResponse.data.authKey,
44878
+ finderUsername,
44879
+ videoFileType,
44880
+ pictureFileType
44881
+ };
44882
+ }
44883
+ const MENTION_TEXT_SUFFIX = "\u0020";
44884
+ const MENTION_XML_SUFFIX = "\u2005";
44885
+ function payload_buildDescription(params) {
44886
+ let description = params.description || "";
44887
+ for (const topic of params.topics || [])description += `#${topic}`;
44888
+ for (const user of params.mentionedUsers || [])description += `@${user.nickname}${MENTION_TEXT_SUFFIX}`;
44889
+ return description;
44890
+ }
44891
+ function buildMentionedUser(mentionedUsers) {
44892
+ return (mentionedUsers || []).map((user)=>({
44893
+ nickname: `${user.nickname}${MENTION_TEXT_SUFFIX}`
44894
+ }));
44895
+ }
44896
+ function payload_buildTopicXml(params) {
44897
+ const values = [];
44898
+ let atIndex = null;
44899
+ if (params.description) values.push(`<![CDATA[${params.description}]]>`);
44900
+ for (const topic of params.topics || [])values.push(`<topic><![CDATA[#${topic}#]]></topic>`);
44901
+ for (const user of params.mentionedUsers || []){
44902
+ if (null === atIndex) atIndex = values.length;
44903
+ values.push(`<![CDATA[@${user.nickname}${MENTION_XML_SUFFIX}]]>`);
44904
+ }
44905
+ let xml = "<finder>";
44906
+ xml += "<version>1</version>";
44907
+ xml += `<valuecount>${values.length}</valuecount>`;
44908
+ xml += `<style><at>${atIndex ?? ""}</at></style>`;
44909
+ values.forEach((value, index)=>{
44910
+ xml += `<value${index}>${value}</value${index}>`;
44911
+ });
44912
+ xml += "</finder>";
44913
+ return xml;
44914
+ }
44915
+ function payload_buildLocation(location) {
44916
+ if (!location) return {
44917
+ latitude: 0,
44918
+ longitude: 0,
44919
+ city: "",
44920
+ poiName: "",
44921
+ address: "",
44922
+ poiClassifyId: ""
44923
+ };
44924
+ return {
44925
+ latitude: location.latitude,
44926
+ longitude: location.longitude,
44927
+ city: location.city,
44928
+ poiName: location.poiName || "",
44929
+ address: location.address || "",
44930
+ poiClassifyId: location.poiClassifyId || ""
44931
+ };
44932
+ }
44933
+ function buildTopic(params) {
44934
+ const topic = {
44935
+ finderTopicInfo: payload_buildTopicXml(params)
44936
+ };
44937
+ if (params.collection) {
44938
+ topic.collectionId = params.collection.collectionId;
44939
+ topic.collectionName = params.collection.collectionName;
44940
+ }
44941
+ return topic;
44942
+ }
44943
+ function buildEvent(event) {
44944
+ if (!event) return {};
44945
+ return {
44946
+ eventTopicId: event.eventTopicId,
44947
+ eventName: event.eventName,
44948
+ eventCreatorNickname: event.eventCreatorNickname || ""
44949
+ };
44950
+ }
44951
+ function buildExtReading(link) {
44952
+ if (!link) return {
44953
+ link: "",
44954
+ title: "",
44955
+ urlType: 1
44956
+ };
44957
+ return {
44958
+ link: link.link.replace(/[\s\u200b]/g, ""),
44959
+ title: link.title,
44960
+ urlType: link.urlType ?? 1
44961
+ };
44962
+ }
44963
+ function buildTagInfo(tagInfo, tagKey) {
44964
+ return {
44965
+ ...tagInfo,
44966
+ tagKey
44967
+ };
44968
+ }
44969
+ const CHUNK_SIZE = 8388608;
44970
+ const UPLOAD_STAGE_TIMEOUT = 180000;
44971
+ const DEFAULT_TUNING = {
44972
+ metaTimeout: UPLOAD_STAGE_TIMEOUT,
44973
+ partTimeout: UPLOAD_STAGE_TIMEOUT,
44974
+ partRetries: 3,
44975
+ completeTimeout: UPLOAD_STAGE_TIMEOUT
44976
+ };
44977
+ async function uploader_uploadFile(opts) {
44978
+ const { filePath, fileType, uin, authKey, http, logger, tuning } = opts;
44979
+ const stat = external_node_fs_default().statSync(filePath);
44980
+ const fileSize = stat.size;
44981
+ const fileName = filePath.split(/[\\/]/).pop() || "file";
44982
+ const metaTimeout = tuning?.metaTimeout ?? DEFAULT_TUNING.metaTimeout;
44983
+ const partTimeout = tuning?.partTimeout ?? DEFAULT_TUNING.partTimeout;
44984
+ const partRetries = tuning?.partRetries ?? DEFAULT_TUNING.partRetries;
44985
+ const completeTimeout = tuning?.completeTimeout ?? DEFAULT_TUNING.completeTimeout;
44986
+ logger?.info(`开始上传: ${fileName} (${fileSize} B, filetype=${fileType})`);
44987
+ logger?.info(`上传超时策略: 单片 ${partTimeout / 1000}s(重试 ${partRetries} 次)、合并 ${completeTimeout / 1000}s`);
44988
+ const fileMd5 = await computeFileMd5(filePath);
44989
+ const taskId = generateTaskId(fileName, fileSize, fileMd5);
44990
+ const baseUrl = "https://finderassistancea.video.qq.com";
44991
+ const headers = {
44992
+ Authorization: authKey
44993
+ };
44994
+ const xArgs = `apptype=251&filetype=${fileType}&weixinnum=${uin}&filekey=${encodeURIComponent(fileName)}&filesize=${fileSize}&taskid=${taskId}&scene=2`;
44995
+ const chunkCount = Math.ceil(fileSize / CHUNK_SIZE);
44996
+ const blockPartLength = [];
44997
+ for(let i = 0; i < chunkCount; i++)blockPartLength.push(Math.min((i + 1) * CHUNK_SIZE, fileSize));
44998
+ logger?.info(`申请 UploadID: ${chunkCount} 片`);
44999
+ const applyRes = await http.api({
45000
+ method: "PUT",
45001
+ url: `${baseUrl}/applyuploaddfs`,
45002
+ headers: {
45003
+ ...headers,
45004
+ "X-Arguments": xArgs
45005
+ },
45006
+ data: {
45007
+ BlockSum: chunkCount,
45008
+ BlockPartLength: blockPartLength
45009
+ }
45010
+ }, {
45011
+ timeout: metaTimeout,
45012
+ retries: 2,
45013
+ retryDelay: 2000
45014
+ });
45015
+ if (!applyRes.UploadID && !applyRes.ListPartsResult) throw new Error("申请 UploadID 失败: " + JSON.stringify(applyRes));
45016
+ let uploadId = applyRes.UploadID;
45017
+ const uploadedParts = new Set();
45018
+ if (applyRes.ListPartsResult) {
45019
+ logger?.info("检测到已上传分片,执行续传");
45020
+ const parts = Array.isArray(applyRes.ListPartsResult.Part) ? applyRes.ListPartsResult.Part : applyRes.ListPartsResult.Part ? [
45021
+ applyRes.ListPartsResult.Part
45022
+ ] : [];
45023
+ for (const p of parts)uploadedParts.add(p.PartNumber);
45024
+ const retryRes = await http.api({
45025
+ method: "PUT",
45026
+ url: `${baseUrl}/applyuploaddfs`,
45027
+ headers: {
45028
+ ...headers,
45029
+ "X-Arguments": xArgs
45030
+ },
45031
+ data: {
45032
+ BlockSum: chunkCount,
45033
+ BlockPartLength: blockPartLength
45034
+ }
45035
+ }, {
45036
+ timeout: metaTimeout,
45037
+ retries: 2,
45038
+ retryDelay: 2000
45039
+ });
45040
+ uploadId = retryRes.UploadID;
45041
+ if (!uploadId) throw new Error("续传获取 UploadID 失败");
45042
+ }
45043
+ const partInfo = [];
45044
+ const fd = external_node_fs_default().openSync(filePath, "r");
45045
+ try {
45046
+ for(let i = 0; i < chunkCount; i++){
45047
+ const partNumber = i + 1;
45048
+ if (uploadedParts.has(partNumber)) {
45049
+ const existing = applyRes.ListPartsResult.Part.find((p)=>p.PartNumber === partNumber);
45050
+ if (existing) {
45051
+ partInfo.push({
45052
+ PartNumber: partNumber,
45053
+ ETag: existing.ETag
45054
+ });
45055
+ logger?.info(`分片 ${partNumber}/${chunkCount} 已存在,跳过`);
45056
+ continue;
45057
+ }
45058
+ }
45059
+ const start = i * CHUNK_SIZE;
45060
+ const end = Math.min(start + CHUNK_SIZE, fileSize);
45061
+ const chunkSize = end - start;
45062
+ const chunk = Buffer.alloc(chunkSize);
45063
+ external_node_fs_default().readSync(fd, chunk, 0, chunkSize, start);
45064
+ const chunkMd5 = external_node_crypto_default().createHash("md5").update(chunk).digest("hex");
45065
+ const partStart = Date.now();
45066
+ await http.api({
45067
+ method: "PUT",
45068
+ url: `${baseUrl}/uploadpartdfs?PartNumber=${partNumber}&UploadID=${encodeURIComponent(uploadId)}`,
45069
+ headers: {
45070
+ ...headers,
45071
+ "X-Arguments": xArgs.replace(/scene=2/, "scene=0"),
45072
+ "Content-MD5": chunkMd5
45073
+ },
45074
+ data: chunk
45075
+ }, {
45076
+ timeout: partTimeout,
45077
+ retries: partRetries,
45078
+ retryDelay: 2000
45079
+ });
45080
+ const partElapsed = Date.now() - partStart;
45081
+ const throughput = Math.round(chunkSize / (partElapsed / 1000));
45082
+ partInfo.push({
45083
+ PartNumber: partNumber,
45084
+ ETag: `"${chunkMd5}"`
45085
+ });
45086
+ logger?.info(`分片 ${partNumber}/${chunkCount} 完成 (${chunkSize} B, ${partElapsed}ms, ${Math.round(throughput / 1024)}KB/s)`);
45087
+ }
45088
+ } finally{
45089
+ external_node_fs_default().closeSync(fd);
45090
+ }
45091
+ logger?.info("合并分片...");
45092
+ const completeRes = await http.api({
45093
+ method: "POST",
45094
+ url: `${baseUrl}/completepartuploaddfs?UploadID=${encodeURIComponent(uploadId)}`,
45095
+ headers: {
45096
+ ...headers,
45097
+ "X-Arguments": xArgs
45098
+ },
45099
+ data: {
45100
+ TransFlag: "0_0",
45101
+ PartInfo: partInfo
45102
+ }
45103
+ }, {
45104
+ timeout: completeTimeout,
45105
+ retries: 1,
45106
+ retryDelay: 3000
45107
+ });
45108
+ if (!completeRes.DownloadURL) throw new Error("合并分片失败: " + JSON.stringify(completeRes));
45109
+ logger?.info("上传成功");
45110
+ return {
45111
+ downloadUrl: completeRes.DownloadURL,
45112
+ md5: fileMd5,
45113
+ fileSize
45114
+ };
45115
+ }
45116
+ async function computeFileMd5(filePath) {
45117
+ return new Promise((resolve, reject)=>{
45118
+ const hash = external_node_crypto_default().createHash("md5");
45119
+ const stream = external_node_fs_default().createReadStream(filePath);
45120
+ stream.on("data", (chunk)=>hash.update(chunk));
45121
+ stream.on("end", ()=>resolve(hash.digest("hex")));
45122
+ stream.on("error", reject);
45123
+ });
45124
+ }
45125
+ function generateTaskId(fileName, fileSize, fileMd5) {
45126
+ const input = `${fileName}-${fileSize}-${fileMd5}`;
45127
+ return external_node_crypto_default().createHash("md5").update(input).digest("hex").slice(0, 32);
45128
+ }
45129
+ const MAX_METADATA_BOX_SIZE = 268435456;
45130
+ function readBoxHeader(fd, offset, limit) {
45131
+ if (offset + 8 > limit) return null;
45132
+ const head = Buffer.alloc(16);
45133
+ const read = external_node_fs_default().readSync(fd, head, 0, 16, offset);
45134
+ if (read < 8) return null;
45135
+ let size = head.readUInt32BE(0);
45136
+ const type = head.toString("latin1", 4, 8);
45137
+ let headerSize = 8;
45138
+ if (1 === size) {
45139
+ if (read < 16) return null;
45140
+ size = head.readUInt32BE(8) * 2 ** 32 + head.readUInt32BE(12);
45141
+ headerSize = 16;
45142
+ } else if (0 === size) size = limit - offset;
45143
+ if (size < headerSize || offset + size > limit) return null;
45144
+ return {
45145
+ type,
45146
+ size,
45147
+ headerSize
45148
+ };
45149
+ }
45150
+ function parseVideoMeta(filePath) {
45151
+ let fd;
45152
+ let fileSize;
45153
+ try {
45154
+ fd = external_node_fs_default().openSync(filePath, "r");
45155
+ } catch {
45156
+ return null;
45157
+ }
45158
+ try {
45159
+ fileSize = external_node_fs_default().fstatSync(fd).size;
45160
+ const state = {
45161
+ movie: null,
45162
+ tracks: [],
45163
+ trexDefaults: new Map(),
45164
+ fragmentDurations: new Map(),
45165
+ trafTrackId: 0,
45166
+ trafDefaultSampleDuration: 0
45167
+ };
45168
+ let offset = 0;
45169
+ while(offset + 8 <= fileSize){
45170
+ const header = readBoxHeader(fd, offset, fileSize);
45171
+ if (!header) break;
45172
+ if ("moov" === header.type || "moof" === header.type) {
45173
+ const bodyLength = header.size - header.headerSize;
45174
+ if (bodyLength > 0 && bodyLength <= MAX_METADATA_BOX_SIZE) {
45175
+ const body = Buffer.alloc(bodyLength);
45176
+ const read = external_node_fs_default().readSync(fd, body, 0, bodyLength, offset + header.headerSize);
45177
+ state.trafTrackId = 0;
45178
+ state.trafDefaultSampleDuration = 0;
45179
+ walkBoxes(body.subarray(0, read), 0, read, state);
45180
+ }
45181
+ }
45182
+ offset += header.size;
45183
+ }
45184
+ const { movie, tracks } = state;
45185
+ const video = tracks.find((t)=>"vide" === t.handler) || tracks.find((t)=>t.width > 0 && t.height > 0);
45186
+ if (!video) return null;
45187
+ let { width, height } = video;
45188
+ if (90 === video.rotation || 270 === video.rotation) [width, height] = [
45189
+ height,
45190
+ width
45191
+ ];
45192
+ return {
45193
+ width: Math.round(width),
45194
+ height: Math.round(height),
45195
+ duration: resolveDuration(movie, video, state.fragmentDurations),
45196
+ rotation: video.rotation,
45197
+ fileSize,
45198
+ codec: video.codec
45199
+ };
45200
+ } catch {
45201
+ return null;
45202
+ } finally{
45203
+ try {
45204
+ external_node_fs_default().closeSync(fd);
45205
+ } catch {}
45206
+ }
45207
+ }
45208
+ function walkBoxes(buf, start, end, state) {
45209
+ let off = start;
45210
+ while(off + 8 <= end){
45211
+ let size = buf.readUInt32BE(off);
45212
+ const type = buf.toString("latin1", off + 4, off + 8);
45213
+ let headerSize = 8;
45214
+ if (1 === size) {
45215
+ if (off + 16 > end) break;
45216
+ const hi = buf.readUInt32BE(off + 8);
45217
+ const lo = buf.readUInt32BE(off + 12);
45218
+ size = hi * 2 ** 32 + lo;
45219
+ headerSize = 16;
45220
+ } else if (0 === size) size = end - off;
45221
+ if (size < headerSize || off + size > end) break;
45222
+ const bodyStart = off + headerSize;
45223
+ const bodyEnd = off + size;
45224
+ switch(type){
45225
+ case "trak":
45226
+ case "mdia":
45227
+ case "minf":
45228
+ case "stbl":
45229
+ case "mvex":
45230
+ case "traf":
45231
+ walkBoxes(buf, bodyStart, bodyEnd, state);
45232
+ break;
45233
+ case "mvhd":
45234
+ state.movie = parseMvhd(buf, bodyStart, bodyEnd);
45235
+ break;
45236
+ case "tkhd":
45237
+ state.tracks.push({
45238
+ ...parseTkhd(buf, bodyStart, bodyEnd),
45239
+ handler: null,
45240
+ codec: null,
45241
+ timescale: 0,
45242
+ mdhdDuration: 0,
45243
+ sttsDuration: 0
45244
+ });
45245
+ break;
45246
+ case "mdhd":
45247
+ {
45248
+ const mdhd = parseMvhd(buf, bodyStart, bodyEnd);
45249
+ if (mdhd && state.tracks.length) {
45250
+ const track = state.tracks[state.tracks.length - 1];
45251
+ track.timescale = mdhd.timescale;
45252
+ track.mdhdDuration = mdhd.duration;
45253
+ }
45254
+ break;
45255
+ }
45256
+ case "hdlr":
45257
+ if (bodyEnd - bodyStart >= 12 && state.tracks.length) state.tracks[state.tracks.length - 1].handler = buf.toString("latin1", bodyStart + 8, bodyStart + 12);
45258
+ break;
45259
+ case "stsd":
45260
+ {
45261
+ const codec = parseStsdCodec(buf, bodyStart, bodyEnd);
45262
+ if (codec && state.tracks.length) state.tracks[state.tracks.length - 1].codec = codec;
45263
+ break;
45264
+ }
45265
+ case "stts":
45266
+ if (state.tracks.length) state.tracks[state.tracks.length - 1].sttsDuration = parseSttsDuration(buf, bodyStart, bodyEnd);
45267
+ break;
45268
+ case "trex":
45269
+ if (bodyStart + 20 > bodyEnd) break;
45270
+ state.trexDefaults.set(buf.readUInt32BE(bodyStart + 4), buf.readUInt32BE(bodyStart + 12));
45271
+ break;
45272
+ case "tfhd":
45273
+ {
45274
+ const tfhd = parseTfhd(buf, bodyStart, bodyEnd);
45275
+ state.trafTrackId = tfhd.trackId;
45276
+ state.trafDefaultSampleDuration = tfhd.defaultSampleDuration || state.trexDefaults.get(tfhd.trackId) || 0;
45277
+ break;
45278
+ }
45279
+ case "trun":
45280
+ {
45281
+ const duration = parseTrunDuration(buf, bodyStart, bodyEnd, state.trafDefaultSampleDuration);
45282
+ state.fragmentDurations.set(state.trafTrackId, (state.fragmentDurations.get(state.trafTrackId) || 0) + duration);
45283
+ break;
45284
+ }
45285
+ }
45286
+ off += size;
45287
+ }
45288
+ }
45289
+ const UNKNOWN_DURATION_32 = 0xffffffff;
45290
+ function isUsableDuration(duration) {
45291
+ return duration > 0 && duration !== UNKNOWN_DURATION_32;
45292
+ }
45293
+ function resolveDuration(movie, video, fragmentDurations) {
45294
+ if (movie && movie.timescale && isUsableDuration(movie.duration)) return movie.duration / movie.timescale;
45295
+ if (video.timescale) {
45296
+ if (isUsableDuration(video.mdhdDuration)) return video.mdhdDuration / video.timescale;
45297
+ if (video.sttsDuration > 0) return video.sttsDuration / video.timescale;
45298
+ const fragment = fragmentDurations.get(video.trackId) ?? (1 === fragmentDurations.size ? [
45299
+ ...fragmentDurations.values()
45300
+ ][0] : 0);
45301
+ if (fragment > 0) return fragment / video.timescale;
45302
+ }
45303
+ return 0;
45304
+ }
45305
+ function parseSttsDuration(buf, start, end) {
45306
+ if (start + 8 > end) return 0;
45307
+ const entryCount = buf.readUInt32BE(start + 4);
45308
+ let total = 0;
45309
+ for(let i = 0; i < entryCount; i++){
45310
+ const off = start + 8 + 8 * i;
45311
+ if (off + 8 > end) break;
45312
+ total += buf.readUInt32BE(off) * buf.readUInt32BE(off + 4);
45313
+ }
45314
+ return total;
45315
+ }
45316
+ function parseTfhd(buf, start, end) {
45317
+ if (start + 8 > end) return {
45318
+ trackId: 0,
45319
+ defaultSampleDuration: 0
45320
+ };
45321
+ const flags = buf.readUIntBE(start + 1, 3);
45322
+ const trackId = buf.readUInt32BE(start + 4);
45323
+ let off = start + 8;
45324
+ if (0x000001 & flags) off += 8;
45325
+ if (0x000002 & flags) off += 4;
45326
+ if (0x000008 & flags && off + 4 <= end) return {
45327
+ trackId,
45328
+ defaultSampleDuration: buf.readUInt32BE(off)
45329
+ };
45330
+ return {
45331
+ trackId,
45332
+ defaultSampleDuration: 0
45333
+ };
45334
+ }
45335
+ function parseTrunDuration(buf, start, end, defaultSampleDuration) {
45336
+ if (start + 8 > end) return 0;
45337
+ const flags = buf.readUIntBE(start + 1, 3);
45338
+ const sampleCount = buf.readUInt32BE(start + 4);
45339
+ let off = start + 8;
45340
+ if (0x000001 & flags) off += 4;
45341
+ if (0x000004 & flags) off += 4;
45342
+ const hasDuration = (0x000100 & flags) !== 0;
45343
+ if (!hasDuration) return sampleCount * defaultSampleDuration;
45344
+ const entrySize = 4 + ((0x000200 & flags) !== 0 ? 4 : 0) + ((0x000400 & flags) !== 0 ? 4 : 0) + ((0x000800 & flags) !== 0 ? 4 : 0);
45345
+ let total = 0;
45346
+ for(let i = 0; i < sampleCount; i++){
45347
+ const entryOff = off + i * entrySize;
45348
+ if (entryOff + 4 > end) break;
45349
+ total += buf.readUInt32BE(entryOff);
45350
+ }
45351
+ return total;
45352
+ }
45353
+ function parseStsdCodec(buf, start, end) {
45354
+ if (start + 16 > end) return null;
45355
+ if (0 === buf.readUInt32BE(start + 4)) return null;
45356
+ return buf.toString("latin1", start + 12, start + 16).toLowerCase();
45357
+ }
45358
+ function parseMvhd(buf, start, end) {
45359
+ const version = buf.readUInt8(start);
45360
+ if (1 === version) {
45361
+ if (start + 28 > end) return null;
45362
+ const timescale = buf.readUInt32BE(start + 20);
45363
+ const hi = buf.readUInt32BE(start + 24);
45364
+ const lo = buf.readUInt32BE(start + 28);
45365
+ return {
45366
+ timescale,
45367
+ duration: hi * 2 ** 32 + lo
45368
+ };
45369
+ }
45370
+ if (start + 20 > end) return null;
45371
+ return {
45372
+ timescale: buf.readUInt32BE(start + 12),
45373
+ duration: buf.readUInt32BE(start + 16)
45374
+ };
45375
+ }
45376
+ function parseTkhd(buf, start, end) {
45377
+ const version = buf.readUInt8(start);
45378
+ const afterDuration = 1 === version ? 36 : 24;
45379
+ const matrixOff = start + afterDuration + 16;
45380
+ const whOff = matrixOff + 36;
45381
+ const trackIdOff = start + (1 === version ? 20 : 12);
45382
+ const trackId = trackIdOff + 4 <= end ? buf.readUInt32BE(trackIdOff) : 0;
45383
+ if (whOff + 8 > end) return {
45384
+ trackId,
45385
+ width: 0,
45386
+ height: 0,
45387
+ rotation: 0
45388
+ };
45389
+ const width = buf.readUInt32BE(whOff) / 65536;
45390
+ const height = buf.readUInt32BE(whOff + 4) / 65536;
45391
+ const a = buf.readInt32BE(matrixOff) / 65536;
45392
+ const b = buf.readInt32BE(matrixOff + 4) / 65536;
45393
+ let rotation = 0;
45394
+ if (Math.abs(a) < 0.01 && Math.abs(b - 1) < 0.01) rotation = 90;
45395
+ else if (Math.abs(a + 1) < 0.01 && Math.abs(b) < 0.01) rotation = 180;
45396
+ else if (Math.abs(a) < 0.01 && Math.abs(b + 1) < 0.01) rotation = 270;
45397
+ return {
45398
+ trackId,
45399
+ width,
45400
+ height,
45401
+ rotation
45402
+ };
45403
+ }
45404
+ function parseVideoCodec(filePath) {
45405
+ return parseVideoMeta(filePath)?.codec ?? null;
45406
+ }
45407
+ function buildVideoMetaFromParams(filePath, metadata) {
45408
+ return {
45409
+ width: Math.round(metadata.width),
45410
+ height: Math.round(metadata.height),
45411
+ duration: metadata.duration,
45412
+ rotation: 0,
45413
+ fileSize: metadata.fileSize,
45414
+ codec: parseVideoCodec(filePath)
45415
+ };
45416
+ }
45417
+ const MAX_DURATION_SECONDS = 28800;
45418
+ const MAX_FILE_SIZE = 21474836480;
45419
+ const ALLOWED_EXTENSIONS = [
45420
+ ".mp4"
45421
+ ];
45422
+ const ALLOWED_CODECS = [
45423
+ "avc1",
45424
+ "avc3"
45425
+ ];
45426
+ const MIN_TITLE_LENGTH = 6;
45427
+ const MAX_TITLE_LENGTH = 16;
45428
+ function formatFileSize(bytes) {
45429
+ if (bytes < 1048576) return `${(bytes / 1024).toFixed(2)} KB`;
45430
+ if (bytes < 1073741824) return `${(bytes / 1024 / 1024).toFixed(2)} MB`;
45431
+ return `${(bytes / 1024 / 1024 / 1024).toFixed(2)} GB`;
45432
+ }
45433
+ function formatDuration(seconds) {
45434
+ const total = Math.round(seconds);
45435
+ const h = Math.floor(total / 3600);
45436
+ const m = Math.floor(total % 3600 / 60);
45437
+ const s = total % 60;
45438
+ if (h > 0) return `${h}小时${m}分${s}秒`;
45439
+ if (m > 0) return `${m}分${s}秒`;
45440
+ return `${s}秒`;
45441
+ }
45442
+ function validateShipinhaoVideo(filePath, meta) {
45443
+ const fileName = external_node_path_default().basename(filePath);
45444
+ const ext = external_node_path_default().extname(fileName).toLowerCase();
45445
+ if (!ALLOWED_EXTENSIONS.includes(ext)) return `视频格式不支持:${fileName}。视频号仅支持 MP4/H.264 格式,请转换后重试。`;
45446
+ if (meta.duration > MAX_DURATION_SECONDS) return `视频时长超过限制:${fileName}(${formatDuration(meta.duration)})。视频号视频时长不能超过 8 小时,请剪辑后重试。`;
45447
+ if (meta.fileSize > MAX_FILE_SIZE) return `视频大小超过限制:${fileName}(${formatFileSize(meta.fileSize)})。视频号视频不能超过 20GB,请压缩后重试。`;
45448
+ if (meta.codec && !ALLOWED_CODECS.includes(meta.codec)) return `视频编码不支持:${fileName}(${meta.codec})。视频号仅支持 H.264 编码,请转码后重试。`;
45449
+ return null;
45450
+ }
45451
+ function validateShipinhaoTitle(title) {
45452
+ if (void 0 === title) return null;
45453
+ const trimmed = title.trim();
45454
+ if ("" === trimmed) return null;
45455
+ const length = [
45456
+ ...trimmed
45457
+ ].length;
45458
+ if (length < MIN_TITLE_LENGTH || length > MAX_TITLE_LENGTH) return `视频号标题需要在 ${MIN_TITLE_LENGTH}-${MAX_TITLE_LENGTH} 个字符之间,当前 ${length} 个字符,请调整后重试。`;
45459
+ return null;
45460
+ }
45461
+ const POST_CREATE_PAGE_URL = "https://channels.weixin.qq.com/micro/content/post/create";
45462
+ const MICRO_CONTENT_BASE = "https://channels.weixin.qq.com/micro/content/cgi-bin/mmfinderassistant-bin";
45463
+ function resolveClientContext(params, fallbackUin) {
45464
+ const extra = params.extraParam || {};
45465
+ const deviceIdCookie = params.cookies.find((c)=>"device_id" === c.name || "finger_print_device_id" === c.name)?.value;
45466
+ return {
45467
+ aId: "string" == typeof extra.aId ? extra.aId : "",
45468
+ fingerPrintDeviceId: "string" == typeof extra.fingerPrintDeviceId ? extra.fingerPrintDeviceId : deviceIdCookie || "",
45469
+ uin: "string" == typeof extra.uin ? extra.uin : String(fallbackUin)
45470
+ };
45471
+ }
45472
+ function buildPublishHeaders(cookieString, client) {
45473
+ const headers = {
45474
+ cookie: cookieString,
45475
+ referer: POST_CREATE_PAGE_URL,
45476
+ origin: "https://channels.weixin.qq.com",
45477
+ "content-type": "application/json"
45478
+ };
45479
+ if (client.fingerPrintDeviceId) headers["finger-print-device-id"] = client.fingerPrintDeviceId;
45480
+ if (client.uin) headers["x-wechat-uin"] = client.uin;
45481
+ return headers;
45482
+ }
45483
+ function buildPublishQuery(client) {
45484
+ const query = {
45485
+ _rid: rid(),
45486
+ _pageUrl: POST_CREATE_PAGE_URL
45487
+ };
45488
+ if (client.aId) query._aid = client.aId;
45489
+ return query;
45490
+ }
45491
+ function buildCommonBody(finderUsername) {
45492
+ return {
45493
+ timestamp: String(Date.now()),
45494
+ _log_finder_uin: "",
45495
+ _log_finder_id: finderUsername,
45496
+ rawKeyBuff: "",
45497
+ pluginSessionId: null,
45498
+ scene: 7,
45499
+ reqScene: 7
45500
+ };
45501
+ }
45502
+ async function getTraceKey(auth, client, http, logger) {
45503
+ logger.info("[getTraceKey] 开始获取 traceKey...");
45504
+ const res = await http.api({
45505
+ method: "POST",
45506
+ url: `${MICRO_CONTENT_BASE}/post/get-finder-post-trace-key`,
45507
+ params: buildPublishQuery(client),
45508
+ data: {
45509
+ objectId: "",
45510
+ ...buildCommonBody(auth.finderUsername)
45511
+ },
45512
+ defaultErrorMsg: "获取 traceKey 失败"
45513
+ });
45514
+ if (0 !== res.errCode || !res.data?.traceKey) {
45515
+ logger.error("[getTraceKey] 获取失败:", JSON.stringify(res));
45516
+ throw new Error(`获取 traceKey 失败: ${JSON.stringify(res)}`);
45517
+ }
45518
+ logger.info(`[getTraceKey] 获取成功: ${res.data.traceKey}`);
45519
+ return res.data.traceKey;
45520
+ }
45521
+ async function getObjectTagKey(auth, client, http, logger) {
45522
+ logger.info("[getObjectTagKey] 获取内容声明 tagKey...");
45523
+ try {
45524
+ const res = await http.api({
45525
+ method: "POST",
45526
+ url: `${MICRO_CONTENT_BASE}/post/finder_get_object_tag_list`,
45527
+ params: buildPublishQuery(client),
45528
+ data: {
45529
+ source: 1,
45530
+ ...buildCommonBody(auth.finderUsername)
45531
+ },
45532
+ defaultErrorMsg: "获取内容声明标注失败"
45533
+ });
45534
+ if (0 !== res.errCode || !res.data?.tagKey) {
45535
+ logger.warn(`[getObjectTagKey] 未取到 tagKey: ${JSON.stringify(res)}`);
45536
+ return null;
45537
+ }
45538
+ logger.info(`[getObjectTagKey] tagKey: ${res.data.tagKey}`);
45539
+ return res.data.tagKey;
45540
+ } catch (error) {
45541
+ logger.warn(`[getObjectTagKey] 获取 tagKey 异常: ${stringifyError(error)}`);
45542
+ return null;
45543
+ }
45544
+ }
45545
+ async function submitAndPollTranscode(opts) {
45546
+ const { videoUrl, videoMeta, traceKey, uploadStartTime, uploadEndTime, finderUsername, client, http, logger } = opts;
45547
+ logger.info("[submitAndPollTranscode] 开始提交转码任务...");
45548
+ const finderUrl = videoUrl.includes("wxapp.tc.qq.com") ? `https://finder.video.qq.com${videoUrl.split("qq.com")[1]}` : videoUrl;
45549
+ logger.info(`[submitAndPollTranscode] 视频尺寸: ${videoMeta.width}x${videoMeta.height}, 时长: ${videoMeta.duration}s`);
45550
+ const submitRes = await http.api({
45551
+ method: "POST",
45552
+ url: `${MICRO_CONTENT_BASE}/post/post_clip_video`,
45553
+ params: buildPublishQuery(client),
45554
+ data: {
45555
+ url: finderUrl,
45556
+ timeStart: 0,
45557
+ cropDuration: 0,
45558
+ height: videoMeta.height,
45559
+ width: videoMeta.width,
45560
+ x: 0,
45561
+ y: 0,
45562
+ clipOriginVideoInfo: {
45563
+ width: videoMeta.width,
45564
+ height: videoMeta.height,
45565
+ duration: videoMeta.duration,
45566
+ fileSize: videoMeta.fileSize
45567
+ },
45568
+ traceInfo: {
45569
+ traceKey,
45570
+ uploadCdnStart: uploadStartTime,
45571
+ uploadCdnEnd: uploadEndTime
45572
+ },
45573
+ targetWidth: videoMeta.width,
45574
+ targetHeight: videoMeta.height,
45575
+ type: 4,
45576
+ useAstraThumbCover: 1,
45577
+ ...buildCommonBody(finderUsername)
45578
+ },
45579
+ defaultErrorMsg: "提交转码失败"
45580
+ });
45581
+ if (0 !== submitRes.errCode || !submitRes.data?.clipKey) {
45582
+ logger.error("[submitAndPollTranscode] 提交转码失败:", JSON.stringify(submitRes));
45583
+ throw new Error(`提交转码失败: ${JSON.stringify(submitRes)}`);
45584
+ }
45585
+ const { clipKey, draftId } = submitRes.data;
45586
+ logger.info(`[submitAndPollTranscode] 转码任务已提交,clipKey: ${clipKey}, draftId: ${draftId}`);
45587
+ const pollInterval = 5000;
45588
+ const pollBudget = Math.min(1800000, 300000 + 1000 * Math.ceil(1.5 * videoMeta.duration));
45589
+ const maxPolls = Math.ceil(pollBudget / pollInterval);
45590
+ let pollCount = 0;
45591
+ logger.info(`[submitAndPollTranscode] 开始轮询转码结果,最多 ${maxPolls} 次(${Math.round(pollBudget / 1000)}s),间隔 ${pollInterval / 1000}s`);
45592
+ while(pollCount < maxPolls){
45593
+ await mock_sleep(pollInterval);
45594
+ pollCount++;
45595
+ const pollRes = await http.api({
45596
+ method: "POST",
45597
+ url: `${MICRO_CONTENT_BASE}/post/post_clip_video_result`,
45598
+ params: buildPublishQuery(client),
45599
+ data: {
45600
+ clipKey,
45601
+ draftId,
45602
+ ...buildCommonBody(finderUsername)
45603
+ },
45604
+ defaultErrorMsg: "转码轮询失败"
45605
+ }, {
45606
+ timeout: 60000,
45607
+ retries: 2,
45608
+ retryDelay: 3000
45609
+ });
45610
+ if (0 !== pollRes.errCode) {
45611
+ logger.error(`[submitAndPollTranscode] 转码轮询失败 (poll ${pollCount}):`, JSON.stringify(pollRes));
45612
+ throw new Error(`转码轮询失败 (poll ${pollCount}): ${JSON.stringify(pollRes)}`);
45613
+ }
45614
+ const { flag, url, width, height, duration, md5, fileSize } = pollRes.data || {};
45615
+ logger.info(`[submitAndPollTranscode] 轮询第 ${pollCount} 次,flag=${flag}`);
45616
+ if (1 === flag) {
45617
+ if (!url || !width || !height || !duration || !md5 || !fileSize) {
45618
+ logger.error("[submitAndPollTranscode] 转码完成但返回数据不完整:", JSON.stringify(pollRes.data));
45619
+ throw new Error(`转码完成但返回数据不完整: ${JSON.stringify(pollRes.data)}`);
45620
+ }
45621
+ logger.info(`[submitAndPollTranscode] 转码完成! 用时: ${pollCount * pollInterval / 1000}s`);
45622
+ logger.info(`[submitAndPollTranscode] 视频信息: ${width}x${height}, 时长: ${duration}s, 大小: ${fileSize}`);
45623
+ return {
45624
+ clipKey,
45625
+ url,
45626
+ width,
45627
+ height,
45628
+ duration,
45629
+ md5,
45630
+ fileSize
45631
+ };
45632
+ }
45633
+ if (2 === flag) logger.info(`[submitAndPollTranscode] 转码中... (${pollCount}/${maxPolls})`);
45634
+ else {
45635
+ logger.error(`[submitAndPollTranscode] 转码失败,未知 flag=${flag}:`, JSON.stringify(pollRes.data));
45636
+ throw new Error(`转码失败,未知 flag=${flag}: ${JSON.stringify(pollRes.data)}`);
45637
+ }
45638
+ }
45639
+ logger.error(`[submitAndPollTranscode] 转码超时,已轮询 ${maxPolls} 次,用时: ${maxPolls * pollInterval / 1000}s`);
45640
+ throw new Error(`转码超时 (${maxPolls * pollInterval / 1000}s)`);
45641
+ }
45642
+ async function publishVideo(opts) {
45643
+ const { params, auth, client, clipResult, videoUpload, coverUpload, verticalCoverUpload, videoMeta, traceKey, tagKey, uploadStartTime, uploadEndTime, proxyHttp, logger } = opts;
45644
+ logger.info("[publishVideo] 开始构建发布请求...");
45645
+ const toFinderUrl = (url)=>url.includes("wxapp.tc.qq.com") ? `https://finder.video.qq.com${url.split("qq.com")[1]}` : url;
45646
+ const thumbFinderUrl = toFinderUrl(coverUpload.downloadUrl);
45647
+ const coverFinderUrl = toFinderUrl(verticalCoverUpload.downloadUrl);
45648
+ const md5sumUuid = external_node_crypto_default().randomUUID();
45649
+ const description = params.description;
45650
+ logger.info("[publishVideo] 发布参数:");
45651
+ logger.info(` - 短标题: ${params.title || "(无)"}`);
45652
+ logger.info(` - 描述: ${description.substring(0, 50)}${description.length > 50 ? "..." : ""}`);
45653
+ logger.info(` - 定时发布: ${params.scheduledTime ? new Date(1000 * params.scheduledTime).toLocaleString() : "立即发布"}`);
45654
+ const objectDesc = {
45655
+ mpTitle: "",
45656
+ description,
45657
+ extReading: buildExtReading(params.link),
45658
+ mediaType: 4,
45659
+ location: payload_buildLocation(params.location),
45660
+ topic: buildTopic({
45661
+ description: params.description,
45662
+ topics: params.topics,
45663
+ mentionedUsers: params.mentionedUsers,
45664
+ collection: params.collection
45665
+ }),
45666
+ event: buildEvent(params.event),
45667
+ mentionedUser: buildMentionedUser(params.mentionedUsers),
45668
+ media: [
45669
+ {
45670
+ url: clipResult.url,
45671
+ fileSize: clipResult.fileSize,
45672
+ thumbUrl: thumbFinderUrl,
45673
+ fullThumbUrl: thumbFinderUrl,
45674
+ coverUrl: coverFinderUrl,
45675
+ fullCoverUrl: coverFinderUrl,
45676
+ shareCoverUrl: coverFinderUrl,
45677
+ mediaType: 4,
45678
+ videoPlayLen: Math.round(clipResult.duration),
45679
+ width: clipResult.width,
45680
+ height: clipResult.height,
45681
+ md5sum: md5sumUuid,
45682
+ cardShowStyle: 2,
45683
+ urlCdnTaskId: clipResult.clipKey
45684
+ }
45685
+ ],
45686
+ shortTitle: params.title ? [
45687
+ {
45688
+ shortTitle: params.title
45689
+ }
45690
+ ] : [],
45691
+ member: {}
45692
+ };
45693
+ const publishData = {
45694
+ objectType: 0,
45695
+ longitude: 0,
45696
+ latitude: 0,
45697
+ feedLongitude: 0,
45698
+ feedLatitude: 0,
45699
+ originalFlag: params.originalFlag ?? 0,
45700
+ topics: params.topics || [],
45701
+ isFullPost: 1,
45702
+ handleFlag: 2,
45703
+ videoClipTaskId: clipResult.clipKey,
45704
+ traceInfo: {
45705
+ traceKey,
45706
+ uploadCdnStart: uploadStartTime,
45707
+ uploadCdnEnd: uploadEndTime
45708
+ },
45709
+ objectDesc,
45710
+ report: {
45711
+ clipKey: clipResult.clipKey,
45712
+ draftId: clipResult.clipKey,
45713
+ ...buildCommonBody(auth.finderUsername),
45714
+ height: videoMeta.height,
45715
+ width: videoMeta.width,
45716
+ duration: videoMeta.duration,
45717
+ fileSize: videoUpload.fileSize,
45718
+ uploadCost: (uploadEndTime - uploadStartTime) * 1000
45719
+ },
45720
+ postFlag: 0,
45721
+ mode: 1,
45722
+ clientid: external_node_crypto_default().randomUUID(),
45723
+ ...buildCommonBody(auth.finderUsername)
45724
+ };
45725
+ if (params.scheduledTime) publishData.effectiveTime = params.scheduledTime;
45726
+ if (params.tagInfo && tagKey) publishData.tagInfo = buildTagInfo(params.tagInfo, tagKey);
45727
+ logger.info("[publishVideo] 开始发布视频,全部参数:" + JSON.stringify(publishData));
45728
+ const publishRes = await proxyHttp.api({
45729
+ method: "POST",
45730
+ url: `${MICRO_CONTENT_BASE}/post/post_create`,
45731
+ params: buildPublishQuery(client),
45732
+ data: publishData,
45733
+ defaultErrorMsg: "发布视频失败"
45734
+ });
45735
+ logger.info(`[publishVideo] 发布响应: errCode=${publishRes.errCode}, baseResp.errcode=${publishRes.data?.baseResp?.errcode}`);
45736
+ return publishRes;
45737
+ }
45738
+ function mock_sleep(ms) {
45739
+ return new Promise((resolve)=>setTimeout(resolve, ms));
45740
+ }
45741
+ async function resolveLocalCoverPath(coverPath, label, tmpCachePath, logger) {
45742
+ if (!/^https?:\/\//i.test(coverPath)) return coverPath;
45743
+ const fileName = getFilenameFromUrl(coverPath);
45744
+ const savePath = external_node_path_default().join(tmpCachePath, `${Date.now()}-${label}-${fileName}`);
45745
+ await downloadImage(coverPath, savePath);
45746
+ return savePath;
45747
+ }
45748
+ const shipinhaoPublishVideo_mock_mockAction = async (task, params)=>{
45749
+ task.logger.info("[shipinhaoPublishVideo] 开始执行视频号视频发布 - Mock API 方式");
45750
+ const updateTaskState = task.taskStageStore?.update?.bind(task.taskStageStore, task.taskId || "");
45751
+ let currentStep = "初始化";
45752
+ try {
45753
+ task.logger.info(`[shipinhaoPublishVideo] 发布方式: ${params.scheduledTime ? `定时 ${new Date(1000 * params.scheduledTime).toLocaleString()}` : "立即发布"}`);
45754
+ currentStep = "解析认证信息";
45755
+ const cookieString = params.cookies.map((c)=>`${c.name}=${c.value}`).join("; ");
45756
+ const http = new Http({
45757
+ headers: {
45758
+ cookie: cookieString
45759
+ }
45760
+ });
45761
+ currentStep = "验证发布参数";
45762
+ if (!params.videoPath) return utils_response(414, "视频文件路径不能为空", "");
45763
+ if (!params.coverPath) return utils_response(414, "横屏封面图片路径不能为空", "");
45764
+ currentStep = "获取上传认证";
45765
+ task.logger.info("[shipinhaoPublishVideo] 获取上传认证...");
45766
+ const auth = await getShipinhaoUploadAuth(cookieString, http);
45767
+ const client = resolveClientContext(params, auth.uin);
45768
+ if (!client.aId) task.logger.warn("[shipinhaoPublishVideo] extraParam.aId 缺失,query 将不带 _aid");
45769
+ if (!client.fingerPrintDeviceId) task.logger.warn("[shipinhaoPublishVideo] extraParam.fingerPrintDeviceId 缺失,请求将不带 finger-print-device-id");
45770
+ const publishHeaders = buildPublishHeaders(cookieString, client);
45771
+ const microHttp = new Http({
45772
+ headers: publishHeaders
45773
+ });
45774
+ const args = [
45775
+ {
45776
+ headers: publishHeaders
45777
+ },
45778
+ task.logger,
45779
+ params.proxyLoc,
45780
+ params.accountId,
45781
+ "shipinhao"
45782
+ ];
45783
+ const proxyHttp = new Http(...args);
45784
+ currentStep = "组装视频元数据";
45785
+ task.logger.info("[shipinhaoPublishVideo] 组装视频元数据...");
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
+ if (!videoMeta.codec) task.logger.warn("[shipinhaoPublishVideo] 未能读取视频编码格式,跳过 H.264 预检,交由服务端判断");
45789
+ currentStep = "校验视频限制";
45790
+ const validationError = validateShipinhaoVideo(params.videoPath, videoMeta);
45791
+ if (validationError) {
45792
+ task.logger.error(`[shipinhaoPublishVideo] 视频校验未通过: ${validationError}`);
45793
+ await updateTaskState?.({
45794
+ state: types_TaskState.FAILED,
45795
+ error: validationError
45796
+ });
45797
+ return utils_response(414, validationError, "");
45798
+ }
45799
+ task.logger.info("[shipinhaoPublishVideo] 视频校验通过");
45800
+ currentStep = "校验标题";
45801
+ const titleError = validateShipinhaoTitle(params.title);
45802
+ if (titleError) {
45803
+ task.logger.error(`[shipinhaoPublishVideo] 标题校验未通过: ${titleError}`);
45804
+ await updateTaskState?.({
45805
+ state: types_TaskState.FAILED,
45806
+ error: titleError
45807
+ });
45808
+ return utils_response(414, titleError, "");
45809
+ }
45810
+ currentStep = "获取 traceKey";
45811
+ task.logger.info("[shipinhaoPublishVideo] 获取 traceKey...");
45812
+ const traceKey = await getTraceKey(auth, client, microHttp, task.logger);
45813
+ let tagKey = null;
45814
+ if (params.tagInfo) {
45815
+ currentStep = "获取内容声明 tagKey";
45816
+ tagKey = await getObjectTagKey(auth, client, microHttp, task.logger);
45817
+ }
45818
+ const uploadStartTime = Math.floor(Date.now() / 1000);
45819
+ task.logger.info(`[shipinhaoPublishVideo] 上传开始时间: ${uploadStartTime}`);
45820
+ currentStep = "上传视频";
45821
+ task.logger.info("[shipinhaoPublishVideo] 上传视频...");
45822
+ task.logger.info(`[shipinhaoPublishVideo] 视频路径: ${params.videoPath}`);
45823
+ task.logger.info(`[shipinhaoPublishVideo] 视频文件类型: ${auth.videoFileType}`);
45824
+ const videoUpload = await uploader_uploadFile({
45825
+ filePath: params.videoPath,
45826
+ fileType: auth.videoFileType,
45827
+ uin: auth.uin,
45828
+ authKey: auth.authKey,
45829
+ http,
45830
+ logger: task.logger
45831
+ });
45832
+ task.logger.info("[shipinhaoPublishVideo] 视频上传完成");
45833
+ const uploadEndTime = Math.floor(Date.now() / 1000);
45834
+ task.logger.info(`[shipinhaoPublishVideo] 上传结束时间: ${uploadEndTime}, 耗时: ${uploadEndTime - uploadStartTime}s`);
45835
+ currentStep = "上传横屏封面";
45836
+ const localCoverPath = await resolveLocalCoverPath(params.coverPath, "横屏封面", task.getTmpPath(), task.logger);
45837
+ task.logger.info("[shipinhaoPublishVideo] 上传横屏封面...");
45838
+ const coverUpload = await uploader_uploadFile({
45839
+ filePath: localCoverPath,
45840
+ fileType: auth.pictureFileType,
45841
+ uin: auth.uin,
45842
+ authKey: auth.authKey,
45843
+ http,
45844
+ logger: task.logger
45845
+ });
45846
+ task.logger.info("[shipinhaoPublishVideo] 横屏封面上传完成");
45847
+ let verticalCoverUpload = coverUpload;
45848
+ if (params.verticalCoverPath) {
45849
+ currentStep = "上传竖屏封面";
45850
+ const localVerticalPath = await resolveLocalCoverPath(params.verticalCoverPath, "竖屏封面", task.getTmpPath(), task.logger);
45851
+ task.logger.info("[shipinhaoPublishVideo] 上传竖屏封面");
45852
+ verticalCoverUpload = await uploader_uploadFile({
45853
+ filePath: localVerticalPath,
45854
+ fileType: auth.pictureFileType,
45855
+ uin: auth.uin,
45856
+ authKey: auth.authKey,
45857
+ http,
45858
+ logger: task.logger
45859
+ });
45860
+ task.logger.info("[shipinhaoPublishVideo] 竖屏封面上传完成");
45861
+ } else task.logger.info("[shipinhaoPublishVideo] 未传竖屏封面,复用横屏封面");
45862
+ currentStep = "提交转码";
45863
+ task.logger.info("[shipinhaoPublishVideo] 提交转码...");
45864
+ const clipResult = await submitAndPollTranscode({
45865
+ videoUrl: videoUpload.downloadUrl,
45866
+ videoMeta,
45867
+ traceKey,
45868
+ uploadStartTime,
45869
+ uploadEndTime,
45870
+ finderUsername: auth.finderUsername,
45871
+ client,
45872
+ http: microHttp,
45873
+ logger: task.logger
45874
+ });
45875
+ currentStep = "发布视频";
45876
+ task.logger.info("[shipinhaoPublishVideo] 发布视频...");
45877
+ task.logger.info(`[shipinhaoPublishVideo] clipKey: ${clipResult.clipKey}`);
45878
+ let publishResult;
45879
+ try {
45880
+ publishResult = await publishVideo({
45881
+ params,
45882
+ auth,
45883
+ client,
45884
+ clipResult,
45885
+ videoUpload,
45886
+ coverUpload,
45887
+ verticalCoverUpload,
45888
+ videoMeta,
45889
+ traceKey,
45890
+ tagKey,
45891
+ uploadStartTime,
45892
+ uploadEndTime,
45893
+ proxyHttp,
45894
+ logger: task.logger
45895
+ });
45896
+ } catch (error) {
45897
+ const handledError = Http.handleApiError(error);
45898
+ task.logger.error(`[shipinhaoPublishVideo] 发布请求失败: ${handledError.message}`, stringifyError(handledError));
45899
+ const classified = classifyPublishError(handledError);
45900
+ if (classified) {
45901
+ const message = `${classified.userMessage}${task.debug ? ` ${http.proxyInfo}` : ""}`;
45902
+ task.logger.error(`[shipinhaoPublishVideo] ${classified.category},直接返回: ${handledError.message} (code=${handledError.code})`, stringifyError(handledError));
45903
+ await updateTaskState?.({
45904
+ state: types_TaskState.FAILED,
45905
+ error: message
45906
+ });
45907
+ return {
45908
+ code: 414,
45909
+ data: "",
45910
+ message
45911
+ };
45912
+ }
45913
+ throw error;
45914
+ }
45915
+ task.logger.info(`[shipinhaoPublishVideo] publishResult: ${JSON.stringify(publishResult)}`);
45916
+ const resultCode = publishResult.data?.baseResp?.errcode ?? publishResult.errCode;
45917
+ const resultMsg = publishResult.data?.baseResp?.errmsg ?? (0 === resultCode ? "发布成功" : `发布失败(errCode=${resultCode})`);
45918
+ if (0 === resultCode) {
45919
+ task.logger.info("[shipinhaoPublishVideo] 发布成功");
45920
+ task.logger.info(`[shipinhaoPublishVideo] 作品ID: ${clipResult.clipKey}`);
45921
+ task.logger.info(`[shipinhaoPublishVideo] 视频URL: ${clipResult.url}`);
45922
+ task.logger.info(`[shipinhaoPublishVideo] 横屏封面URL: ${coverUpload.downloadUrl}`);
45923
+ task.logger.info(`[shipinhaoPublishVideo] 竖屏封面URL: ${verticalCoverUpload.downloadUrl}`);
45924
+ await updateTaskState?.({
45925
+ state: types_TaskState.SUCCESS,
45926
+ result: {
45927
+ response: resultMsg
45928
+ }
45929
+ });
45930
+ reportLogger({
45931
+ token: params.huiwenToken || "",
45932
+ enverionment: task.enverionment || "development",
45933
+ postId: params.articleId,
45934
+ eip: proxyHttp.proxyInfo,
45935
+ accountId: params.accountId,
45936
+ uid: params.uid,
45937
+ publishParams: {
45938
+ videoPath: params.videoPath,
45939
+ coverPath: params.coverPath,
45940
+ verticalCoverPath: params.verticalCoverPath,
45941
+ title: params.title,
45942
+ topics: params.topics,
45943
+ mentionedUsers: params.mentionedUsers,
45944
+ collection: params.collection,
45945
+ event: params.event,
45946
+ link: params.link,
45947
+ tagInfo: params.tagInfo,
45948
+ originalFlag: params.originalFlag,
45949
+ scheduledTime: params.scheduledTime
45950
+ },
45951
+ platform: "shipinhao"
45952
+ });
45953
+ task.logger.info("[shipinhaoPublishVideo] 日志上报完成");
45954
+ return utils_response(0, "发布成功", clipResult.clipKey);
45955
+ }
45956
+ let errorMessage = resultMsg;
45957
+ if (-11224 === resultCode) errorMessage = "视频号管理员完成实名且绑定手机号后才可以发表";
45958
+ else if (300333 === resultCode || 300334 === resultCode) errorMessage = "登录失效";
45959
+ else if (300330 === resultCode) errorMessage = "未登录";
45960
+ else if (300002 === resultCode) errorMessage = "官方平台在校验音乐/位置/定时信息时失败了,请重新编辑后发布";
45961
+ task.logger.error(`[shipinhaoPublishVideo] 发布失败: ${errorMessage} (errCode=${resultCode})`);
45962
+ await updateTaskState?.({
45963
+ state: types_TaskState.FAILED,
45964
+ error: errorMessage
45965
+ });
45966
+ return utils_response(resultCode || 414, errorMessage, "");
45967
+ } catch (error) {
45968
+ const handledError = Http.handleApiError(error);
45969
+ const errorMsg = handledError.message || "发布失败,请稍后重试";
45970
+ const errorCode = handledError.code || 414;
45971
+ task.logger.error(`[shipinhaoPublishVideo] 发布流程异常 [${currentStep}]: ${errorMsg}`, stringifyError(error), handledError.extra);
45972
+ task.logger.error(`[shipinhaoPublishVideo] 错误码: ${errorCode}, 当前步骤: ${currentStep}`);
45973
+ await updateTaskState?.({
45974
+ state: types_TaskState.FAILED,
45975
+ error: errorMsg
45976
+ });
45977
+ return utils_response(errorCode, errorMsg, "");
45978
+ }
45979
+ };
45980
+ const shipinhaoPublishVideo_rpa_rpaAction = async (task, params)=>{
45981
+ task.logger.info("开始微信视频号视频发布(RPA 模式)");
45982
+ const videoMeta = buildVideoMetaFromParams(params.videoPath, params.videoMetadata);
45983
+ task.logger.info(`视频: ${videoMeta.width}×${videoMeta.height}, ${videoMeta.duration.toFixed(2)}s, ${(videoMeta.fileSize / 1024 / 1024).toFixed(2)}MB, codec=${videoMeta.codec || "unknown"}`);
45984
+ if (!videoMeta.codec) task.logger.warn("未能读取视频编码格式,跳过 H.264 预检,交由服务端判断");
45985
+ const validationError = validateShipinhaoVideo(params.videoPath, videoMeta);
45986
+ if (validationError) {
45987
+ task.logger.error(`视频校验未通过: ${validationError}`);
45988
+ return utils_response(414, validationError, "");
45989
+ }
45990
+ task.logger.info("视频校验通过");
45991
+ const titleError = validateShipinhaoTitle(params.title);
45992
+ if (titleError) {
45993
+ task.logger.error(`标题校验未通过: ${titleError}`);
45994
+ return utils_response(414, titleError, "");
45995
+ }
45996
+ const unsupported = [
45997
+ params.verticalCoverPath && "verticalCoverPath",
45998
+ params.collection && "collection",
45999
+ params.originalFlag && "originalFlag",
46000
+ params.postWithMemberZoneLink && "postWithMemberZoneLink"
46001
+ ].filter(Boolean);
46002
+ if (unsupported.length) task.logger.warn(`RPA 模式不支持以下参数,将被忽略: ${unsupported.join("、")};如需生效请使用 mockApi 模式`);
46003
+ if (params.tagInfo && 5 === params.tagInfo.tagType) {
46004
+ const shootInfo = params.tagInfo.shootInfo;
46005
+ if (shootInfo && (shootInfo.provinceCode || shootInfo.cityCode)) task.logger.warn("tagInfo.tagType=5 在 RPA 模式下仅支持拍摄时间和国家选择,省市选择需要使用 mockApi 模式");
46006
+ }
46007
+ const tmpCachePath = task.getTmpPath();
46008
+ const page = await task.createPage({
46009
+ url: "https://channels.weixin.qq.com/platform/post/create",
46010
+ show: task.debug,
46011
+ cookies: params.cookies
46012
+ });
46013
+ try {
46014
+ const waitForElement = async (selector, timeout = 10000)=>{
46015
+ try {
46016
+ const element = page.locator(selector);
46017
+ await element.waitFor({
46018
+ state: "visible",
46019
+ timeout
46020
+ });
46021
+ return element;
46022
+ } catch {
46023
+ task.logger.warn(`元素未找到: ${selector}`);
46024
+ return null;
46025
+ }
46026
+ };
46027
+ const retryAction = async (action, maxRetries = 3, delay = 1000)=>{
46028
+ let lastError;
46029
+ for(let i = 0; i < maxRetries; i++)try {
46030
+ return await action();
46031
+ } catch (error) {
46032
+ lastError = error;
46033
+ task.logger.warn(`重试 ${i + 1}/${maxRetries}: ${lastError.message}`);
46034
+ if (i < maxRetries - 1) await page.waitForTimeout(delay);
46035
+ }
46036
+ throw lastError;
46037
+ };
46038
+ task.logger.info("等待页面加载...");
46039
+ task.logger.info("检查登录状态...");
46040
+ if (task.debug) {
46041
+ task.logger.info(`当前页面 URL: ${page.url()}`);
46042
+ const title = await page.title();
46043
+ task.logger.info(`页面标题: ${title}`);
46044
+ }
46045
+ try {
46046
+ await page.waitForSelector(".post-edit-wrap", {
46047
+ state: "visible",
46048
+ timeout: 30000
46049
+ });
46050
+ task.logger.info("✓ 登录状态正常,找到编辑器容器");
46051
+ } catch {
46052
+ task.logger.error("✗ 未找到编辑器,可能登录失效");
46053
+ return {
46054
+ code: 414,
46055
+ message: "登录失效或页面加载异常",
46056
+ data: page.url()
46057
+ };
46058
+ }
46059
+ task.logger.info("页面加载完成,开始填充内容");
46060
+ task.logger.info("开始上传视频");
46061
+ await retryAction(async ()=>{
46062
+ const videoUploadSelectors = [
46063
+ '.ant-upload-btn input[type="file"][accept*="video"]',
46064
+ '.upload input[type="file"][accept*="video"]',
46065
+ 'input[type="file"][accept*="video"]'
46066
+ ];
46067
+ let uploadInput = null;
46068
+ if (task.debug) {
46069
+ const allFileInputs = await page.locator('input[type="file"]').count();
46070
+ task.logger.info(`页面中共找到 ${allFileInputs} 个文件上传输入框`);
46071
+ }
46072
+ for (const selector of videoUploadSelectors){
46073
+ const input = page.locator(selector);
46074
+ const count = await input.count();
46075
+ if (count > 0) {
46076
+ uploadInput = input.first();
46077
+ task.logger.info(`找到视频上传输入框: ${selector}`);
46078
+ break;
46079
+ }
46080
+ }
46081
+ if (!uploadInput) {
46082
+ task.logger.warn("未找到视频上传输入框,等待 3 秒后重试...");
46083
+ await page.waitForTimeout(3000);
46084
+ const anyFileInput = page.locator('input[type="file"]');
46085
+ const inputCount = await anyFileInput.count();
46086
+ if (inputCount > 0) {
46087
+ uploadInput = anyFileInput.first();
46088
+ task.logger.info(`找到文件输入框(共 ${inputCount} 个)`);
46089
+ } else {
46090
+ if (task.debug) {
46091
+ const screenshotPath = external_node_path_default().join(tmpCachePath, `upload-error-${Date.now()}.png`);
46092
+ await page.screenshot({
46093
+ path: screenshotPath,
46094
+ fullPage: true
46095
+ });
46096
+ task.logger.error(`未找到上传输入框,已截图保存至: ${screenshotPath}`);
46097
+ }
46098
+ throw new Error("未找到视频上传输入框");
46099
+ }
46100
+ }
46101
+ await uploadInput.setInputFiles(params.videoPath);
46102
+ task.logger.info("视频上传成功");
46103
+ await page.waitForTimeout(5000);
46104
+ });
46105
+ if (params.coverPath) {
46106
+ task.logger.info("开始上传封面");
46107
+ await retryAction(async ()=>{
46108
+ const coverUploadBtn = await waitForElement(".cover-upload-btn", 10000);
46109
+ if (coverUploadBtn) {
46110
+ const coverInput = page.locator('.cover-upload-btn input[type="file"]');
46111
+ await coverInput.setInputFiles(params.coverPath);
46112
+ task.logger.info("封面上传成功");
46113
+ await page.waitForTimeout(2000);
46114
+ }
46115
+ });
46116
+ }
46117
+ const descriptionText = payload_buildDescription({
46118
+ description: params.description,
46119
+ topics: params.topics,
46120
+ mentionedUsers: params.mentionedUsers
46121
+ });
46122
+ if (descriptionText) {
46123
+ task.logger.info("填写视频描述");
46124
+ await retryAction(async ()=>{
46125
+ const descEditor = await waitForElement(".input-editor", 10000);
46126
+ if (!descEditor) throw new Error("未找到描述编辑器");
46127
+ await descEditor.click();
46128
+ await page.waitForTimeout(500);
46129
+ await descEditor.evaluate((el)=>{
46130
+ el.textContent = "";
46131
+ });
46132
+ await page.waitForTimeout(300);
46133
+ task.logger.info("已清空编辑器内容");
46134
+ await descEditor.pressSequentially(descriptionText, {
46135
+ delay: 10
46136
+ });
46137
+ await page.waitForTimeout(500);
46138
+ task.logger.info("描述填写完成");
46139
+ });
46140
+ }
46141
+ if (params.title) {
46142
+ task.logger.info(`填写标题: ${params.title}`);
46143
+ const title = params.title;
46144
+ await retryAction(async ()=>{
46145
+ const titleInput = await waitForElement("#container-wrap div.form-item-body.short-title-wrap input", 10000);
46146
+ if (!titleInput) throw new Error("未找到标题输入框");
46147
+ await titleInput.click();
46148
+ await titleInput.clear({
46149
+ timeout: 3000
46150
+ });
46151
+ await titleInput.fill(title, {
46152
+ timeout: 5000
46153
+ });
46154
+ task.logger.info("标题填写完成");
46155
+ });
46156
+ }
46157
+ if (params.location) {
46158
+ task.logger.info(`选择地点: ${params.location.city}`);
46159
+ const instance = page.locator(".position-display-wrap");
46160
+ await instance.click();
46161
+ await page.waitForTimeout(1000);
46162
+ await page.locator(".location-filter-wrap input").fill(params.location.city);
46163
+ await page.waitForTimeout(2000);
46164
+ const poperInstance = page.locator(".location-filter-wrap .common-option-list-wrap .option-item");
46165
+ await poperInstance.nth(1).waitFor();
46166
+ await poperInstance.nth(1).click();
46167
+ task.logger.info("地点选择完成");
46168
+ }
46169
+ if (params.collection) {
46170
+ task.logger.info(`选择合集: ${params.collection.collectionName}`);
46171
+ const instanceCollection = page.locator(".post-album-display-wrap");
46172
+ await instanceCollection.click();
46173
+ await page.waitForTimeout(1000);
46174
+ page.locator(".post-album-wrap .option-item").filter({
46175
+ hasText: params.collection.collectionName
46176
+ }).first().click({
46177
+ force: true
46178
+ });
46179
+ }
46180
+ if (params.link) {
46181
+ task.logger.info(`设置扩展阅读链接: ${params.link.title}`);
46182
+ await page.locator(".post-link-wrap .link-display-wrap").click();
46183
+ await page.waitForTimeout(300);
46184
+ const linkTypeText = 2 === params.link.urlType ? "红包封面" : "公众号文章";
46185
+ await page.locator(".link-option-item .title-wrap span").filter({
46186
+ hasText: linkTypeText
46187
+ }).click();
46188
+ await page.waitForTimeout(300);
46189
+ const placeholder = 2 === params.link.urlType ? "粘贴红包封面链接" : "粘贴公众号文章链接";
46190
+ await page.locator(`.link-input-wrap input[placeholder="${placeholder}"]`).fill(params.link.link);
46191
+ await page.waitForTimeout(500);
46192
+ task.logger.info(`已设置${linkTypeText}: ${params.link.link}`);
46193
+ }
46194
+ if (params.event) {
46195
+ task.logger.info(`选择活动: ${params.event.eventName}`);
46196
+ await page.locator(".post-activity-wrap .activity-display").click();
46197
+ await page.waitForTimeout(500);
46198
+ await page.locator(".activity-filter-wrap .weui-desktop-form__input[placeholder='搜索活动']").fill(params.event.eventName);
46199
+ await page.waitForTimeout(500);
46200
+ const searchLoading = page.locator(".search-loading");
46201
+ await searchLoading.waitFor({
46202
+ state: "hidden",
46203
+ timeout: 5000
46204
+ }).catch(()=>{
46205
+ task.logger.warn("活动搜索加载超时,继续尝试选择");
46206
+ });
46207
+ const activityItem = page.locator(".option-item .activity-item .activity-item-info .name").filter({
46208
+ hasText: params.event.eventName
46209
+ });
46210
+ const count = await activityItem.count();
46211
+ if (count > 0) {
46212
+ await activityItem.first().click();
46213
+ await page.waitForTimeout(300);
46214
+ task.logger.info(`已选择活动: ${params.event.eventName}`);
46215
+ } else {
46216
+ task.logger.warn(`未找到活动: ${params.event.eventName},将不参与活动`);
46217
+ await page.locator(".post-activity-wrap .activity-display").click();
46218
+ await page.waitForTimeout(300);
46219
+ }
46220
+ }
46221
+ if (params.scheduledTime) {
46222
+ task.logger.info("设置定时发布");
46223
+ const timingRadio = page.locator(".weui-desktop-form__check-label").filter({
46224
+ hasNotText: "不定时"
46225
+ }).first();
46226
+ await timingRadio.click();
46227
+ await page.waitForTimeout(500);
46228
+ const instance = page.locator(".weui-desktop-picker__date");
46229
+ await instance.click();
46230
+ const dateD = utils_TimeFormatter.format(1000 * params.scheduledTime, "d");
46231
+ const nowMonth = utils_TimeFormatter.format(Date.now(), "MM月");
46232
+ const nowMonthText = utils_TimeFormatter.format(Date.now(), "M月");
46233
+ const month = utils_TimeFormatter.format(1000 * params.scheduledTime, "MM月");
46234
+ const monthLocator = await page.locator("weui-desktop-picker__panel__label").filter({
46235
+ hasText: month
46236
+ }).first();
46237
+ if (!monthLocator) {
46238
+ await page.locator(".weui-desktop-picker__panel__label").filter({
46239
+ hasText: nowMonth
46240
+ }).first().click();
46241
+ await page.waitForTimeout(500);
46242
+ await page.locator(".weui-desktop-picker__table-row td a").filter({
46243
+ hasText: nowMonthText
46244
+ }).first().click();
46245
+ }
46246
+ await page.waitForTimeout(500);
46247
+ await page.locator(".weui-desktop-picker__table-row td a").filter({
46248
+ hasText: dateD
46249
+ }).first().click();
46250
+ await page.locator(".weui-desktop-form__input-wrp input[placeholder*='请选择时间']").fill(utils_TimeFormatter.format(1000 * params.scheduledTime, "hh:mm"));
46251
+ await page.locator("i.weui-desktop-icon__time").click();
46252
+ await page.locator(".post-time-wrap .form-item .label").filter({
46253
+ hasText: "发表时间"
46254
+ }).click();
46255
+ }
46256
+ if (params.tagInfo) {
46257
+ task.logger.info(`设置视频标注: tagType=${params.tagInfo.tagType}`);
46258
+ await page.locator(".mark-tag-select").click();
46259
+ await page.waitForTimeout(300);
46260
+ const tagTypeTextMap = {
46261
+ 0: "无需标注",
46262
+ 1: "含AI生成内容",
46263
+ 2: "内容包含营销广告",
46264
+ 3: "内容为虚构剧情,仅供娱乐",
46265
+ 5: "内容为自行拍摄",
46266
+ 7: "内容为转载",
46267
+ 8: "个人观点,仅供参考"
46268
+ };
46269
+ const tagText = tagTypeTextMap[params.tagInfo.tagType];
46270
+ if (tagText) {
46271
+ await page.locator(".mark-tag-option .option-main").filter({
46272
+ hasText: tagText
46273
+ }).click();
46274
+ await page.waitForTimeout(300);
46275
+ if (5 === params.tagInfo.tagType) {
46276
+ const shootInfo = params.tagInfo.shootInfo;
46277
+ if (shootInfo) {
46278
+ task.logger.info("填写拍摄时间和地点...");
46279
+ await page.waitForTimeout(500);
46280
+ if (shootInfo.postTimestamp) {
46281
+ task.logger.info(`设置拍摄时间: ${shootInfo.postTimestamp}`);
46282
+ const timestamp = 1000 * parseInt(shootInfo.postTimestamp, 10);
46283
+ const date = new Date(timestamp);
46284
+ await page.locator(".original-dialog-content .weui-desktop-picker__date input[placeholder*='请选择拍摄时间']").click();
46285
+ await page.waitForTimeout(300);
46286
+ const dayNum = date.getDate();
46287
+ await page.locator(".weui-desktop-picker__table a").filter({
46288
+ hasText: new RegExp(`^\\s*${dayNum}\\s*$`)
46289
+ }).first().click();
46290
+ await page.waitForTimeout(300);
46291
+ }
46292
+ if (shootInfo.countryCode || shootInfo.provinceCode || shootInfo.cityCode) {
46293
+ task.logger.info("设置拍摄地点...");
46294
+ await page.locator(".original-dialog-content .weui-desktop-form__dropdowncascade .weui-desktop-form__dropdowncascade__dt").click();
46295
+ await page.waitForTimeout(300);
46296
+ if (1156 === shootInfo.countryCode) {
46297
+ await page.locator(".weui-desktop-dropdown__list-ele .weui-desktop-dropdown__list-ele__text").filter({
46298
+ hasText: "中国"
46299
+ }).click();
46300
+ await page.waitForTimeout(300);
46301
+ task.logger.warn("RPA 模式下暂不支持选择具体省份和城市,仅选择了国家");
46302
+ } else task.logger.warn(`不支持的国家代码: ${shootInfo.countryCode},跳过地点设置`);
46303
+ }
46304
+ const confirmBtn = await waitForElement(".weui-desktop-dialog .weui-desktop-btn_primary");
46305
+ if (confirmBtn) {
46306
+ await confirmBtn.click();
46307
+ await page.waitForTimeout(300);
46308
+ }
46309
+ } else task.logger.warn("tagType=5 需要提供 shootInfo 字段(拍摄时间和地点)");
46310
+ }
46311
+ if (7 === params.tagInfo.tagType) {
46312
+ const repostSource = params.tagInfo.repostSource;
46313
+ if (repostSource) {
46314
+ task.logger.info(`填写转载来源: ${repostSource}`);
46315
+ await page.waitForTimeout(500);
46316
+ await page.locator(".repost-dialog-content .repost-textarea").fill(repostSource);
46317
+ await page.waitForTimeout(300);
46318
+ const confirmBtn = await waitForElement(".weui-desktop-dialog .weui-desktop-btn_primary");
46319
+ if (confirmBtn) {
46320
+ await confirmBtn.click();
46321
+ await page.waitForTimeout(300);
46322
+ }
46323
+ } else task.logger.warn("tagType=7 需要提供 repostSource 字段(转载来源)");
46324
+ }
46325
+ } else task.logger.warn(`未知的 tagType: ${params.tagInfo.tagType},跳过标注设置`);
46326
+ }
46327
+ task.logger.info("准备发布...");
46328
+ await page.waitForTimeout(500);
46329
+ let videoId = "";
46330
+ const handleResponse = async (response)=>{
46331
+ const url = response.url();
46332
+ if (url.includes("/post/post_create")) {
46333
+ const jsonResponse = await response.json();
46334
+ page.off("response", handleResponse);
46335
+ videoId = jsonResponse.object?.id || jsonResponse.data?.objectId || "";
46336
+ }
46337
+ };
46338
+ page.on("response", handleResponse);
46339
+ task._timerRecord.PrePublish = Date.now();
46340
+ 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";
46341
+ task.logger.info("等待视频上传完成(预览区媒体操作栏出现)...");
46342
+ const uploadTimeout = 600000;
46343
+ const uploadWaitStart = Date.now();
46344
+ let lastProgressLog = 0;
46345
+ while(true){
46346
+ const ready = await page.evaluate((selector)=>{
46347
+ const host = document.querySelector("#container-wrap > div.container-center > div > wujie-app");
46348
+ const root = host?.shadowRoot;
46349
+ if (!root) return false;
46350
+ return !!root.querySelector(selector);
46351
+ }, MEDIA_OPR_SELECTOR);
46352
+ if (ready) break;
46353
+ const elapsed = Date.now() - uploadWaitStart;
46354
+ if (elapsed > uploadTimeout) throw new Error(`视频上传超时,预览区未就绪(已等待 ${Math.round(elapsed / 1000)}s)`);
46355
+ if (elapsed - lastProgressLog >= 15000) {
46356
+ lastProgressLog = elapsed;
46357
+ task.logger.info(`视频仍在上传中... 已等待 ${Math.round(elapsed / 1000)}s`);
46358
+ }
46359
+ await page.waitForTimeout(1000);
46360
+ }
46361
+ task.logger.info(`视频上传完成(等待 ${Math.round((Date.now() - uploadWaitStart) / 1000)}s)`);
46362
+ const clicked = await page.evaluate(()=>{
46363
+ const host = document.querySelector("#container-wrap > div.container-center > div > wujie-app");
46364
+ const root = host?.shadowRoot;
46365
+ if (!root) return "未找到 wujie-app shadowRoot";
46366
+ const btns = Array.from(root.querySelectorAll(".form-btns .weui-desktop-btn"));
46367
+ const target = btns.find((el)=>(el.textContent || "").includes("发表"));
46368
+ if (!target) return "未找到发表按钮";
46369
+ if (target.classList.contains("weui-desktop-btn_disabled")) return "发表按钮仍处于禁用状态";
46370
+ target.click();
46371
+ return null;
46372
+ });
46373
+ if (clicked) throw new Error(clicked);
46374
+ task.logger.info("已点击发布按钮,等待响应...");
46375
+ try {
46376
+ await page.waitForURL((url)=>url.href !== page.url(), {
46377
+ timeout: 30000
46378
+ });
46379
+ task.logger.info(`发布成功,页面已跳转: ${page.url()}`);
46380
+ } catch {
46381
+ task.logger.warn("等待页面跳转超时,可能发布失败或网络慢,继续关闭页面");
46382
+ }
46383
+ await page.close();
46384
+ return success(videoId, "发布成功");
46385
+ } catch (error) {
46386
+ let errorMsg = error instanceof Error ? error.message : String(error);
46387
+ if (errorMsg.includes("context or browser has been closed")) errorMsg = "浏览器上下文已被关闭";
46388
+ task.logger.error(`微信视频号视频发布失败: ${errorMsg}`);
46389
+ return utils_response(414, `微信视频号视频发布失败: ${errorMsg}`, "");
46390
+ }
46391
+ };
46392
+ const ShipinhaoPublishVideoParamsSchema = ActionCommonParamsSchema.extend({
46393
+ videoPath: classic_schemas_string().min(1),
46394
+ videoMetadata: classic_schemas_object({
46395
+ duration: classic_schemas_number().positive(),
46396
+ width: classic_schemas_number().int().positive(),
46397
+ height: classic_schemas_number().int().positive(),
46398
+ fileSize: classic_schemas_number().int().positive(),
46399
+ path: classic_schemas_string().min(1).optional(),
46400
+ fileName: classic_schemas_string().min(1)
46401
+ }),
46402
+ coverPath: classic_schemas_string().min(1),
46403
+ verticalCoverPath: classic_schemas_string().min(1).optional(),
46404
+ description: classic_schemas_string(),
46405
+ title: classic_schemas_string().optional(),
46406
+ scheduledTime: classic_schemas_number().int().positive().optional(),
46407
+ isImmediatelyPublish: classic_schemas_boolean().optional(),
46408
+ topics: classic_schemas_array(classic_schemas_string()).optional(),
46409
+ mentionedUsers: classic_schemas_array(classic_schemas_object({
46410
+ nickname: classic_schemas_string()
46411
+ })).optional(),
46412
+ collection: classic_schemas_object({
46413
+ collectionId: classic_schemas_string(),
46414
+ collectionName: classic_schemas_string()
46415
+ }).optional(),
46416
+ event: classic_schemas_object({
46417
+ eventTopicId: classic_schemas_string(),
46418
+ eventName: classic_schemas_string(),
46419
+ eventCreatorNickname: classic_schemas_string().optional()
46420
+ }).optional(),
46421
+ link: classic_schemas_object({
46422
+ link: classic_schemas_string(),
46423
+ title: classic_schemas_string(),
46424
+ urlType: classic_schemas_number().int().default(1)
46425
+ }).optional(),
46426
+ tagInfo: looseObject({
46427
+ tagType: classic_schemas_number().int()
46428
+ }).optional(),
46429
+ originalFlag: schemas_union([
46430
+ literal(0),
46431
+ literal(1)
46432
+ ]).optional(),
46433
+ postWithMemberZoneLink: schemas_union([
46434
+ literal(0),
46435
+ literal(1)
46436
+ ]).optional(),
46437
+ location: classic_schemas_object({
46438
+ latitude: classic_schemas_number(),
46439
+ longitude: classic_schemas_number(),
46440
+ city: classic_schemas_string(),
46441
+ poiName: classic_schemas_string().optional(),
46442
+ address: classic_schemas_string().optional(),
46443
+ poiClassifyId: classic_schemas_string().optional()
46444
+ }).optional()
46445
+ });
46446
+ const shipinhaoPublishVideo = async (task, params)=>{
46447
+ task.logger.info(`[shipinhaoPublishVideo] actionType: ${params.actionType}`);
46448
+ if ("rpa" === params.actionType) return shipinhaoPublishVideo_rpa_rpaAction(task, params);
46449
+ if ("mockApi" === params.actionType) return shipinhaoPublishVideo_mock_mockAction(task, params);
46450
+ return executeAction(shipinhaoPublishVideo_mock_mockAction, shipinhaoPublishVideo_rpa_rpaAction)(task, params);
46451
+ };
44590
46452
  const ShipinhaoSendMsgParamsSchema = ActionCommonParamsSchema.extend({
44591
46453
  toUsername: classic_schemas_string().min(1, "接收者用户名不能为空"),
44592
46454
  sessionId: classic_schemas_string().min(1, "会话ID不能为空"),
@@ -44601,7 +46463,7 @@ var __webpack_exports__ = {};
44601
46463
  pathOrUrl: classic_schemas_string().min(1, "图片路径或URL不能为空")
44602
46464
  }).optional()
44603
46465
  });
44604
- const CHUNK_SIZE = 524288;
46466
+ const shipinhaoSendMsg_CHUNK_SIZE = 524288;
44605
46467
  async function shipinhaoSendMsg_getUserInfo(cookieStr, http) {
44606
46468
  const url = `https://channels.weixin.qq.com/cgi-bin/mmfinderassistant-bin/auth/auth_data?_rid=${rid()}`;
44607
46469
  const headers = {
@@ -44679,15 +46541,16 @@ var __webpack_exports__ = {};
44679
46541
  imageBuffer = Buffer.from(await external_node_fs_default().promises.readFile(filePath));
44680
46542
  }
44681
46543
  } catch (err) {
44682
- return utils_response(414, `读取图片失败: ${err instanceof Error ? err.message : String(err)}`, void 0);
46544
+ _task.logger.error(`读取图片失败: ${err instanceof Error ? err.message : String(err)}`);
46545
+ return utils_response(414, USER_MESSAGE.IMAGE_UPLOAD_FAILED, void 0);
44683
46546
  }
44684
46547
  const md5 = (0, external_node_crypto_namespaceObject.createHash)("md5").update(imageBuffer).digest("hex");
44685
46548
  const timestamp = Date.now().toString();
44686
- const totalChunks = Math.ceil(imageBuffer.length / CHUNK_SIZE);
46549
+ const totalChunks = Math.ceil(imageBuffer.length / shipinhaoSendMsg_CHUNK_SIZE);
44687
46550
  console.log(`分片上传md5${md5}`);
44688
46551
  let lastRes;
44689
46552
  for(let i = 0; i < totalChunks; i++){
44690
- const chunkBuffer = imageBuffer.slice(i * CHUNK_SIZE, (i + 1) * CHUNK_SIZE);
46553
+ const chunkBuffer = imageBuffer.slice(i * shipinhaoSendMsg_CHUNK_SIZE, (i + 1) * shipinhaoSendMsg_CHUNK_SIZE);
44691
46554
  const requestData = {
44692
46555
  content: `data:application/octet-stream;base64,${chunkBuffer.toString("base64")}`,
44693
46556
  chunk: i,
@@ -45140,6 +47003,13 @@ var __webpack_exports__ = {};
45140
47003
  const uploadImages = async (images)=>await Promise.all(images.map(async (url)=>{
45141
47004
  const fileName = getFilenameFromUrl(url);
45142
47005
  const image = await downloadImage(url, external_node_path_default().join(tmpCachePath, fileName));
47006
+ const stats = external_node_fs_default().statSync(image);
47007
+ const maxSize = 20971520;
47008
+ if (stats.size > maxSize) throw {
47009
+ code: 414,
47010
+ message: "头条号平台:单张图片不得超过 20MB",
47011
+ data: ""
47012
+ };
45143
47013
  const formData = new (form_data_default())();
45144
47014
  formData.append("image", external_node_fs_default().createReadStream(image));
45145
47015
  const response = await http.api({
@@ -47190,18 +49060,10 @@ var __webpack_exports__ = {};
47190
49060
  });
47191
49061
  } catch (error) {
47192
49062
  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));
49063
+ const classified = classifyPublishError(handledError);
49064
+ if (classified) {
49065
+ const message = `${classified.userMessage}${task.debug ? ` ${http.proxyInfo}` : ""}`;
49066
+ task.logger.error(`[weixinPublish] ${classified.category},直接返回: ${handledError.message} (code=${handledError.code})`, stringifyError(handledError));
47205
49067
  await updateTaskState?.({
47206
49068
  state: types_TaskState.FAILED,
47207
49069
  error: message
@@ -48431,6 +50293,12 @@ var __webpack_exports__ = {};
48431
50293
  const fileName = getFilenameFromUrl(url);
48432
50294
  const localUrl = await downloadImage(url, external_node_path_default().join(tmpCachePath, fileName));
48433
50295
  const fileBuffer = external_node_fs_default().readFileSync(localUrl);
50296
+ const maxSize = 33554432;
50297
+ if (fileBuffer.byteLength > maxSize) throw {
50298
+ code: 414,
50299
+ message: "小红书平台:单张图片不得超过 32MB",
50300
+ data: ""
50301
+ };
48434
50302
  let width = 0;
48435
50303
  let height = 0;
48436
50304
  try {
@@ -48669,6 +50537,7 @@ var __webpack_exports__ = {};
48669
50537
  });
48670
50538
  return success(data, message);
48671
50539
  }
50540
+ task.logger.info(`[xiaohongshuPublish] publishData: ${JSON.stringify(publishData)} `);
48672
50541
  let publishResult;
48673
50542
  try {
48674
50543
  publishResult = await proxyHttp.api({
@@ -48679,23 +50548,15 @@ var __webpack_exports__ = {};
48679
50548
  defaultErrorMsg: "文章发布异常,请稍后重试。"
48680
50549
  }, {
48681
50550
  retries: 2,
48682
- retryDelay: 500,
48683
- timeout: 12000
50551
+ retryDelay: 3000,
50552
+ timeout: 30000
48684
50553
  });
48685
50554
  } catch (error) {
48686
50555
  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));
50556
+ const classified = classifyPublishError(handledError);
50557
+ if (classified) {
50558
+ const message = `${classified.userMessage}${task.debug ? ` ${http.proxyInfo}` : ""}`;
50559
+ task.logger.error(`[xiaohongshuPublish] ${classified.category},直接返回: ${handledError.message} (code=${handledError.code})`, stringifyError(handledError));
48699
50560
  await updateTaskState?.({
48700
50561
  state: types_TaskState.FAILED,
48701
50562
  error: message
@@ -50391,6 +52252,14 @@ var __webpack_exports__ = {};
50391
52252
  this.task = task;
50392
52253
  this.task.logger.info(`当前包版本:Share=>${package_namespaceObject.i8} Action=>${package_namespaceObject_0.i8}`);
50393
52254
  }
52255
+ getActionVersionMarker() {
52256
+ return {
52257
+ version: package_namespaceObject_0.i8,
52258
+ shareVersion: package_namespaceObject.i8,
52259
+ marker: `Action_${package_namespaceObject_0.i8}_${package_namespaceObject.i8}`,
52260
+ timestamp: new Date().toLocaleString()
52261
+ };
52262
+ }
50394
52263
  async bindTask(func, params) {
50395
52264
  let responseData;
50396
52265
  this.task.isBeta = this.task?.isFeatOn ? this.task?.isFeatOn(BetaFlag) : false;
@@ -50614,6 +52483,9 @@ var __webpack_exports__ = {};
50614
52483
  shipinhaoPublish(params) {
50615
52484
  return this.bindTask(shipinhaoPublish, params);
50616
52485
  }
52486
+ shipinhaoPublishVideo(params) {
52487
+ return this.bindTask(shipinhaoPublishVideo, params);
52488
+ }
50617
52489
  douyinGetTopics(params) {
50618
52490
  return this.bindTask(douyinGetTopics, params);
50619
52491
  }
@@ -50674,4 +52546,4 @@ if (__webpack_exports__.__esModule) Object.defineProperty(__webpack_export_targe
50674
52546
  });
50675
52547
 
50676
52548
  //# sourceMappingURL=bundle.js.map
50677
- //# debugId=1b1757c5-d32a-56c9-a781-bb1e22dcee63
52549
+ //# debugId=6fdb1841-1467-5c52-bdfa-6acbd4df3bcb