@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/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
 
2
- !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]="4505f4f9-b586-5fae-8a9f-3ce0ceb72967")}catch(e){}}();
2
+ !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]="4653233b-4a56-52c6-8a3b-2a28934c66cb")}catch(e){}}();
3
3
  var __webpack_modules__ = {
4
4
  "./src/utils/XhsXsCommonEnc.js": function(module) {
5
5
  var encrypt_lookup = [
@@ -4366,6 +4366,7 @@ var __webpack_exports__ = {};
4366
4366
  SessionCheckResultSchema: ()=>SessionCheckResultSchema,
4367
4367
  DouyinGetCommentReplyListParamsSchema: ()=>DouyinGetCommentReplyListParamsSchema,
4368
4368
  DouyinCreateCommentReplyParamsSchema: ()=>DouyinCreateCommentReplyParamsSchema,
4369
+ ShipinhaoPublishVideoParamsSchema: ()=>ShipinhaoPublishVideoParamsSchema,
4369
4370
  DouyinGetHotParamsSchema: ()=>DouyinGetHotParamsSchema,
4370
4371
  DouyinGetMusicParamsSchema: ()=>DouyinGetMusicParamsSchema,
4371
4372
  FetchArticlesDataSchema: ()=>FetchArticlesDataSchema,
@@ -4402,9 +4403,7 @@ var __webpack_exports__ = {};
4402
4403
  });
4403
4404
  const package_json_namespaceObject = require("@iflyrpa/share/package.json");
4404
4405
  var package_json_default = /*#__PURE__*/ __webpack_require__.n(package_json_namespaceObject);
4405
- var package_namespaceObject = {
4406
- i8: "4.0.9"
4407
- };
4406
+ var package_namespaceObject = JSON.parse('{"i8":"4.1.0-beta.0"}');
4408
4407
  const share_namespaceObject = require("@iflyrpa/share");
4409
4408
  const external_node_fs_namespaceObject = require("node:fs");
4410
4409
  var external_node_fs_default = /*#__PURE__*/ __webpack_require__.n(external_node_fs_namespaceObject);
@@ -4420,6 +4419,124 @@ var __webpack_exports__ = {};
4420
4419
  var external_node_crypto_default = /*#__PURE__*/ __webpack_require__.n(external_node_crypto_namespaceObject);
4421
4420
  const external_axios_namespaceObject = require("axios");
4422
4421
  var external_axios_default = /*#__PURE__*/ __webpack_require__.n(external_axios_namespaceObject);
4422
+ const USER_MESSAGE = {
4423
+ PROXY_UNAVAILABLE: "代理暂时不可用,请稍后重试或使用本地IP",
4424
+ NETWORK_ERROR: "网络异常,请稍后重试",
4425
+ SYSTEM_ERROR: "系统异常,请稍后重试或联系客服",
4426
+ PUBLISH_NETWORK: "发布失败,网络不稳定,请稍后重试",
4427
+ DOUYIN_ACCOUNT_FETCH_FAILED: "抖音数据获取失败,请稍后重试",
4428
+ SHIPINHAO_ACCOUNT_FETCH_FAILED: "视频号数据获取失败,请稍后重试",
4429
+ DOUYIN_POST_FETCH_FAILED: "抖音作品数据获取失败,请稍后重试",
4430
+ SHIPINHAO_POST_FETCH_FAILED: "视频号作品数据获取失败,请稍后重试",
4431
+ BJH_POST_FETCH_FAILED: "百家号作品数据获取失败,请稍后重试",
4432
+ TT_POST_FETCH_FAILED: "头条号作品数据获取失败,请稍后重试",
4433
+ QRCODE_FETCH_FAILED: "认证二维码获取失败,请稍后重试",
4434
+ IMAGE_UPLOAD_FAILED: "图片上传失败,请稍后重试或联系客服"
4435
+ };
4436
+ const NETWORK_CODES = [
4437
+ 500,
4438
+ 502,
4439
+ 503,
4440
+ 504
4441
+ ];
4442
+ function classifyPublishError(handledError) {
4443
+ const { code } = handledError;
4444
+ const isProxyRequest = handledError.extra?.isProxyRequest === true;
4445
+ if (!NETWORK_CODES.includes(code) && 599 !== code) return null;
4446
+ const category = 599 === code || isProxyRequest ? "代理错误" : "网络错误";
4447
+ return {
4448
+ category,
4449
+ userMessage: USER_MESSAGE.PUBLISH_NETWORK
4450
+ };
4451
+ }
4452
+ const RPA_ERROR_WEBHOOK_URL = "https://open.xfchat.iflytek.com/open-apis/bot/v2/hook/d202c0dc-5af5-40bc-83ed-abc677caa4a5";
4453
+ const ALARM_THROTTLE_MS = 60000;
4454
+ const lastSentAt = new Map();
4455
+ const postFeishuWebhook = (webhookUrl, payload)=>external_axios_default().post(webhookUrl, payload, {
4456
+ headers: {
4457
+ "Content-Type": "application/json"
4458
+ },
4459
+ timeout: 10000
4460
+ });
4461
+ const buildFeishuPostMessage = (report)=>{
4462
+ const content = [
4463
+ [
4464
+ {
4465
+ tag: "text",
4466
+ text: `平台:${report.platform || "未知平台"}`
4467
+ }
4468
+ ],
4469
+ [
4470
+ {
4471
+ tag: "text",
4472
+ text: `错误信息:${report.msg || "未知错误信息"}`
4473
+ }
4474
+ ],
4475
+ [
4476
+ {
4477
+ tag: "text",
4478
+ text: `错误类型:${report.errorType || "未知错误类型"}`
4479
+ }
4480
+ ],
4481
+ [
4482
+ {
4483
+ tag: "text",
4484
+ text: `阶段:${report.stage || "未知阶段"}`
4485
+ }
4486
+ ],
4487
+ [
4488
+ {
4489
+ tag: "text",
4490
+ text: `等级:${report.level}`
4491
+ }
4492
+ ],
4493
+ [
4494
+ {
4495
+ tag: "text",
4496
+ text: `来源:${report.source}`
4497
+ }
4498
+ ]
4499
+ ];
4500
+ if (void 0 !== report.code && null !== report.code) content.push([
4501
+ {
4502
+ tag: "text",
4503
+ text: `接口错误码:${report.code}`
4504
+ }
4505
+ ]);
4506
+ if (report.url) content.push([
4507
+ {
4508
+ tag: "text",
4509
+ text: `地址:${report.url}`
4510
+ }
4511
+ ]);
4512
+ if ("alarm" === report.level) content.push([
4513
+ {
4514
+ tag: "at",
4515
+ user_id: "all"
4516
+ }
4517
+ ]);
4518
+ return {
4519
+ msg_type: "post",
4520
+ content: {
4521
+ post: {
4522
+ zh_cn: {
4523
+ title: report.title || "RPA异常",
4524
+ content
4525
+ }
4526
+ }
4527
+ }
4528
+ };
4529
+ };
4530
+ const reportFeishuAlarm = (report)=>{
4531
+ try {
4532
+ const key = `${report.platform}|${report.source}|${report.errorType}|${report.code ?? ""}`;
4533
+ const now = Date.now();
4534
+ const last = lastSentAt.get(key);
4535
+ if (last && now - last < ALARM_THROTTLE_MS) return;
4536
+ lastSentAt.set(key, now);
4537
+ postFeishuWebhook(RPA_ERROR_WEBHOOK_URL, buildFeishuPostMessage(report)).catch(()=>{});
4538
+ } catch {}
4539
+ };
4423
4540
  const external_socks_proxy_agent_namespaceObject = require("socks-proxy-agent");
4424
4541
  const PROXY_CREDENTIALS = [
4425
4542
  {
@@ -4522,9 +4639,20 @@ var __webpack_exports__ = {};
4522
4639
  url: "https://fetdev.iflysec.com/ip-pool/pool/eip/proxy",
4523
4640
  data: params
4524
4641
  }).catch((err)=>{
4642
+ reportFeishuAlarm({
4643
+ level: "alarm",
4644
+ platform: "ip-pool",
4645
+ source: "proxy",
4646
+ stage: "POST /ip-pool/pool/eip/proxy",
4647
+ errorType: "PROXY_REQUEST_FAILED",
4648
+ code: err?.code,
4649
+ msg: `请求代理失败:${err.message},区域:${addr ?? "-"},AccountId:${accountId ?? "-"}`,
4650
+ url: "https://fetdev.iflysec.com/ip-pool/pool/eip/proxy",
4651
+ title: "代理异常"
4652
+ });
4525
4653
  throw {
4526
4654
  code: 414,
4527
- message: `请求代理失败:${err.message}`,
4655
+ message: USER_MESSAGE.PROXY_UNAVAILABLE,
4528
4656
  data: {}
4529
4657
  };
4530
4658
  });
@@ -4544,12 +4672,53 @@ var __webpack_exports__ = {};
4544
4672
  } : null;
4545
4673
  return proxyAgent;
4546
4674
  }
4675
+ const ALARM_STATUS = new Set([
4676
+ 401,
4677
+ 403,
4678
+ 429,
4679
+ 461,
4680
+ 471
4681
+ ]);
4682
+ const HTTP_STATUS_MESSAGE = {
4683
+ 400: "请求参数错误,请检查参数格式是否正确!",
4684
+ 401: "登录状态已失效,请重新登录后重试!",
4685
+ 403: "没有访问权限,账号可能受限或签名已失效!",
4686
+ 404: "请求的资源不存在,请检查接口地址!",
4687
+ 405: "请求方法不被允许,请检查接口调用方式!",
4688
+ 406: "服务端无法返回可接受的内容格式!",
4689
+ 407: "代理需要身份验证,请检查代理配置!",
4690
+ 408: "请求超时,请检查网络连接!",
4691
+ 409: "请求冲突,资源状态已变更,请刷新后重试!",
4692
+ 410: "请求的资源已被移除!",
4693
+ 412: "请求前置条件不满足,请刷新后重试!",
4694
+ 413: "提交内容过大,请压缩或分批后重试!",
4695
+ 414: "请求地址过长,请检查参数!",
4696
+ 415: "不支持的内容类型,请检查请求格式!",
4697
+ 422: "请求内容校验失败,请检查参数内容!",
4698
+ 423: "资源已被锁定,请稍后重试!",
4699
+ 429: "请求过于频繁,请稍后重试!",
4700
+ 431: "请求头过大,请清理 Cookie 后重试!",
4701
+ 451: "内容不合规或因法律原因被拒绝!",
4702
+ 461: "账号可能受限,请在网页上完成验证后重试!",
4703
+ 471: "账号可能受限,请在网页上完成验证后重试!",
4704
+ 500: "服务器内部错误,请稍后重试!",
4705
+ 501: "服务端不支持该请求,请稍后重试!",
4706
+ 502: "网关错误,请稍后重试!",
4707
+ 503: "服务暂时不可用,请稍后重试!",
4708
+ 504: "网关超时,请稍后重试!",
4709
+ 507: "服务端存储空间不足,请稍后重试!",
4710
+ 509: "服务带宽超限,请稍后重试!",
4711
+ 520: "服务端返回未知错误,请稍后重试!",
4712
+ 521: "源站拒绝连接,请稍后重试!",
4713
+ 522: "源站连接超时,请稍后重试!",
4714
+ 524: "源站响应超时,请稍后重试!"
4715
+ };
4547
4716
  class Http {
4548
4717
  static handleApiError(error) {
4549
4718
  if (error && "object" == typeof error && "code" in error && "message" in error) return error;
4550
4719
  return {
4551
4720
  code: 500,
4552
- message: error instanceof Error ? error.message : "未知错误",
4721
+ message: USER_MESSAGE.SYSTEM_ERROR,
4553
4722
  data: error
4554
4723
  };
4555
4724
  }
@@ -4604,6 +4773,18 @@ var __webpack_exports__ = {};
4604
4773
  const verifyDecision = error.response?.headers?.["x-tt-verify-passport-decision"];
4605
4774
  if (verifyDecision) this.logger?.warn(`[403 验证决策] x-tt-verify-passport-decision: ${verifyDecision}`);
4606
4775
  }
4776
+ if (error.response?.status === 461 || error.response?.status === 471) {
4777
+ const h = error.response?.headers ?? {};
4778
+ const pick = (name)=>h[name] ?? h[name.toLowerCase()];
4779
+ this.logger?.warn(`[${error.response.status} 风控验证] URL: ${error.config?.url} Verifytype: ${pick("Verifytype") ?? "-"} Verifyuuid: ${pick("Verifyuuid") ?? "-"} Verifybiz: ${pick("Verifybiz") ?? "-"}`);
4780
+ this.logger?.warn(`[${error.response.status} 响应头] ${JSON.stringify(h)}`);
4781
+ errorResponse.extra = {
4782
+ ...errorResponse.extra,
4783
+ verifyType: pick("Verifytype"),
4784
+ verifyUuid: pick("Verifyuuid"),
4785
+ verifyBiz: pick("Verifybiz")
4786
+ };
4787
+ }
4607
4788
  if (error.response?.data) {
4608
4789
  if ("object" == typeof error.response.data) {
4609
4790
  const serverError = error.response.data;
@@ -4634,11 +4815,17 @@ var __webpack_exports__ = {};
4634
4815
  _message = "DNS 查询超时,请稍后重试!";
4635
4816
  break;
4636
4817
  case "ERR_BAD_REQUEST":
4637
- _message = "请求出现错误,请检查请求参数!";
4638
- break;
4818
+ {
4819
+ const status = error.response?.status;
4820
+ _message = status && HTTP_STATUS_MESSAGE[status] || `请求失败,状态码${status ?? "unknown"}!`;
4821
+ break;
4822
+ }
4639
4823
  case "ERR_BAD_RESPONSE":
4640
- _message = `服务器响应异常 (${error.response?.status ?? "unknown"}),请稍后重试!`;
4641
- break;
4824
+ {
4825
+ const status = error.response?.status;
4826
+ _message = status && HTTP_STATUS_MESSAGE[status] || `服务器响应异常 (${status ?? "unknown"}),请稍后重试!`;
4827
+ break;
4828
+ }
4642
4829
  case "ERR_CANCELED":
4643
4830
  errorResponse.code = 414;
4644
4831
  _message = "请求连接超时,请稍候重试!";
@@ -4649,11 +4836,14 @@ var __webpack_exports__ = {};
4649
4836
  }
4650
4837
  break;
4651
4838
  default:
4652
- this.logger?.debug(`未处理的网络错误代码: ${error.code} ${error.message}`, {
4653
- errorString: stringifyError(error)
4654
- });
4655
- _message = `网络错误: ${error.message}`;
4656
- break;
4839
+ {
4840
+ this.logger?.debug(`未处理的网络错误代码: ${error.code} ${error.message}`, {
4841
+ errorString: stringifyError(error)
4842
+ });
4843
+ const status = error.response?.status;
4844
+ _message = status && HTTP_STATUS_MESSAGE[status] || USER_MESSAGE.NETWORK_ERROR;
4845
+ break;
4846
+ }
4657
4847
  }
4658
4848
  }
4659
4849
  if (error.code && !error.response?.data) errorResponse.message = _message || errorResponse.message;
@@ -4663,29 +4853,51 @@ var __webpack_exports__ = {};
4663
4853
  errorResponse.message = message;
4664
4854
  }
4665
4855
  if (error.message.includes("Proxy connection ended")) errorResponse.message = "所在区域代理连接超时,请更换区域或稍后重试!";
4856
+ const status = error.response?.status;
4857
+ reportFeishuAlarm({
4858
+ level: status && ALARM_STATUS.has(status) ? "alarm" : "warning",
4859
+ platform: this.platform || "unknown",
4860
+ source: "http",
4861
+ stage: `${(error.config?.method || "get").toUpperCase()} ${error.config?.url || "-"}`,
4862
+ errorType: status ? `HTTP_${status}` : error.code || "NETWORK_ERROR",
4863
+ code: errorResponse.code,
4864
+ msg: errorResponse.message,
4865
+ url: error.config?.url,
4866
+ title: "RPA接口异常"
4867
+ });
4666
4868
  throw errorResponse;
4667
4869
  });
4668
4870
  }
4669
4871
  async api(config, options) {
4670
4872
  const retries = options?.retries ?? 0;
4671
4873
  const retryDelay = options?.retryDelay ?? 500;
4672
- const reqTimeout = options?.timeout ?? 30000;
4874
+ const reqTimeout = options?.timeout ?? 60000;
4875
+ const externalSignal = options?.signal;
4673
4876
  let agent;
4674
4877
  const sessionRt = async (Rtimes)=>{
4675
4878
  try {
4676
4879
  this.proxyInfo = agent ? `${agent.ip}:${agent.port}` : void 0;
4677
4880
  const controller = new AbortController();
4678
4881
  const timeoutId = setTimeout(()=>controller.abort(), reqTimeout + 500);
4882
+ const forwardAbort = ()=>controller.abort();
4883
+ if (externalSignal) {
4884
+ if (externalSignal.aborted) controller.abort();
4885
+ else externalSignal.addEventListener("abort", forwardAbort, {
4886
+ once: true
4887
+ });
4888
+ }
4679
4889
  const response = await this.apiClient({
4680
4890
  ...config,
4681
4891
  timeout: reqTimeout,
4682
4892
  signal: controller.signal,
4893
+ onUploadProgress: options?.onUploadProgress,
4683
4894
  ...agent ? {
4684
4895
  httpAgent: agent.agent,
4685
4896
  httpsAgent: agent.agent
4686
4897
  } : {}
4687
4898
  }).finally(()=>{
4688
4899
  clearTimeout(timeoutId);
4900
+ externalSignal?.removeEventListener("abort", forwardAbort);
4689
4901
  });
4690
4902
  return response.data;
4691
4903
  } catch (error) {
@@ -5432,7 +5644,7 @@ var __webpack_exports__ = {};
5432
5644
  Number.MAX_VALUE
5433
5645
  ]
5434
5646
  };
5435
- function pick(schema, mask) {
5647
+ function util_pick(schema, mask) {
5436
5648
  const currDef = schema._zod.def;
5437
5649
  const def = mergeDefs(schema._zod.def, {
5438
5650
  get shape () {
@@ -5802,7 +6014,7 @@ var __webpack_exports__ = {};
5802
6014
  const xid = /^[0-9a-vA-V]{20}$/;
5803
6015
  const ksuid = /^[A-Za-z0-9]{27}$/;
5804
6016
  const nanoid = /^[a-zA-Z0-9_-]{21}$/;
5805
- const duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
6017
+ const regexes_duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
5806
6018
  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})$/;
5807
6019
  const regexes_uuid = (version)=>{
5808
6020
  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)$/;
@@ -6488,7 +6700,7 @@ var __webpack_exports__ = {};
6488
6700
  $ZodStringFormat.init(inst, def);
6489
6701
  });
6490
6702
  const $ZodISODuration = /*@__PURE__*/ $constructor("$ZodISODuration", (inst, def)=>{
6491
- def.pattern ?? (def.pattern = duration);
6703
+ def.pattern ?? (def.pattern = regexes_duration);
6492
6704
  $ZodStringFormat.init(inst, def);
6493
6705
  });
6494
6706
  const $ZodIPv4 = /*@__PURE__*/ $constructor("$ZodIPv4", (inst, def)=>{
@@ -8413,7 +8625,7 @@ var __webpack_exports__ = {};
8413
8625
  inst.extend = (incoming)=>extend(inst, incoming);
8414
8626
  inst.safeExtend = (incoming)=>safeExtend(inst, incoming);
8415
8627
  inst.merge = (other)=>merge(inst, other);
8416
- inst.pick = (mask)=>pick(inst, mask);
8628
+ inst.pick = (mask)=>util_pick(inst, mask);
8417
8629
  inst.omit = (mask)=>omit(inst, mask);
8418
8630
  inst.partial = (...args)=>partial(ZodOptional, inst, args[0]);
8419
8631
  inst.required = (...args)=>required(ZodNonOptional, inst, args[0]);
@@ -8426,6 +8638,14 @@ var __webpack_exports__ = {};
8426
8638
  };
8427
8639
  return new ZodObject(def);
8428
8640
  }
8641
+ function looseObject(shape, params) {
8642
+ return new ZodObject({
8643
+ type: "object",
8644
+ shape,
8645
+ catchall: unknown(),
8646
+ ...normalizeParams(params)
8647
+ });
8648
+ }
8429
8649
  const ZodUnion = /*@__PURE__*/ $constructor("ZodUnion", (inst, def)=>{
8430
8650
  $ZodUnion.init(inst, def);
8431
8651
  ZodType.init(inst, def);
@@ -9124,6 +9344,13 @@ var __webpack_exports__ = {};
9124
9344
  data: ""
9125
9345
  };
9126
9346
  const image = await (0, share_namespaceObject.downloadImage)(url, external_node_path_default().join(tmpCachePath, fileName));
9347
+ const stats = external_node_fs_default().statSync(image);
9348
+ const maxSize = 5242880;
9349
+ if (stats.size > maxSize) throw {
9350
+ code: 414,
9351
+ message: "百家号平台:单张图片不得超过 5MB",
9352
+ data: ""
9353
+ };
9127
9354
  const formData = new (external_form_data_default())();
9128
9355
  formData.append("org_file_name", fileName);
9129
9356
  formData.append("type", "image");
@@ -12407,7 +12634,7 @@ var __webpack_exports__ = {};
12407
12634
  });
12408
12635
  const qrData = qrCodeResponse?.data;
12409
12636
  task.logger.info(`获取二维码响应: error_code=${qrData?.error_code}, message=${qrCodeResponse?.message}`);
12410
- if (qrData?.error_code !== 0) return (0, share_namespaceObject.response)(414, `获取二维码失败: error_code=${qrData?.error_code}`, "");
12637
+ if (qrData?.error_code !== 0) return (0, share_namespaceObject.response)(414, USER_MESSAGE.QRCODE_FETCH_FAILED, "");
12411
12638
  return (0, share_namespaceObject.response)(0, "获取二维码成功", {
12412
12639
  qrcode: qrData.qrcode,
12413
12640
  token: qrData.token,
@@ -12422,7 +12649,7 @@ var __webpack_exports__ = {};
12422
12649
  } catch (err) {
12423
12650
  const msg = err instanceof Error ? err.message : String(err);
12424
12651
  task.logger.warn(`[douyinGetVerifyQrCode] 获取二维码失败: ${msg}`);
12425
- return (0, share_namespaceObject.response)(500, `获取二维码失败: ${msg}`, "");
12652
+ return (0, share_namespaceObject.response)(500, USER_MESSAGE.QRCODE_FETCH_FAILED, "");
12426
12653
  }
12427
12654
  };
12428
12655
  const DouyinGetWorkListParamsSchema = ActionCommonParamsSchema.extend({
@@ -13261,6 +13488,11 @@ var __webpack_exports__ = {};
13261
13488
  }
13262
13489
  async getImageInfo(localPath) {
13263
13490
  const stats = external_node_fs_default().statSync(localPath);
13491
+ const maxSize = 52428800;
13492
+ if (stats.size > maxSize) {
13493
+ external_node_path_default().basename(localPath);
13494
+ throw new Error("抖音平台:单张图片不得超过 50MB");
13495
+ }
13264
13496
  let width = 1080;
13265
13497
  let height = 1920;
13266
13498
  try {
@@ -13741,18 +13973,10 @@ var __webpack_exports__ = {};
13741
13973
  });
13742
13974
  } catch (error) {
13743
13975
  const handledError = Http.handleApiError(error);
13744
- const isProxyOrNetworkError = [
13745
- 599,
13746
- 500,
13747
- 502,
13748
- 503,
13749
- 504
13750
- ].includes(handledError.code);
13751
- if (isProxyOrNetworkError) {
13752
- const isProxyRequest = handledError.extra?.isProxyRequest === true;
13753
- const errorType = 599 === handledError.code || isProxyRequest ? "代理错误" : "网络错误";
13754
- const message = `图文发布失败,${errorType}:${handledError.message}${task.debug ? ` ${http.proxyInfo}` : ""}`;
13755
- task.logger.error(`[douyinPublish] ${errorType},直接返回: ${message}`, stringifyError(handledError));
13976
+ const classified = classifyPublishError(handledError);
13977
+ if (classified) {
13978
+ const message = `${classified.userMessage}${task.debug ? ` ${http.proxyInfo}` : ""}`;
13979
+ task.logger.error(`[douyinPublish] ${classified.category},直接返回: ${handledError.message} (code=${handledError.code})`, stringifyError(handledError));
13756
13980
  await updateTaskState?.({
13757
13981
  state: share_namespaceObject.TaskState.FAILED,
13758
13982
  error: message
@@ -15470,7 +15694,7 @@ var __webpack_exports__ = {};
15470
15694
  }
15471
15695
  const errMsg = error instanceof Error ? error.message : String(error);
15472
15696
  _task.logger.error(`抖音账号数据获取失败: ${errMsg}`);
15473
- return types_errorResponse(errMsg || "抖音账号数据获取失败");
15697
+ return types_errorResponse(USER_MESSAGE.DOUYIN_ACCOUNT_FETCH_FAILED);
15474
15698
  }
15475
15699
  }
15476
15700
  async function getShipinhaoData(_task, params) {
@@ -15601,7 +15825,7 @@ var __webpack_exports__ = {};
15601
15825
  }
15602
15826
  const errMsg = error instanceof Error ? error.message : String(error);
15603
15827
  _task.logger.error(`视频号账号数据获取失败: ${errMsg}`);
15604
- return types_errorResponse(errMsg || "视频号账号数据获取失败");
15828
+ return types_errorResponse(USER_MESSAGE.SHIPINHAO_ACCOUNT_FETCH_FAILED);
15605
15829
  }
15606
15830
  }
15607
15831
  async function getToutiaoData(_task, params) {
@@ -16042,7 +16266,9 @@ var __webpack_exports__ = {};
16042
16266
  } : null
16043
16267
  }, "百家号文章数据获取成功");
16044
16268
  } catch (error) {
16045
- return searchPublishInfo_types_errorResponse(error instanceof Error ? error.message : "百家号文章数据获取失败");
16269
+ const errMsg = error instanceof Error ? error.message : String(error);
16270
+ _task.logger.error(`百家号文章数据获取失败: ${errMsg}`);
16271
+ return searchPublishInfo_types_errorResponse(USER_MESSAGE.BJH_POST_FETCH_FAILED);
16046
16272
  }
16047
16273
  }
16048
16274
  async function handleDouyinData(_task, params) {
@@ -16137,7 +16363,9 @@ var __webpack_exports__ = {};
16137
16363
  } : null
16138
16364
  }, "抖音数据获取成功");
16139
16365
  } catch (error) {
16140
- return searchPublishInfo_types_errorResponse(error instanceof Error ? error.message : "抖音数据获取失败");
16366
+ const errMsg = error instanceof Error ? error.message : String(error);
16367
+ _task.logger.error(`抖音作品数据获取失败: ${errMsg}`);
16368
+ return searchPublishInfo_types_errorResponse(USER_MESSAGE.DOUYIN_POST_FETCH_FAILED);
16141
16369
  }
16142
16370
  }
16143
16371
  async function handleShipinhaoData(_task, params) {
@@ -16302,8 +16530,9 @@ var __webpack_exports__ = {};
16302
16530
  }, "视频号数据获取成功");
16303
16531
  } catch (error) {
16304
16532
  const errMsg = error instanceof Error ? error.message : String(error);
16533
+ _task.logger.error(`视频号作品数据获取失败: ${errMsg}`);
16305
16534
  if (errMsg.startsWith("AUTH_ERROR:")) return searchPublishInfo_types_errorResponse("视频号数据获取失败,请检查账号状态", 414);
16306
- return searchPublishInfo_types_errorResponse(errMsg || "视频号数据获取失败");
16535
+ return searchPublishInfo_types_errorResponse(USER_MESSAGE.SHIPINHAO_POST_FETCH_FAILED);
16307
16536
  }
16308
16537
  }
16309
16538
  async function handleToutiaoData(_task, params) {
@@ -16388,7 +16617,9 @@ var __webpack_exports__ = {};
16388
16617
  } : null
16389
16618
  }, "头条号文章文章获取成功");
16390
16619
  } catch (error) {
16391
- return searchPublishInfo_types_errorResponse(error instanceof Error ? error.message : "头条号文章数据获取失败");
16620
+ const errMsg = error instanceof Error ? error.message : String(error);
16621
+ _task.logger.error(`头条号文章数据获取失败: ${errMsg}`);
16622
+ return searchPublishInfo_types_errorResponse(USER_MESSAGE.TT_POST_FETCH_FAILED);
16392
16623
  }
16393
16624
  }
16394
16625
  const external_node_vm_namespaceObject = require("node:vm");
@@ -18765,18 +18996,10 @@ var __webpack_exports__ = {};
18765
18996
  });
18766
18997
  } catch (error) {
18767
18998
  const handledError = Http.handleApiError(error);
18768
- const isProxyOrNetworkError = [
18769
- 599,
18770
- 500,
18771
- 502,
18772
- 503,
18773
- 504
18774
- ].includes(handledError.code);
18775
- if (isProxyOrNetworkError) {
18776
- const isProxyRequest = handledError.extra?.isProxyRequest === true;
18777
- const errorType = 599 === handledError.code || isProxyRequest ? "代理错误" : "网络错误";
18778
- const message = `图文发布失败,${errorType}:${handledError.message}${task.debug ? ` ${http.proxyInfo}` : ""}`;
18779
- task.logger.error(`[shipinhaoPublish] ${errorType},直接返回: ${message}`, stringifyError(handledError));
18999
+ const classified = classifyPublishError(handledError);
19000
+ if (classified) {
19001
+ const message = `${classified.userMessage}${task.debug ? ` ${http.proxyInfo}` : ""}`;
19002
+ task.logger.error(`[shipinhaoPublish] ${classified.category},直接返回: ${handledError.message} (code=${handledError.code})`, stringifyError(handledError));
18780
19003
  await updateTaskState?.({
18781
19004
  state: share_namespaceObject.TaskState.FAILED,
18782
19005
  error: message
@@ -19516,107 +19739,1747 @@ var __webpack_exports__ = {};
19516
19739
  if ("server" === params.actionType) return rpa_server_rpaAction_Server(task, params);
19517
19740
  return executeAction(shipinhaoPublish_mock_mockAction, rpa_server_rpaAction_Server)(task, params);
19518
19741
  };
19519
- const ShipinhaoSendMsgParamsSchema = ActionCommonParamsSchema.extend({
19520
- toUsername: schemas_string().min(1, "接收者用户名不能为空"),
19521
- sessionId: schemas_string().min(1, "会话ID不能为空"),
19522
- msgType: schemas_enum([
19523
- "TEXT",
19524
- "IMAGE"
19525
- ], {
19526
- message: "消息类型必须是 TEXT 或 IMAGE"
19527
- }),
19528
- content: schemas_string().optional(),
19529
- imageInfo: schemas_object({
19530
- pathOrUrl: schemas_string().min(1, "图片路径或URL不能为空")
19531
- }).optional()
19532
- });
19533
- const CHUNK_SIZE = 524288;
19534
- async function shipinhaoSendMsg_getUserInfo(cookieStr, http) {
19535
- const url = `https://channels.weixin.qq.com/cgi-bin/mmfinderassistant-bin/auth/auth_data?_rid=${rid()}`;
19536
- const headers = {
19537
- referer: "https://channels.weixin.qq.com/micro/interaction/private_msg",
19538
- cookie: cookieStr,
19539
- Origin: "https://channels.weixin.qq.com"
19540
- };
19541
- return await http.api({
19542
- method: "get",
19543
- url,
19544
- headers
19545
- }, {
19546
- retries: 3,
19547
- retryDelay: 1000,
19548
- timeout: 10000
19742
+ function auth_getTimeStamp(length) {
19743
+ return Date.now().toString().substring(0, length);
19744
+ }
19745
+ async function auth_getUserInfo(cookies, http) {
19746
+ return http.api({
19747
+ method: "post",
19748
+ url: "https://channels.weixin.qq.com/cgi-bin/mmfinderassistant-bin/auth/auth_data",
19749
+ data: {
19750
+ timestamp: auth_getTimeStamp(13),
19751
+ _log_finder_uin: "",
19752
+ _log_finder_id: "",
19753
+ rawKeyBuff: null,
19754
+ pluginSessionId: null,
19755
+ scene: 7,
19756
+ reqScene: 7
19757
+ },
19758
+ headers: {
19759
+ cookie: cookies,
19760
+ referer: "https://channels.weixin.qq.com",
19761
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
19762
+ },
19763
+ defaultErrorMsg: "获取用户信息失败"
19549
19764
  });
19550
19765
  }
19551
- const shipinhaoSendMsg = async (_task, params)=>{
19552
- if (!params.sessionId) return (0, share_namespaceObject.response)(414, "sessionId 不能为空", void 0);
19553
- if (!params.toUsername) return (0, share_namespaceObject.response)(414, "接收者用户名不能为空", void 0);
19554
- if (!params.msgType) return (0, share_namespaceObject.response)(414, "消息类型不能为空", void 0);
19555
- if (![
19556
- "TEXT",
19557
- "IMAGE"
19558
- ].includes(params.msgType)) return (0, share_namespaceObject.response)(414, "消息类型必须是 TEXT 或 IMAGE", void 0);
19559
- if ("TEXT" === params.msgType) {
19560
- if (!params.content || "" === params.content.trim()) return (0, share_namespaceObject.response)(414, "消息内容不能为空", void 0);
19561
- }
19562
- if ("IMAGE" === params.msgType) {
19563
- if (!params.imageInfo?.pathOrUrl) return (0, share_namespaceObject.response)(414, "图片路径或URL不能为空", void 0);
19766
+ async function auth_getUploadAuthKey(cookies, finderUsername, http) {
19767
+ return http.api({
19768
+ method: "post",
19769
+ url: "https://channels.weixin.qq.com/cgi-bin/mmfinderassistant-bin/helper/helper_upload_params",
19770
+ data: {
19771
+ timestamp: auth_getTimeStamp(13),
19772
+ _log_finder_id: finderUsername,
19773
+ rawKeyBuff: null
19774
+ },
19775
+ headers: {
19776
+ cookie: cookies,
19777
+ referer: "https://channels.weixin.qq.com",
19778
+ Accept: "application/json, text/plain, */*",
19779
+ "Content-Type": "application/json",
19780
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
19781
+ },
19782
+ defaultErrorMsg: "获取上传认证密钥失败"
19783
+ });
19784
+ }
19785
+ class ShipinhaoAuthError extends Error {
19786
+ constructor(message, errCode){
19787
+ super(message), this.errCode = errCode;
19788
+ this.name = "ShipinhaoAuthError";
19564
19789
  }
19565
- if (!params.extraParam) return (0, share_namespaceObject.response)(414, "缺少 extraParam 参数", void 0);
19566
- if (!params.extraParam.fingerPrintDeviceId || !params.extraParam.aId || !params.extraParam.uin) return (0, share_namespaceObject.response)(414, "fingerPrintDeviceId、aId 和 uin 不能为空", void 0);
19567
- const cookieStr = params.cookies.map((it)=>`${it.name}=${it.value}`).join(";");
19568
- const headers = {
19569
- cookie: cookieStr,
19570
- referer: "https://channels.weixin.qq.com/micro/interaction/private_msg",
19571
- origin: "https://channels.weixin.qq.com",
19572
- "content-type": "application/json",
19573
- "finger-print-device-id": params.extraParam.fingerPrintDeviceId,
19574
- "x-wechat-uin": params.extraParam.uin
19790
+ }
19791
+ async function getShipinhaoUploadAuth(cookies, http) {
19792
+ const userInfo = await auth_getUserInfo(cookies, http);
19793
+ if (0 !== userInfo.errCode || !userInfo.data?.finderUser) {
19794
+ const isLoginExpired = 300333 === userInfo.errCode || 300334 === userInfo.errCode;
19795
+ throw new ShipinhaoAuthError(isLoginExpired ? "登录失效" : userInfo.errMsg || "获取用户信息失败", userInfo.errCode || 500);
19796
+ }
19797
+ const finderUsername = userInfo.data.finderUser.finderUsername;
19798
+ const authKeyResponse = await auth_getUploadAuthKey(cookies, finderUsername, http);
19799
+ if (0 !== authKeyResponse.errCode || !authKeyResponse.data?.authKey) throw new ShipinhaoAuthError(`获取上传认证参数失败: ${authKeyResponse.errMsg}`, authKeyResponse.errCode || 500);
19800
+ const uin = authKeyResponse.data.uin;
19801
+ if (!uin) throw new ShipinhaoAuthError("获取用户 uin 失败", 500);
19802
+ const videoFileType = authKeyResponse.data.videoFileType || 20302;
19803
+ const pictureFileType = authKeyResponse.data.pictureFileType || 20304;
19804
+ return {
19805
+ uin,
19806
+ authKey: authKeyResponse.data.authKey,
19807
+ finderUsername,
19808
+ videoFileType,
19809
+ pictureFileType
19575
19810
  };
19576
- const http = new Http({
19577
- headers
19811
+ }
19812
+ const MENTION_TEXT_SUFFIX = "\u0020";
19813
+ const MENTION_XML_SUFFIX = "\u2005";
19814
+ function payload_buildDescription(params) {
19815
+ let description = params.description || "";
19816
+ for (const topic of params.topics || [])description += `#${topic}`;
19817
+ for (const user of params.mentionedUsers || [])description += `@${user.nickname}${MENTION_TEXT_SUFFIX}`;
19818
+ return description;
19819
+ }
19820
+ function buildMentionedUser(mentionedUsers) {
19821
+ return (mentionedUsers || []).map((user)=>({
19822
+ nickname: `${user.nickname}${MENTION_TEXT_SUFFIX}`
19823
+ }));
19824
+ }
19825
+ function payload_buildTopicXml(params) {
19826
+ const values = [];
19827
+ let atIndex = null;
19828
+ if (params.description) values.push(`<![CDATA[${params.description}]]>`);
19829
+ for (const topic of params.topics || [])values.push(`<topic><![CDATA[#${topic}#]]></topic>`);
19830
+ for (const user of params.mentionedUsers || []){
19831
+ if (null === atIndex) atIndex = values.length;
19832
+ values.push(`<![CDATA[@${user.nickname}${MENTION_XML_SUFFIX}]]>`);
19833
+ }
19834
+ let xml = "<finder>";
19835
+ xml += "<version>1</version>";
19836
+ xml += `<valuecount>${values.length}</valuecount>`;
19837
+ xml += `<style><at>${atIndex ?? ""}</at></style>`;
19838
+ values.forEach((value, index)=>{
19839
+ xml += `<value${index}>${value}</value${index}>`;
19578
19840
  });
19579
- const urlParams = new URLSearchParams({
19580
- _aid: params.extraParam.aId,
19581
- _rid: rid(),
19582
- _pageUrl: "https://channels.weixin.qq.com/micro/interaction/private_msg"
19583
- }).toString();
19584
- const generateCliMsgId = ()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (s)=>{
19585
- const t = 16 * Math.random() | 0;
19586
- return ("x" === s ? t : 3 & t | 8).toString(16);
19841
+ xml += "</finder>";
19842
+ return xml;
19843
+ }
19844
+ function payload_buildLocation(location) {
19845
+ if (!location) return {
19846
+ latitude: 0,
19847
+ longitude: 0,
19848
+ city: "",
19849
+ poiName: "",
19850
+ address: "",
19851
+ poiClassifyId: ""
19852
+ };
19853
+ return {
19854
+ latitude: location.latitude,
19855
+ longitude: location.longitude,
19856
+ city: location.city,
19857
+ poiName: location.poiName || "",
19858
+ address: location.address || "",
19859
+ poiClassifyId: location.poiClassifyId || ""
19860
+ };
19861
+ }
19862
+ function buildTopic(params) {
19863
+ const topic = {
19864
+ finderTopicInfo: payload_buildTopicXml(params)
19865
+ };
19866
+ if (params.collection) {
19867
+ topic.collectionId = params.collection.collectionId;
19868
+ topic.collectionName = params.collection.collectionName;
19869
+ }
19870
+ return topic;
19871
+ }
19872
+ function buildEvent(event) {
19873
+ if (!event) return {};
19874
+ return {
19875
+ eventTopicId: event.eventTopicId,
19876
+ eventName: event.eventName,
19877
+ eventCreatorNickname: event.eventCreatorNickname || ""
19878
+ };
19879
+ }
19880
+ function buildExtReading(link) {
19881
+ if (!link) return {
19882
+ link: "",
19883
+ title: "",
19884
+ urlType: 1
19885
+ };
19886
+ return {
19887
+ link: link.link.replace(/[\s\u200b]/g, ""),
19888
+ title: link.title,
19889
+ urlType: link.urlType ?? 1
19890
+ };
19891
+ }
19892
+ function buildTagInfo(tagInfo, tagKey) {
19893
+ return {
19894
+ ...tagInfo,
19895
+ tagKey
19896
+ };
19897
+ }
19898
+ const CHUNK_SIZE = 8388608;
19899
+ const UPLOAD_STAGE_TIMEOUT = 180000;
19900
+ const DEFAULT_TUNING = {
19901
+ metaTimeout: UPLOAD_STAGE_TIMEOUT,
19902
+ partTimeout: UPLOAD_STAGE_TIMEOUT,
19903
+ partRetries: 3,
19904
+ completeTimeout: UPLOAD_STAGE_TIMEOUT
19905
+ };
19906
+ async function uploader_uploadFile(opts) {
19907
+ const { filePath, fileType, uin, authKey, http, logger, tuning } = opts;
19908
+ const stat = external_node_fs_default().statSync(filePath);
19909
+ const fileSize = stat.size;
19910
+ const fileName = filePath.split(/[\\/]/).pop() || "file";
19911
+ const metaTimeout = tuning?.metaTimeout ?? DEFAULT_TUNING.metaTimeout;
19912
+ const partTimeout = tuning?.partTimeout ?? DEFAULT_TUNING.partTimeout;
19913
+ const partRetries = tuning?.partRetries ?? DEFAULT_TUNING.partRetries;
19914
+ const completeTimeout = tuning?.completeTimeout ?? DEFAULT_TUNING.completeTimeout;
19915
+ logger?.info(`开始上传: ${fileName} (${fileSize} B, filetype=${fileType})`);
19916
+ logger?.info(`上传超时策略: 单片 ${partTimeout / 1000}s(重试 ${partRetries} 次)、合并 ${completeTimeout / 1000}s`);
19917
+ const fileMd5 = await computeFileMd5(filePath);
19918
+ const taskId = generateTaskId(fileName, fileSize, fileMd5);
19919
+ const baseUrl = "https://finderassistancea.video.qq.com";
19920
+ const headers = {
19921
+ Authorization: authKey
19922
+ };
19923
+ const xArgs = `apptype=251&filetype=${fileType}&weixinnum=${uin}&filekey=${encodeURIComponent(fileName)}&filesize=${fileSize}&taskid=${taskId}&scene=2`;
19924
+ const chunkCount = Math.ceil(fileSize / CHUNK_SIZE);
19925
+ const blockPartLength = [];
19926
+ for(let i = 0; i < chunkCount; i++)blockPartLength.push(Math.min((i + 1) * CHUNK_SIZE, fileSize));
19927
+ logger?.info(`申请 UploadID: ${chunkCount} 片`);
19928
+ const applyRes = await http.api({
19929
+ method: "PUT",
19930
+ url: `${baseUrl}/applyuploaddfs`,
19931
+ headers: {
19932
+ ...headers,
19933
+ "X-Arguments": xArgs
19934
+ },
19935
+ data: {
19936
+ BlockSum: chunkCount,
19937
+ BlockPartLength: blockPartLength
19938
+ }
19939
+ }, {
19940
+ timeout: metaTimeout,
19941
+ retries: 2,
19942
+ retryDelay: 2000
19943
+ });
19944
+ if (!applyRes.UploadID && !applyRes.ListPartsResult) throw new Error("申请 UploadID 失败: " + JSON.stringify(applyRes));
19945
+ let uploadId = applyRes.UploadID;
19946
+ const uploadedParts = new Set();
19947
+ if (applyRes.ListPartsResult) {
19948
+ logger?.info("检测到已上传分片,执行续传");
19949
+ const parts = Array.isArray(applyRes.ListPartsResult.Part) ? applyRes.ListPartsResult.Part : applyRes.ListPartsResult.Part ? [
19950
+ applyRes.ListPartsResult.Part
19951
+ ] : [];
19952
+ for (const p of parts)uploadedParts.add(p.PartNumber);
19953
+ const retryRes = await http.api({
19954
+ method: "PUT",
19955
+ url: `${baseUrl}/applyuploaddfs`,
19956
+ headers: {
19957
+ ...headers,
19958
+ "X-Arguments": xArgs
19959
+ },
19960
+ data: {
19961
+ BlockSum: chunkCount,
19962
+ BlockPartLength: blockPartLength
19963
+ }
19964
+ }, {
19965
+ timeout: metaTimeout,
19966
+ retries: 2,
19967
+ retryDelay: 2000
19587
19968
  });
19588
- let fromUsername = params.extraParam.finderUserName;
19589
- if (!fromUsername) {
19590
- _task.logger.info("未提供 finderUserName,尝试获取用户信息");
19591
- const userInfoRes = await shipinhaoSendMsg_getUserInfo(cookieStr, http);
19592
- if (!userInfoRes.data?.finderUser?.finderUsername) return (0, share_namespaceObject.response)(userInfoRes.errCode || -1, userInfoRes.errMsg || "获取用户信息失败", {});
19593
- fromUsername = userInfoRes.data.finderUser.finderUsername;
19594
- _task.logger.info(`获取到用户名: ${fromUsername}`);
19969
+ uploadId = retryRes.UploadID;
19970
+ if (!uploadId) throw new Error("续传获取 UploadID 失败");
19595
19971
  }
19596
- let imgMsg;
19597
- if ("IMAGE" === params.msgType) {
19598
- let imageBuffer;
19599
- const imagePath = params.imageInfo.pathOrUrl;
19600
- try {
19601
- if (imagePath.startsWith("http://") || imagePath.startsWith("https://")) {
19602
- const resp = await external_axios_default().get(imagePath, {
19603
- responseType: "arraybuffer"
19604
- });
19605
- imageBuffer = Buffer.from(resp.data);
19606
- } else {
19607
- const filePath = imagePath.startsWith("file://") ? imagePath.slice(7) : imagePath;
19608
- imageBuffer = Buffer.from(await external_node_fs_default().promises.readFile(filePath));
19972
+ const partInfo = [];
19973
+ const fd = external_node_fs_default().openSync(filePath, "r");
19974
+ try {
19975
+ for(let i = 0; i < chunkCount; i++){
19976
+ const partNumber = i + 1;
19977
+ if (uploadedParts.has(partNumber)) {
19978
+ const existing = applyRes.ListPartsResult.Part.find((p)=>p.PartNumber === partNumber);
19979
+ if (existing) {
19980
+ partInfo.push({
19981
+ PartNumber: partNumber,
19982
+ ETag: existing.ETag
19983
+ });
19984
+ logger?.info(`分片 ${partNumber}/${chunkCount} 已存在,跳过`);
19985
+ continue;
19986
+ }
19609
19987
  }
19610
- } catch (err) {
19611
- return (0, share_namespaceObject.response)(414, `读取图片失败: ${err instanceof Error ? err.message : String(err)}`, void 0);
19988
+ const start = i * CHUNK_SIZE;
19989
+ const end = Math.min(start + CHUNK_SIZE, fileSize);
19990
+ const chunkSize = end - start;
19991
+ const chunk = Buffer.alloc(chunkSize);
19992
+ external_node_fs_default().readSync(fd, chunk, 0, chunkSize, start);
19993
+ const chunkMd5 = external_node_crypto_default().createHash("md5").update(chunk).digest("hex");
19994
+ const partStart = Date.now();
19995
+ await http.api({
19996
+ method: "PUT",
19997
+ url: `${baseUrl}/uploadpartdfs?PartNumber=${partNumber}&UploadID=${encodeURIComponent(uploadId)}`,
19998
+ headers: {
19999
+ ...headers,
20000
+ "X-Arguments": xArgs.replace(/scene=2/, "scene=0"),
20001
+ "Content-MD5": chunkMd5
20002
+ },
20003
+ data: chunk
20004
+ }, {
20005
+ timeout: partTimeout,
20006
+ retries: partRetries,
20007
+ retryDelay: 2000
20008
+ });
20009
+ const partElapsed = Date.now() - partStart;
20010
+ const throughput = Math.round(chunkSize / (partElapsed / 1000));
20011
+ partInfo.push({
20012
+ PartNumber: partNumber,
20013
+ ETag: `"${chunkMd5}"`
20014
+ });
20015
+ logger?.info(`分片 ${partNumber}/${chunkCount} 完成 (${chunkSize} B, ${partElapsed}ms, ${Math.round(throughput / 1024)}KB/s)`);
19612
20016
  }
19613
- const md5 = (0, external_node_crypto_namespaceObject.createHash)("md5").update(imageBuffer).digest("hex");
20017
+ } finally{
20018
+ external_node_fs_default().closeSync(fd);
20019
+ }
20020
+ logger?.info("合并分片...");
20021
+ const completeRes = await http.api({
20022
+ method: "POST",
20023
+ url: `${baseUrl}/completepartuploaddfs?UploadID=${encodeURIComponent(uploadId)}`,
20024
+ headers: {
20025
+ ...headers,
20026
+ "X-Arguments": xArgs
20027
+ },
20028
+ data: {
20029
+ TransFlag: "0_0",
20030
+ PartInfo: partInfo
20031
+ }
20032
+ }, {
20033
+ timeout: completeTimeout,
20034
+ retries: 1,
20035
+ retryDelay: 3000
20036
+ });
20037
+ if (!completeRes.DownloadURL) throw new Error("合并分片失败: " + JSON.stringify(completeRes));
20038
+ logger?.info("上传成功");
20039
+ return {
20040
+ downloadUrl: completeRes.DownloadURL,
20041
+ md5: fileMd5,
20042
+ fileSize
20043
+ };
20044
+ }
20045
+ async function computeFileMd5(filePath) {
20046
+ return new Promise((resolve, reject)=>{
20047
+ const hash = external_node_crypto_default().createHash("md5");
20048
+ const stream = external_node_fs_default().createReadStream(filePath);
20049
+ stream.on("data", (chunk)=>hash.update(chunk));
20050
+ stream.on("end", ()=>resolve(hash.digest("hex")));
20051
+ stream.on("error", reject);
20052
+ });
20053
+ }
20054
+ function generateTaskId(fileName, fileSize, fileMd5) {
20055
+ const input = `${fileName}-${fileSize}-${fileMd5}`;
20056
+ return external_node_crypto_default().createHash("md5").update(input).digest("hex").slice(0, 32);
20057
+ }
20058
+ const MAX_METADATA_BOX_SIZE = 268435456;
20059
+ function readBoxHeader(fd, offset, limit) {
20060
+ if (offset + 8 > limit) return null;
20061
+ const head = Buffer.alloc(16);
20062
+ const read = external_node_fs_default().readSync(fd, head, 0, 16, offset);
20063
+ if (read < 8) return null;
20064
+ let size = head.readUInt32BE(0);
20065
+ const type = head.toString("latin1", 4, 8);
20066
+ let headerSize = 8;
20067
+ if (1 === size) {
20068
+ if (read < 16) return null;
20069
+ size = head.readUInt32BE(8) * 2 ** 32 + head.readUInt32BE(12);
20070
+ headerSize = 16;
20071
+ } else if (0 === size) size = limit - offset;
20072
+ if (size < headerSize || offset + size > limit) return null;
20073
+ return {
20074
+ type,
20075
+ size,
20076
+ headerSize
20077
+ };
20078
+ }
20079
+ function parseVideoMeta(filePath) {
20080
+ let fd;
20081
+ let fileSize;
20082
+ try {
20083
+ fd = external_node_fs_default().openSync(filePath, "r");
20084
+ } catch {
20085
+ return null;
20086
+ }
20087
+ try {
20088
+ fileSize = external_node_fs_default().fstatSync(fd).size;
20089
+ const state = {
20090
+ movie: null,
20091
+ tracks: [],
20092
+ trexDefaults: new Map(),
20093
+ fragmentDurations: new Map(),
20094
+ trafTrackId: 0,
20095
+ trafDefaultSampleDuration: 0
20096
+ };
20097
+ let offset = 0;
20098
+ while(offset + 8 <= fileSize){
20099
+ const header = readBoxHeader(fd, offset, fileSize);
20100
+ if (!header) break;
20101
+ if ("moov" === header.type || "moof" === header.type) {
20102
+ const bodyLength = header.size - header.headerSize;
20103
+ if (bodyLength > 0 && bodyLength <= MAX_METADATA_BOX_SIZE) {
20104
+ const body = Buffer.alloc(bodyLength);
20105
+ const read = external_node_fs_default().readSync(fd, body, 0, bodyLength, offset + header.headerSize);
20106
+ state.trafTrackId = 0;
20107
+ state.trafDefaultSampleDuration = 0;
20108
+ walkBoxes(body.subarray(0, read), 0, read, state);
20109
+ }
20110
+ }
20111
+ offset += header.size;
20112
+ }
20113
+ const { movie, tracks } = state;
20114
+ const video = tracks.find((t)=>"vide" === t.handler) || tracks.find((t)=>t.width > 0 && t.height > 0);
20115
+ if (!video) return null;
20116
+ let { width, height } = video;
20117
+ if (90 === video.rotation || 270 === video.rotation) [width, height] = [
20118
+ height,
20119
+ width
20120
+ ];
20121
+ return {
20122
+ width: Math.round(width),
20123
+ height: Math.round(height),
20124
+ duration: resolveDuration(movie, video, state.fragmentDurations),
20125
+ rotation: video.rotation,
20126
+ fileSize,
20127
+ codec: video.codec
20128
+ };
20129
+ } catch {
20130
+ return null;
20131
+ } finally{
20132
+ try {
20133
+ external_node_fs_default().closeSync(fd);
20134
+ } catch {}
20135
+ }
20136
+ }
20137
+ function walkBoxes(buf, start, end, state) {
20138
+ let off = start;
20139
+ while(off + 8 <= end){
20140
+ let size = buf.readUInt32BE(off);
20141
+ const type = buf.toString("latin1", off + 4, off + 8);
20142
+ let headerSize = 8;
20143
+ if (1 === size) {
20144
+ if (off + 16 > end) break;
20145
+ const hi = buf.readUInt32BE(off + 8);
20146
+ const lo = buf.readUInt32BE(off + 12);
20147
+ size = hi * 2 ** 32 + lo;
20148
+ headerSize = 16;
20149
+ } else if (0 === size) size = end - off;
20150
+ if (size < headerSize || off + size > end) break;
20151
+ const bodyStart = off + headerSize;
20152
+ const bodyEnd = off + size;
20153
+ switch(type){
20154
+ case "trak":
20155
+ case "mdia":
20156
+ case "minf":
20157
+ case "stbl":
20158
+ case "mvex":
20159
+ case "traf":
20160
+ walkBoxes(buf, bodyStart, bodyEnd, state);
20161
+ break;
20162
+ case "mvhd":
20163
+ state.movie = parseMvhd(buf, bodyStart, bodyEnd);
20164
+ break;
20165
+ case "tkhd":
20166
+ state.tracks.push({
20167
+ ...parseTkhd(buf, bodyStart, bodyEnd),
20168
+ handler: null,
20169
+ codec: null,
20170
+ timescale: 0,
20171
+ mdhdDuration: 0,
20172
+ sttsDuration: 0
20173
+ });
20174
+ break;
20175
+ case "mdhd":
20176
+ {
20177
+ const mdhd = parseMvhd(buf, bodyStart, bodyEnd);
20178
+ if (mdhd && state.tracks.length) {
20179
+ const track = state.tracks[state.tracks.length - 1];
20180
+ track.timescale = mdhd.timescale;
20181
+ track.mdhdDuration = mdhd.duration;
20182
+ }
20183
+ break;
20184
+ }
20185
+ case "hdlr":
20186
+ if (bodyEnd - bodyStart >= 12 && state.tracks.length) state.tracks[state.tracks.length - 1].handler = buf.toString("latin1", bodyStart + 8, bodyStart + 12);
20187
+ break;
20188
+ case "stsd":
20189
+ {
20190
+ const codec = parseStsdCodec(buf, bodyStart, bodyEnd);
20191
+ if (codec && state.tracks.length) state.tracks[state.tracks.length - 1].codec = codec;
20192
+ break;
20193
+ }
20194
+ case "stts":
20195
+ if (state.tracks.length) state.tracks[state.tracks.length - 1].sttsDuration = parseSttsDuration(buf, bodyStart, bodyEnd);
20196
+ break;
20197
+ case "trex":
20198
+ if (bodyStart + 20 > bodyEnd) break;
20199
+ state.trexDefaults.set(buf.readUInt32BE(bodyStart + 4), buf.readUInt32BE(bodyStart + 12));
20200
+ break;
20201
+ case "tfhd":
20202
+ {
20203
+ const tfhd = parseTfhd(buf, bodyStart, bodyEnd);
20204
+ state.trafTrackId = tfhd.trackId;
20205
+ state.trafDefaultSampleDuration = tfhd.defaultSampleDuration || state.trexDefaults.get(tfhd.trackId) || 0;
20206
+ break;
20207
+ }
20208
+ case "trun":
20209
+ {
20210
+ const duration = parseTrunDuration(buf, bodyStart, bodyEnd, state.trafDefaultSampleDuration);
20211
+ state.fragmentDurations.set(state.trafTrackId, (state.fragmentDurations.get(state.trafTrackId) || 0) + duration);
20212
+ break;
20213
+ }
20214
+ }
20215
+ off += size;
20216
+ }
20217
+ }
20218
+ const UNKNOWN_DURATION_32 = 0xffffffff;
20219
+ function isUsableDuration(duration) {
20220
+ return duration > 0 && duration !== UNKNOWN_DURATION_32;
20221
+ }
20222
+ function resolveDuration(movie, video, fragmentDurations) {
20223
+ if (movie && movie.timescale && isUsableDuration(movie.duration)) return movie.duration / movie.timescale;
20224
+ if (video.timescale) {
20225
+ if (isUsableDuration(video.mdhdDuration)) return video.mdhdDuration / video.timescale;
20226
+ if (video.sttsDuration > 0) return video.sttsDuration / video.timescale;
20227
+ const fragment = fragmentDurations.get(video.trackId) ?? (1 === fragmentDurations.size ? [
20228
+ ...fragmentDurations.values()
20229
+ ][0] : 0);
20230
+ if (fragment > 0) return fragment / video.timescale;
20231
+ }
20232
+ return 0;
20233
+ }
20234
+ function parseSttsDuration(buf, start, end) {
20235
+ if (start + 8 > end) return 0;
20236
+ const entryCount = buf.readUInt32BE(start + 4);
20237
+ let total = 0;
20238
+ for(let i = 0; i < entryCount; i++){
20239
+ const off = start + 8 + 8 * i;
20240
+ if (off + 8 > end) break;
20241
+ total += buf.readUInt32BE(off) * buf.readUInt32BE(off + 4);
20242
+ }
20243
+ return total;
20244
+ }
20245
+ function parseTfhd(buf, start, end) {
20246
+ if (start + 8 > end) return {
20247
+ trackId: 0,
20248
+ defaultSampleDuration: 0
20249
+ };
20250
+ const flags = buf.readUIntBE(start + 1, 3);
20251
+ const trackId = buf.readUInt32BE(start + 4);
20252
+ let off = start + 8;
20253
+ if (0x000001 & flags) off += 8;
20254
+ if (0x000002 & flags) off += 4;
20255
+ if (0x000008 & flags && off + 4 <= end) return {
20256
+ trackId,
20257
+ defaultSampleDuration: buf.readUInt32BE(off)
20258
+ };
20259
+ return {
20260
+ trackId,
20261
+ defaultSampleDuration: 0
20262
+ };
20263
+ }
20264
+ function parseTrunDuration(buf, start, end, defaultSampleDuration) {
20265
+ if (start + 8 > end) return 0;
20266
+ const flags = buf.readUIntBE(start + 1, 3);
20267
+ const sampleCount = buf.readUInt32BE(start + 4);
20268
+ let off = start + 8;
20269
+ if (0x000001 & flags) off += 4;
20270
+ if (0x000004 & flags) off += 4;
20271
+ const hasDuration = (0x000100 & flags) !== 0;
20272
+ if (!hasDuration) return sampleCount * defaultSampleDuration;
20273
+ const entrySize = 4 + ((0x000200 & flags) !== 0 ? 4 : 0) + ((0x000400 & flags) !== 0 ? 4 : 0) + ((0x000800 & flags) !== 0 ? 4 : 0);
20274
+ let total = 0;
20275
+ for(let i = 0; i < sampleCount; i++){
20276
+ const entryOff = off + i * entrySize;
20277
+ if (entryOff + 4 > end) break;
20278
+ total += buf.readUInt32BE(entryOff);
20279
+ }
20280
+ return total;
20281
+ }
20282
+ function parseStsdCodec(buf, start, end) {
20283
+ if (start + 16 > end) return null;
20284
+ if (0 === buf.readUInt32BE(start + 4)) return null;
20285
+ return buf.toString("latin1", start + 12, start + 16).toLowerCase();
20286
+ }
20287
+ function parseMvhd(buf, start, end) {
20288
+ const version = buf.readUInt8(start);
20289
+ if (1 === version) {
20290
+ if (start + 28 > end) return null;
20291
+ const timescale = buf.readUInt32BE(start + 20);
20292
+ const hi = buf.readUInt32BE(start + 24);
20293
+ const lo = buf.readUInt32BE(start + 28);
20294
+ return {
20295
+ timescale,
20296
+ duration: hi * 2 ** 32 + lo
20297
+ };
20298
+ }
20299
+ if (start + 20 > end) return null;
20300
+ return {
20301
+ timescale: buf.readUInt32BE(start + 12),
20302
+ duration: buf.readUInt32BE(start + 16)
20303
+ };
20304
+ }
20305
+ function parseTkhd(buf, start, end) {
20306
+ const version = buf.readUInt8(start);
20307
+ const afterDuration = 1 === version ? 36 : 24;
20308
+ const matrixOff = start + afterDuration + 16;
20309
+ const whOff = matrixOff + 36;
20310
+ const trackIdOff = start + (1 === version ? 20 : 12);
20311
+ const trackId = trackIdOff + 4 <= end ? buf.readUInt32BE(trackIdOff) : 0;
20312
+ if (whOff + 8 > end) return {
20313
+ trackId,
20314
+ width: 0,
20315
+ height: 0,
20316
+ rotation: 0
20317
+ };
20318
+ const width = buf.readUInt32BE(whOff) / 65536;
20319
+ const height = buf.readUInt32BE(whOff + 4) / 65536;
20320
+ const a = buf.readInt32BE(matrixOff) / 65536;
20321
+ const b = buf.readInt32BE(matrixOff + 4) / 65536;
20322
+ let rotation = 0;
20323
+ if (Math.abs(a) < 0.01 && Math.abs(b - 1) < 0.01) rotation = 90;
20324
+ else if (Math.abs(a + 1) < 0.01 && Math.abs(b) < 0.01) rotation = 180;
20325
+ else if (Math.abs(a) < 0.01 && Math.abs(b + 1) < 0.01) rotation = 270;
20326
+ return {
20327
+ trackId,
20328
+ width,
20329
+ height,
20330
+ rotation
20331
+ };
20332
+ }
20333
+ function parseVideoCodec(filePath) {
20334
+ return parseVideoMeta(filePath)?.codec ?? null;
20335
+ }
20336
+ function buildVideoMetaFromParams(filePath, metadata) {
20337
+ return {
20338
+ width: Math.round(metadata.width),
20339
+ height: Math.round(metadata.height),
20340
+ duration: metadata.duration,
20341
+ rotation: 0,
20342
+ fileSize: metadata.fileSize,
20343
+ codec: parseVideoCodec(filePath)
20344
+ };
20345
+ }
20346
+ const MAX_DURATION_SECONDS = 28800;
20347
+ const MAX_FILE_SIZE = 21474836480;
20348
+ const ALLOWED_EXTENSIONS = [
20349
+ ".mp4"
20350
+ ];
20351
+ const ALLOWED_CODECS = [
20352
+ "avc1",
20353
+ "avc3"
20354
+ ];
20355
+ const MIN_TITLE_LENGTH = 6;
20356
+ const MAX_TITLE_LENGTH = 16;
20357
+ function formatFileSize(bytes) {
20358
+ if (bytes < 1048576) return `${(bytes / 1024).toFixed(2)} KB`;
20359
+ if (bytes < 1073741824) return `${(bytes / 1024 / 1024).toFixed(2)} MB`;
20360
+ return `${(bytes / 1024 / 1024 / 1024).toFixed(2)} GB`;
20361
+ }
20362
+ function formatDuration(seconds) {
20363
+ const total = Math.round(seconds);
20364
+ const h = Math.floor(total / 3600);
20365
+ const m = Math.floor(total % 3600 / 60);
20366
+ const s = total % 60;
20367
+ if (h > 0) return `${h}小时${m}分${s}秒`;
20368
+ if (m > 0) return `${m}分${s}秒`;
20369
+ return `${s}秒`;
20370
+ }
20371
+ function validateShipinhaoVideo(filePath, meta) {
20372
+ const fileName = external_node_path_default().basename(filePath);
20373
+ const ext = external_node_path_default().extname(fileName).toLowerCase();
20374
+ if (!ALLOWED_EXTENSIONS.includes(ext)) return `视频格式不支持:${fileName}。视频号仅支持 MP4/H.264 格式,请转换后重试。`;
20375
+ if (meta.duration > MAX_DURATION_SECONDS) return `视频时长超过限制:${fileName}(${formatDuration(meta.duration)})。视频号视频时长不能超过 8 小时,请剪辑后重试。`;
20376
+ if (meta.fileSize > MAX_FILE_SIZE) return `视频大小超过限制:${fileName}(${formatFileSize(meta.fileSize)})。视频号视频不能超过 20GB,请压缩后重试。`;
20377
+ if (meta.codec && !ALLOWED_CODECS.includes(meta.codec)) return `视频编码不支持:${fileName}(${meta.codec})。视频号仅支持 H.264 编码,请转码后重试。`;
20378
+ return null;
20379
+ }
20380
+ function validateShipinhaoTitle(title) {
20381
+ if (void 0 === title) return null;
20382
+ const trimmed = title.trim();
20383
+ if ("" === trimmed) return null;
20384
+ const length = [
20385
+ ...trimmed
20386
+ ].length;
20387
+ if (length < MIN_TITLE_LENGTH || length > MAX_TITLE_LENGTH) return `视频号标题需要在 ${MIN_TITLE_LENGTH}-${MAX_TITLE_LENGTH} 个字符之间,当前 ${length} 个字符,请调整后重试。`;
20388
+ return null;
20389
+ }
20390
+ const POST_CREATE_PAGE_URL = "https://channels.weixin.qq.com/micro/content/post/create";
20391
+ const MICRO_CONTENT_BASE = "https://channels.weixin.qq.com/micro/content/cgi-bin/mmfinderassistant-bin";
20392
+ function resolveClientContext(params, fallbackUin) {
20393
+ const extra = params.extraParam || {};
20394
+ const deviceIdCookie = params.cookies.find((c)=>"device_id" === c.name || "finger_print_device_id" === c.name)?.value;
20395
+ return {
20396
+ aId: "string" == typeof extra.aId ? extra.aId : "",
20397
+ fingerPrintDeviceId: "string" == typeof extra.fingerPrintDeviceId ? extra.fingerPrintDeviceId : deviceIdCookie || "",
20398
+ uin: "string" == typeof extra.uin ? extra.uin : String(fallbackUin)
20399
+ };
20400
+ }
20401
+ function buildPublishHeaders(cookieString, client) {
20402
+ const headers = {
20403
+ cookie: cookieString,
20404
+ referer: POST_CREATE_PAGE_URL,
20405
+ origin: "https://channels.weixin.qq.com",
20406
+ "content-type": "application/json"
20407
+ };
20408
+ if (client.fingerPrintDeviceId) headers["finger-print-device-id"] = client.fingerPrintDeviceId;
20409
+ if (client.uin) headers["x-wechat-uin"] = client.uin;
20410
+ return headers;
20411
+ }
20412
+ function buildPublishQuery(client) {
20413
+ const query = {
20414
+ _rid: rid(),
20415
+ _pageUrl: POST_CREATE_PAGE_URL
20416
+ };
20417
+ if (client.aId) query._aid = client.aId;
20418
+ return query;
20419
+ }
20420
+ function buildCommonBody(finderUsername) {
20421
+ return {
20422
+ timestamp: String(Date.now()),
20423
+ _log_finder_uin: "",
20424
+ _log_finder_id: finderUsername,
20425
+ rawKeyBuff: "",
20426
+ pluginSessionId: null,
20427
+ scene: 7,
20428
+ reqScene: 7
20429
+ };
20430
+ }
20431
+ async function getTraceKey(auth, client, http, logger) {
20432
+ logger.info("[getTraceKey] 开始获取 traceKey...");
20433
+ const res = await http.api({
20434
+ method: "POST",
20435
+ url: `${MICRO_CONTENT_BASE}/post/get-finder-post-trace-key`,
20436
+ params: buildPublishQuery(client),
20437
+ data: {
20438
+ objectId: "",
20439
+ ...buildCommonBody(auth.finderUsername)
20440
+ },
20441
+ defaultErrorMsg: "获取 traceKey 失败"
20442
+ });
20443
+ if (0 !== res.errCode || !res.data?.traceKey) {
20444
+ logger.error("[getTraceKey] 获取失败:", JSON.stringify(res));
20445
+ throw new Error(`获取 traceKey 失败: ${JSON.stringify(res)}`);
20446
+ }
20447
+ logger.info(`[getTraceKey] 获取成功: ${res.data.traceKey}`);
20448
+ return res.data.traceKey;
20449
+ }
20450
+ async function getObjectTagKey(auth, client, http, logger) {
20451
+ logger.info("[getObjectTagKey] 获取内容声明 tagKey...");
20452
+ try {
20453
+ const res = await http.api({
20454
+ method: "POST",
20455
+ url: `${MICRO_CONTENT_BASE}/post/finder_get_object_tag_list`,
20456
+ params: buildPublishQuery(client),
20457
+ data: {
20458
+ source: 1,
20459
+ ...buildCommonBody(auth.finderUsername)
20460
+ },
20461
+ defaultErrorMsg: "获取内容声明标注失败"
20462
+ });
20463
+ if (0 !== res.errCode || !res.data?.tagKey) {
20464
+ logger.warn(`[getObjectTagKey] 未取到 tagKey: ${JSON.stringify(res)}`);
20465
+ return null;
20466
+ }
20467
+ logger.info(`[getObjectTagKey] tagKey: ${res.data.tagKey}`);
20468
+ return res.data.tagKey;
20469
+ } catch (error) {
20470
+ logger.warn(`[getObjectTagKey] 获取 tagKey 异常: ${stringifyError(error)}`);
20471
+ return null;
20472
+ }
20473
+ }
20474
+ async function submitAndPollTranscode(opts) {
20475
+ const { videoUrl, videoMeta, traceKey, uploadStartTime, uploadEndTime, finderUsername, client, http, logger } = opts;
20476
+ logger.info("[submitAndPollTranscode] 开始提交转码任务...");
20477
+ const finderUrl = videoUrl.includes("wxapp.tc.qq.com") ? `https://finder.video.qq.com${videoUrl.split("qq.com")[1]}` : videoUrl;
20478
+ logger.info(`[submitAndPollTranscode] 视频尺寸: ${videoMeta.width}x${videoMeta.height}, 时长: ${videoMeta.duration}s`);
20479
+ const submitRes = await http.api({
20480
+ method: "POST",
20481
+ url: `${MICRO_CONTENT_BASE}/post/post_clip_video`,
20482
+ params: buildPublishQuery(client),
20483
+ data: {
20484
+ url: finderUrl,
20485
+ timeStart: 0,
20486
+ cropDuration: 0,
20487
+ height: videoMeta.height,
20488
+ width: videoMeta.width,
20489
+ x: 0,
20490
+ y: 0,
20491
+ clipOriginVideoInfo: {
20492
+ width: videoMeta.width,
20493
+ height: videoMeta.height,
20494
+ duration: videoMeta.duration,
20495
+ fileSize: videoMeta.fileSize
20496
+ },
20497
+ traceInfo: {
20498
+ traceKey,
20499
+ uploadCdnStart: uploadStartTime,
20500
+ uploadCdnEnd: uploadEndTime
20501
+ },
20502
+ targetWidth: videoMeta.width,
20503
+ targetHeight: videoMeta.height,
20504
+ type: 4,
20505
+ useAstraThumbCover: 1,
20506
+ ...buildCommonBody(finderUsername)
20507
+ },
20508
+ defaultErrorMsg: "提交转码失败"
20509
+ });
20510
+ if (0 !== submitRes.errCode || !submitRes.data?.clipKey) {
20511
+ logger.error("[submitAndPollTranscode] 提交转码失败:", JSON.stringify(submitRes));
20512
+ throw new Error(`提交转码失败: ${JSON.stringify(submitRes)}`);
20513
+ }
20514
+ const { clipKey, draftId } = submitRes.data;
20515
+ logger.info(`[submitAndPollTranscode] 转码任务已提交,clipKey: ${clipKey}, draftId: ${draftId}`);
20516
+ const pollInterval = 5000;
20517
+ const pollBudget = Math.min(1800000, 300000 + 1000 * Math.ceil(1.5 * videoMeta.duration));
20518
+ const maxPolls = Math.ceil(pollBudget / pollInterval);
20519
+ let pollCount = 0;
20520
+ logger.info(`[submitAndPollTranscode] 开始轮询转码结果,最多 ${maxPolls} 次(${Math.round(pollBudget / 1000)}s),间隔 ${pollInterval / 1000}s`);
20521
+ while(pollCount < maxPolls){
20522
+ await sleep(pollInterval);
20523
+ pollCount++;
20524
+ const pollRes = await http.api({
20525
+ method: "POST",
20526
+ url: `${MICRO_CONTENT_BASE}/post/post_clip_video_result`,
20527
+ params: buildPublishQuery(client),
20528
+ data: {
20529
+ clipKey,
20530
+ draftId,
20531
+ ...buildCommonBody(finderUsername)
20532
+ },
20533
+ defaultErrorMsg: "转码轮询失败"
20534
+ }, {
20535
+ timeout: 60000,
20536
+ retries: 2,
20537
+ retryDelay: 3000
20538
+ });
20539
+ if (0 !== pollRes.errCode) {
20540
+ logger.error(`[submitAndPollTranscode] 转码轮询失败 (poll ${pollCount}):`, JSON.stringify(pollRes));
20541
+ throw new Error(`转码轮询失败 (poll ${pollCount}): ${JSON.stringify(pollRes)}`);
20542
+ }
20543
+ const { flag, url, width, height, duration, md5, fileSize } = pollRes.data || {};
20544
+ logger.info(`[submitAndPollTranscode] 轮询第 ${pollCount} 次,flag=${flag}`);
20545
+ if (1 === flag) {
20546
+ if (!url || !width || !height || !duration || !md5 || !fileSize) {
20547
+ logger.error("[submitAndPollTranscode] 转码完成但返回数据不完整:", JSON.stringify(pollRes.data));
20548
+ throw new Error(`转码完成但返回数据不完整: ${JSON.stringify(pollRes.data)}`);
20549
+ }
20550
+ logger.info(`[submitAndPollTranscode] 转码完成! 用时: ${pollCount * pollInterval / 1000}s`);
20551
+ logger.info(`[submitAndPollTranscode] 视频信息: ${width}x${height}, 时长: ${duration}s, 大小: ${fileSize}`);
20552
+ return {
20553
+ clipKey,
20554
+ url,
20555
+ width,
20556
+ height,
20557
+ duration,
20558
+ md5,
20559
+ fileSize
20560
+ };
20561
+ }
20562
+ if (2 === flag) logger.info(`[submitAndPollTranscode] 转码中... (${pollCount}/${maxPolls})`);
20563
+ else {
20564
+ logger.error(`[submitAndPollTranscode] 转码失败,未知 flag=${flag}:`, JSON.stringify(pollRes.data));
20565
+ throw new Error(`转码失败,未知 flag=${flag}: ${JSON.stringify(pollRes.data)}`);
20566
+ }
20567
+ }
20568
+ logger.error(`[submitAndPollTranscode] 转码超时,已轮询 ${maxPolls} 次,用时: ${maxPolls * pollInterval / 1000}s`);
20569
+ throw new Error(`转码超时 (${maxPolls * pollInterval / 1000}s)`);
20570
+ }
20571
+ async function publishVideo(opts) {
20572
+ const { params, auth, client, clipResult, videoUpload, coverUpload, verticalCoverUpload, videoMeta, traceKey, tagKey, uploadStartTime, uploadEndTime, proxyHttp, logger } = opts;
20573
+ logger.info("[publishVideo] 开始构建发布请求...");
20574
+ const toFinderUrl = (url)=>url.includes("wxapp.tc.qq.com") ? `https://finder.video.qq.com${url.split("qq.com")[1]}` : url;
20575
+ const thumbFinderUrl = toFinderUrl(coverUpload.downloadUrl);
20576
+ const coverFinderUrl = toFinderUrl(verticalCoverUpload.downloadUrl);
20577
+ const md5sumUuid = external_node_crypto_default().randomUUID();
20578
+ const description = params.description;
20579
+ logger.info("[publishVideo] 发布参数:");
20580
+ logger.info(` - 短标题: ${params.title || "(无)"}`);
20581
+ logger.info(` - 描述: ${description.substring(0, 50)}${description.length > 50 ? "..." : ""}`);
20582
+ logger.info(` - 定时发布: ${params.scheduledTime ? new Date(1000 * params.scheduledTime).toLocaleString() : "立即发布"}`);
20583
+ const objectDesc = {
20584
+ mpTitle: "",
20585
+ description,
20586
+ extReading: buildExtReading(params.link),
20587
+ mediaType: 4,
20588
+ location: payload_buildLocation(params.location),
20589
+ topic: buildTopic({
20590
+ description: params.description,
20591
+ topics: params.topics,
20592
+ mentionedUsers: params.mentionedUsers,
20593
+ collection: params.collection
20594
+ }),
20595
+ event: buildEvent(params.event),
20596
+ mentionedUser: buildMentionedUser(params.mentionedUsers),
20597
+ media: [
20598
+ {
20599
+ url: clipResult.url,
20600
+ fileSize: clipResult.fileSize,
20601
+ thumbUrl: thumbFinderUrl,
20602
+ fullThumbUrl: thumbFinderUrl,
20603
+ coverUrl: coverFinderUrl,
20604
+ fullCoverUrl: coverFinderUrl,
20605
+ shareCoverUrl: coverFinderUrl,
20606
+ mediaType: 4,
20607
+ videoPlayLen: Math.round(clipResult.duration),
20608
+ width: clipResult.width,
20609
+ height: clipResult.height,
20610
+ md5sum: md5sumUuid,
20611
+ cardShowStyle: 2,
20612
+ urlCdnTaskId: clipResult.clipKey
20613
+ }
20614
+ ],
20615
+ shortTitle: params.title ? [
20616
+ {
20617
+ shortTitle: params.title
20618
+ }
20619
+ ] : [],
20620
+ member: {}
20621
+ };
20622
+ const publishData = {
20623
+ objectType: 0,
20624
+ longitude: 0,
20625
+ latitude: 0,
20626
+ feedLongitude: 0,
20627
+ feedLatitude: 0,
20628
+ originalFlag: params.originalFlag ?? 0,
20629
+ topics: params.topics || [],
20630
+ isFullPost: 1,
20631
+ handleFlag: 2,
20632
+ videoClipTaskId: clipResult.clipKey,
20633
+ traceInfo: {
20634
+ traceKey,
20635
+ uploadCdnStart: uploadStartTime,
20636
+ uploadCdnEnd: uploadEndTime
20637
+ },
20638
+ objectDesc,
20639
+ report: {
20640
+ clipKey: clipResult.clipKey,
20641
+ draftId: clipResult.clipKey,
20642
+ ...buildCommonBody(auth.finderUsername),
20643
+ height: videoMeta.height,
20644
+ width: videoMeta.width,
20645
+ duration: videoMeta.duration,
20646
+ fileSize: videoUpload.fileSize,
20647
+ uploadCost: (uploadEndTime - uploadStartTime) * 1000
20648
+ },
20649
+ postFlag: 0,
20650
+ mode: 1,
20651
+ clientid: external_node_crypto_default().randomUUID(),
20652
+ ...buildCommonBody(auth.finderUsername)
20653
+ };
20654
+ if (params.scheduledTime) publishData.effectiveTime = params.scheduledTime;
20655
+ if (params.tagInfo && tagKey) publishData.tagInfo = buildTagInfo(params.tagInfo, tagKey);
20656
+ logger.info("[publishVideo] 开始发布视频,全部参数:" + JSON.stringify(publishData));
20657
+ const publishRes = await proxyHttp.api({
20658
+ method: "POST",
20659
+ url: `${MICRO_CONTENT_BASE}/post/post_create`,
20660
+ params: buildPublishQuery(client),
20661
+ data: publishData,
20662
+ defaultErrorMsg: "发布视频失败"
20663
+ });
20664
+ logger.info(`[publishVideo] 发布响应: errCode=${publishRes.errCode}, baseResp.errcode=${publishRes.data?.baseResp?.errcode}`);
20665
+ return publishRes;
20666
+ }
20667
+ function sleep(ms) {
20668
+ return new Promise((resolve)=>setTimeout(resolve, ms));
20669
+ }
20670
+ async function resolveLocalCoverPath(coverPath, label, tmpCachePath, logger) {
20671
+ if (!/^https?:\/\//i.test(coverPath)) return coverPath;
20672
+ const fileName = (0, share_namespaceObject.getFilenameFromUrl)(coverPath);
20673
+ const savePath = external_node_path_default().join(tmpCachePath, `${Date.now()}-${label}-${fileName}`);
20674
+ await (0, share_namespaceObject.downloadImage)(coverPath, savePath);
20675
+ return savePath;
20676
+ }
20677
+ const shipinhaoPublishVideo_mock_mockAction = async (task, params)=>{
20678
+ task.logger.info("[shipinhaoPublishVideo] 开始执行视频号视频发布 - Mock API 方式");
20679
+ const updateTaskState = task.taskStageStore?.update?.bind(task.taskStageStore, task.taskId || "");
20680
+ let currentStep = "初始化";
20681
+ try {
20682
+ task.logger.info(`[shipinhaoPublishVideo] 发布方式: ${params.scheduledTime ? `定时 ${new Date(1000 * params.scheduledTime).toLocaleString()}` : "立即发布"}`);
20683
+ currentStep = "解析认证信息";
20684
+ const cookieString = params.cookies.map((c)=>`${c.name}=${c.value}`).join("; ");
20685
+ const http = new Http({
20686
+ headers: {
20687
+ cookie: cookieString
20688
+ }
20689
+ });
20690
+ currentStep = "验证发布参数";
20691
+ if (!params.videoPath) return (0, share_namespaceObject.response)(414, "视频文件路径不能为空", "");
20692
+ if (!params.coverPath) return (0, share_namespaceObject.response)(414, "横屏封面图片路径不能为空", "");
20693
+ currentStep = "获取上传认证";
20694
+ task.logger.info("[shipinhaoPublishVideo] 获取上传认证...");
20695
+ const auth = await getShipinhaoUploadAuth(cookieString, http);
20696
+ const client = resolveClientContext(params, auth.uin);
20697
+ if (!client.aId) task.logger.warn("[shipinhaoPublishVideo] extraParam.aId 缺失,query 将不带 _aid");
20698
+ if (!client.fingerPrintDeviceId) task.logger.warn("[shipinhaoPublishVideo] extraParam.fingerPrintDeviceId 缺失,请求将不带 finger-print-device-id");
20699
+ const publishHeaders = buildPublishHeaders(cookieString, client);
20700
+ const microHttp = new Http({
20701
+ headers: publishHeaders
20702
+ });
20703
+ const args = [
20704
+ {
20705
+ headers: publishHeaders
20706
+ },
20707
+ task.logger,
20708
+ params.proxyLoc,
20709
+ params.accountId,
20710
+ "shipinhao"
20711
+ ];
20712
+ const proxyHttp = new Http(...args);
20713
+ currentStep = "组装视频元数据";
20714
+ task.logger.info("[shipinhaoPublishVideo] 组装视频元数据...");
20715
+ const videoMeta = buildVideoMetaFromParams(params.videoPath, params.videoMetadata);
20716
+ task.logger.info(`[shipinhaoPublishVideo] 视频: ${videoMeta.width}×${videoMeta.height}, ${videoMeta.duration.toFixed(2)}s, ${(videoMeta.fileSize / 1024 / 1024).toFixed(2)}MB, codec=${videoMeta.codec || "unknown"}`);
20717
+ if (!videoMeta.codec) task.logger.warn("[shipinhaoPublishVideo] 未能读取视频编码格式,跳过 H.264 预检,交由服务端判断");
20718
+ currentStep = "校验视频限制";
20719
+ const validationError = validateShipinhaoVideo(params.videoPath, videoMeta);
20720
+ if (validationError) {
20721
+ task.logger.error(`[shipinhaoPublishVideo] 视频校验未通过: ${validationError}`);
20722
+ await updateTaskState?.({
20723
+ state: share_namespaceObject.TaskState.FAILED,
20724
+ error: validationError
20725
+ });
20726
+ return (0, share_namespaceObject.response)(414, validationError, "");
20727
+ }
20728
+ task.logger.info("[shipinhaoPublishVideo] 视频校验通过");
20729
+ currentStep = "校验标题";
20730
+ const titleError = validateShipinhaoTitle(params.title);
20731
+ if (titleError) {
20732
+ task.logger.error(`[shipinhaoPublishVideo] 标题校验未通过: ${titleError}`);
20733
+ await updateTaskState?.({
20734
+ state: share_namespaceObject.TaskState.FAILED,
20735
+ error: titleError
20736
+ });
20737
+ return (0, share_namespaceObject.response)(414, titleError, "");
20738
+ }
20739
+ currentStep = "获取 traceKey";
20740
+ task.logger.info("[shipinhaoPublishVideo] 获取 traceKey...");
20741
+ const traceKey = await getTraceKey(auth, client, microHttp, task.logger);
20742
+ let tagKey = null;
20743
+ if (params.tagInfo) {
20744
+ currentStep = "获取内容声明 tagKey";
20745
+ tagKey = await getObjectTagKey(auth, client, microHttp, task.logger);
20746
+ }
20747
+ const uploadStartTime = Math.floor(Date.now() / 1000);
20748
+ task.logger.info(`[shipinhaoPublishVideo] 上传开始时间: ${uploadStartTime}`);
20749
+ currentStep = "上传视频";
20750
+ task.logger.info("[shipinhaoPublishVideo] 上传视频...");
20751
+ task.logger.info(`[shipinhaoPublishVideo] 视频路径: ${params.videoPath}`);
20752
+ task.logger.info(`[shipinhaoPublishVideo] 视频文件类型: ${auth.videoFileType}`);
20753
+ const videoUpload = await uploader_uploadFile({
20754
+ filePath: params.videoPath,
20755
+ fileType: auth.videoFileType,
20756
+ uin: auth.uin,
20757
+ authKey: auth.authKey,
20758
+ http,
20759
+ logger: task.logger
20760
+ });
20761
+ task.logger.info("[shipinhaoPublishVideo] 视频上传完成");
20762
+ const uploadEndTime = Math.floor(Date.now() / 1000);
20763
+ task.logger.info(`[shipinhaoPublishVideo] 上传结束时间: ${uploadEndTime}, 耗时: ${uploadEndTime - uploadStartTime}s`);
20764
+ currentStep = "上传横屏封面";
20765
+ const localCoverPath = await resolveLocalCoverPath(params.coverPath, "横屏封面", task.getTmpPath(), task.logger);
20766
+ task.logger.info("[shipinhaoPublishVideo] 上传横屏封面...");
20767
+ const coverUpload = await uploader_uploadFile({
20768
+ filePath: localCoverPath,
20769
+ fileType: auth.pictureFileType,
20770
+ uin: auth.uin,
20771
+ authKey: auth.authKey,
20772
+ http,
20773
+ logger: task.logger
20774
+ });
20775
+ task.logger.info("[shipinhaoPublishVideo] 横屏封面上传完成");
20776
+ let verticalCoverUpload = coverUpload;
20777
+ if (params.verticalCoverPath) {
20778
+ currentStep = "上传竖屏封面";
20779
+ const localVerticalPath = await resolveLocalCoverPath(params.verticalCoverPath, "竖屏封面", task.getTmpPath(), task.logger);
20780
+ task.logger.info("[shipinhaoPublishVideo] 上传竖屏封面");
20781
+ verticalCoverUpload = await uploader_uploadFile({
20782
+ filePath: localVerticalPath,
20783
+ fileType: auth.pictureFileType,
20784
+ uin: auth.uin,
20785
+ authKey: auth.authKey,
20786
+ http,
20787
+ logger: task.logger
20788
+ });
20789
+ task.logger.info("[shipinhaoPublishVideo] 竖屏封面上传完成");
20790
+ } else task.logger.info("[shipinhaoPublishVideo] 未传竖屏封面,复用横屏封面");
20791
+ currentStep = "提交转码";
20792
+ task.logger.info("[shipinhaoPublishVideo] 提交转码...");
20793
+ const clipResult = await submitAndPollTranscode({
20794
+ videoUrl: videoUpload.downloadUrl,
20795
+ videoMeta,
20796
+ traceKey,
20797
+ uploadStartTime,
20798
+ uploadEndTime,
20799
+ finderUsername: auth.finderUsername,
20800
+ client,
20801
+ http: microHttp,
20802
+ logger: task.logger
20803
+ });
20804
+ currentStep = "发布视频";
20805
+ task.logger.info("[shipinhaoPublishVideo] 发布视频...");
20806
+ task.logger.info(`[shipinhaoPublishVideo] clipKey: ${clipResult.clipKey}`);
20807
+ let publishResult;
20808
+ try {
20809
+ publishResult = await publishVideo({
20810
+ params,
20811
+ auth,
20812
+ client,
20813
+ clipResult,
20814
+ videoUpload,
20815
+ coverUpload,
20816
+ verticalCoverUpload,
20817
+ videoMeta,
20818
+ traceKey,
20819
+ tagKey,
20820
+ uploadStartTime,
20821
+ uploadEndTime,
20822
+ proxyHttp,
20823
+ logger: task.logger
20824
+ });
20825
+ } catch (error) {
20826
+ const handledError = Http.handleApiError(error);
20827
+ task.logger.error(`[shipinhaoPublishVideo] 发布请求失败: ${handledError.message}`, stringifyError(handledError));
20828
+ const classified = classifyPublishError(handledError);
20829
+ if (classified) {
20830
+ const message = `${classified.userMessage}${task.debug ? ` ${http.proxyInfo}` : ""}`;
20831
+ task.logger.error(`[shipinhaoPublishVideo] ${classified.category},直接返回: ${handledError.message} (code=${handledError.code})`, stringifyError(handledError));
20832
+ await updateTaskState?.({
20833
+ state: share_namespaceObject.TaskState.FAILED,
20834
+ error: message
20835
+ });
20836
+ return {
20837
+ code: 414,
20838
+ data: "",
20839
+ message
20840
+ };
20841
+ }
20842
+ throw error;
20843
+ }
20844
+ task.logger.info(`[shipinhaoPublishVideo] publishResult: ${JSON.stringify(publishResult)}`);
20845
+ const resultCode = publishResult.data?.baseResp?.errcode ?? publishResult.errCode;
20846
+ const resultMsg = publishResult.data?.baseResp?.errmsg ?? (0 === resultCode ? "发布成功" : `发布失败(errCode=${resultCode})`);
20847
+ if (0 === resultCode) {
20848
+ task.logger.info("[shipinhaoPublishVideo] 发布成功");
20849
+ task.logger.info(`[shipinhaoPublishVideo] 作品ID: ${clipResult.clipKey}`);
20850
+ task.logger.info(`[shipinhaoPublishVideo] 视频URL: ${clipResult.url}`);
20851
+ task.logger.info(`[shipinhaoPublishVideo] 横屏封面URL: ${coverUpload.downloadUrl}`);
20852
+ task.logger.info(`[shipinhaoPublishVideo] 竖屏封面URL: ${verticalCoverUpload.downloadUrl}`);
20853
+ await updateTaskState?.({
20854
+ state: share_namespaceObject.TaskState.SUCCESS,
20855
+ result: {
20856
+ response: resultMsg
20857
+ }
20858
+ });
20859
+ reportLogger({
20860
+ token: params.huiwenToken || "",
20861
+ enverionment: task.enverionment || "development",
20862
+ postId: params.articleId,
20863
+ eip: proxyHttp.proxyInfo,
20864
+ accountId: params.accountId,
20865
+ uid: params.uid,
20866
+ publishParams: {
20867
+ videoPath: params.videoPath,
20868
+ coverPath: params.coverPath,
20869
+ verticalCoverPath: params.verticalCoverPath,
20870
+ title: params.title,
20871
+ topics: params.topics,
20872
+ mentionedUsers: params.mentionedUsers,
20873
+ collection: params.collection,
20874
+ event: params.event,
20875
+ link: params.link,
20876
+ tagInfo: params.tagInfo,
20877
+ originalFlag: params.originalFlag,
20878
+ scheduledTime: params.scheduledTime
20879
+ },
20880
+ platform: "shipinhao"
20881
+ });
20882
+ task.logger.info("[shipinhaoPublishVideo] 日志上报完成");
20883
+ return (0, share_namespaceObject.response)(0, "发布成功", clipResult.clipKey);
20884
+ }
20885
+ let errorMessage = resultMsg;
20886
+ if (-11224 === resultCode) errorMessage = "视频号管理员完成实名且绑定手机号后才可以发表";
20887
+ else if (300333 === resultCode || 300334 === resultCode) errorMessage = "登录失效";
20888
+ else if (300330 === resultCode) errorMessage = "未登录";
20889
+ else if (300002 === resultCode) errorMessage = "官方平台在校验音乐/位置/定时信息时失败了,请重新编辑后发布";
20890
+ task.logger.error(`[shipinhaoPublishVideo] 发布失败: ${errorMessage} (errCode=${resultCode})`);
20891
+ await updateTaskState?.({
20892
+ state: share_namespaceObject.TaskState.FAILED,
20893
+ error: errorMessage
20894
+ });
20895
+ return (0, share_namespaceObject.response)(resultCode || 414, errorMessage, "");
20896
+ } catch (error) {
20897
+ const handledError = Http.handleApiError(error);
20898
+ const errorMsg = handledError.message || "发布失败,请稍后重试";
20899
+ const errorCode = handledError.code || 414;
20900
+ task.logger.error(`[shipinhaoPublishVideo] 发布流程异常 [${currentStep}]: ${errorMsg}`, stringifyError(error), handledError.extra);
20901
+ task.logger.error(`[shipinhaoPublishVideo] 错误码: ${errorCode}, 当前步骤: ${currentStep}`);
20902
+ await updateTaskState?.({
20903
+ state: share_namespaceObject.TaskState.FAILED,
20904
+ error: errorMsg
20905
+ });
20906
+ return (0, share_namespaceObject.response)(errorCode, errorMsg, "");
20907
+ }
20908
+ };
20909
+ const shipinhaoPublishVideo_rpa_rpaAction = async (task, params)=>{
20910
+ task.logger.info("开始微信视频号视频发布(RPA 模式)");
20911
+ const videoMeta = buildVideoMetaFromParams(params.videoPath, params.videoMetadata);
20912
+ task.logger.info(`视频: ${videoMeta.width}×${videoMeta.height}, ${videoMeta.duration.toFixed(2)}s, ${(videoMeta.fileSize / 1024 / 1024).toFixed(2)}MB, codec=${videoMeta.codec || "unknown"}`);
20913
+ if (!videoMeta.codec) task.logger.warn("未能读取视频编码格式,跳过 H.264 预检,交由服务端判断");
20914
+ const validationError = validateShipinhaoVideo(params.videoPath, videoMeta);
20915
+ if (validationError) {
20916
+ task.logger.error(`视频校验未通过: ${validationError}`);
20917
+ return (0, share_namespaceObject.response)(414, validationError, "");
20918
+ }
20919
+ task.logger.info("视频校验通过");
20920
+ const titleError = validateShipinhaoTitle(params.title);
20921
+ if (titleError) {
20922
+ task.logger.error(`标题校验未通过: ${titleError}`);
20923
+ return (0, share_namespaceObject.response)(414, titleError, "");
20924
+ }
20925
+ const unsupported = [
20926
+ params.verticalCoverPath && "verticalCoverPath",
20927
+ params.collection && "collection",
20928
+ params.originalFlag && "originalFlag",
20929
+ params.postWithMemberZoneLink && "postWithMemberZoneLink"
20930
+ ].filter(Boolean);
20931
+ if (unsupported.length) task.logger.warn(`RPA 模式不支持以下参数,将被忽略: ${unsupported.join("、")};如需生效请使用 mockApi 模式`);
20932
+ if (params.tagInfo && 5 === params.tagInfo.tagType) {
20933
+ const shootInfo = params.tagInfo.shootInfo;
20934
+ if (shootInfo && (shootInfo.provinceCode || shootInfo.cityCode)) task.logger.warn("tagInfo.tagType=5 在 RPA 模式下仅支持拍摄时间和国家选择,省市选择需要使用 mockApi 模式");
20935
+ }
20936
+ const tmpCachePath = task.getTmpPath();
20937
+ const page = await task.createPage({
20938
+ url: "https://channels.weixin.qq.com/platform/post/create",
20939
+ show: task.debug,
20940
+ cookies: params.cookies
20941
+ });
20942
+ try {
20943
+ const waitForElement = async (selector, timeout = 10000)=>{
20944
+ try {
20945
+ const element = page.locator(selector);
20946
+ await element.waitFor({
20947
+ state: "visible",
20948
+ timeout
20949
+ });
20950
+ return element;
20951
+ } catch {
20952
+ task.logger.warn(`元素未找到: ${selector}`);
20953
+ return null;
20954
+ }
20955
+ };
20956
+ const retryAction = async (action, maxRetries = 3, delay = 1000)=>{
20957
+ let lastError;
20958
+ for(let i = 0; i < maxRetries; i++)try {
20959
+ return await action();
20960
+ } catch (error) {
20961
+ lastError = error;
20962
+ task.logger.warn(`重试 ${i + 1}/${maxRetries}: ${lastError.message}`);
20963
+ if (i < maxRetries - 1) await page.waitForTimeout(delay);
20964
+ }
20965
+ throw lastError;
20966
+ };
20967
+ task.logger.info("等待页面加载...");
20968
+ task.logger.info("检查登录状态...");
20969
+ if (task.debug) {
20970
+ task.logger.info(`当前页面 URL: ${page.url()}`);
20971
+ const title = await page.title();
20972
+ task.logger.info(`页面标题: ${title}`);
20973
+ }
20974
+ try {
20975
+ await page.waitForSelector(".post-edit-wrap", {
20976
+ state: "visible",
20977
+ timeout: 30000
20978
+ });
20979
+ task.logger.info("✓ 登录状态正常,找到编辑器容器");
20980
+ } catch {
20981
+ task.logger.error("✗ 未找到编辑器,可能登录失效");
20982
+ return {
20983
+ code: 414,
20984
+ message: "登录失效或页面加载异常",
20985
+ data: page.url()
20986
+ };
20987
+ }
20988
+ task.logger.info("页面加载完成,开始填充内容");
20989
+ task.logger.info("开始上传视频");
20990
+ await retryAction(async ()=>{
20991
+ const videoUploadSelectors = [
20992
+ '.ant-upload-btn input[type="file"][accept*="video"]',
20993
+ '.upload input[type="file"][accept*="video"]',
20994
+ 'input[type="file"][accept*="video"]'
20995
+ ];
20996
+ let uploadInput = null;
20997
+ if (task.debug) {
20998
+ const allFileInputs = await page.locator('input[type="file"]').count();
20999
+ task.logger.info(`页面中共找到 ${allFileInputs} 个文件上传输入框`);
21000
+ }
21001
+ for (const selector of videoUploadSelectors){
21002
+ const input = page.locator(selector);
21003
+ const count = await input.count();
21004
+ if (count > 0) {
21005
+ uploadInput = input.first();
21006
+ task.logger.info(`找到视频上传输入框: ${selector}`);
21007
+ break;
21008
+ }
21009
+ }
21010
+ if (!uploadInput) {
21011
+ task.logger.warn("未找到视频上传输入框,等待 3 秒后重试...");
21012
+ await page.waitForTimeout(3000);
21013
+ const anyFileInput = page.locator('input[type="file"]');
21014
+ const inputCount = await anyFileInput.count();
21015
+ if (inputCount > 0) {
21016
+ uploadInput = anyFileInput.first();
21017
+ task.logger.info(`找到文件输入框(共 ${inputCount} 个)`);
21018
+ } else {
21019
+ if (task.debug) {
21020
+ const screenshotPath = external_node_path_default().join(tmpCachePath, `upload-error-${Date.now()}.png`);
21021
+ await page.screenshot({
21022
+ path: screenshotPath,
21023
+ fullPage: true
21024
+ });
21025
+ task.logger.error(`未找到上传输入框,已截图保存至: ${screenshotPath}`);
21026
+ }
21027
+ throw new Error("未找到视频上传输入框");
21028
+ }
21029
+ }
21030
+ await uploadInput.setInputFiles(params.videoPath);
21031
+ task.logger.info("视频上传成功");
21032
+ await page.waitForTimeout(5000);
21033
+ });
21034
+ if (params.coverPath) {
21035
+ task.logger.info("开始上传封面");
21036
+ await retryAction(async ()=>{
21037
+ const coverUploadBtn = await waitForElement(".cover-upload-btn", 10000);
21038
+ if (coverUploadBtn) {
21039
+ const coverInput = page.locator('.cover-upload-btn input[type="file"]');
21040
+ await coverInput.setInputFiles(params.coverPath);
21041
+ task.logger.info("封面上传成功");
21042
+ await page.waitForTimeout(2000);
21043
+ }
21044
+ });
21045
+ }
21046
+ const descriptionText = payload_buildDescription({
21047
+ description: params.description,
21048
+ topics: params.topics,
21049
+ mentionedUsers: params.mentionedUsers
21050
+ });
21051
+ if (descriptionText) {
21052
+ task.logger.info("填写视频描述");
21053
+ await retryAction(async ()=>{
21054
+ const descEditor = await waitForElement(".input-editor", 10000);
21055
+ if (!descEditor) throw new Error("未找到描述编辑器");
21056
+ await descEditor.click();
21057
+ await page.waitForTimeout(500);
21058
+ await descEditor.evaluate((el)=>{
21059
+ el.textContent = "";
21060
+ });
21061
+ await page.waitForTimeout(300);
21062
+ task.logger.info("已清空编辑器内容");
21063
+ await descEditor.pressSequentially(descriptionText, {
21064
+ delay: 10
21065
+ });
21066
+ await page.waitForTimeout(500);
21067
+ task.logger.info("描述填写完成");
21068
+ });
21069
+ }
21070
+ if (params.title) {
21071
+ task.logger.info(`填写标题: ${params.title}`);
21072
+ const title = params.title;
21073
+ await retryAction(async ()=>{
21074
+ const titleInput = await waitForElement("#container-wrap div.form-item-body.short-title-wrap input", 10000);
21075
+ if (!titleInput) throw new Error("未找到标题输入框");
21076
+ await titleInput.click();
21077
+ await titleInput.clear({
21078
+ timeout: 3000
21079
+ });
21080
+ await titleInput.fill(title, {
21081
+ timeout: 5000
21082
+ });
21083
+ task.logger.info("标题填写完成");
21084
+ });
21085
+ }
21086
+ if (params.location) {
21087
+ task.logger.info(`选择地点: ${params.location.city}`);
21088
+ const instance = page.locator(".position-display-wrap");
21089
+ await instance.click();
21090
+ await page.waitForTimeout(1000);
21091
+ await page.locator(".location-filter-wrap input").fill(params.location.city);
21092
+ await page.waitForTimeout(2000);
21093
+ const poperInstance = page.locator(".location-filter-wrap .common-option-list-wrap .option-item");
21094
+ await poperInstance.nth(1).waitFor();
21095
+ await poperInstance.nth(1).click();
21096
+ task.logger.info("地点选择完成");
21097
+ }
21098
+ if (params.collection) {
21099
+ task.logger.info(`选择合集: ${params.collection.collectionName}`);
21100
+ const instanceCollection = page.locator(".post-album-display-wrap");
21101
+ await instanceCollection.click();
21102
+ await page.waitForTimeout(1000);
21103
+ page.locator(".post-album-wrap .option-item").filter({
21104
+ hasText: params.collection.collectionName
21105
+ }).first().click({
21106
+ force: true
21107
+ });
21108
+ }
21109
+ if (params.link) {
21110
+ task.logger.info(`设置扩展阅读链接: ${params.link.title}`);
21111
+ await page.locator(".post-link-wrap .link-display-wrap").click();
21112
+ await page.waitForTimeout(300);
21113
+ const linkTypeText = 2 === params.link.urlType ? "红包封面" : "公众号文章";
21114
+ await page.locator(".link-option-item .title-wrap span").filter({
21115
+ hasText: linkTypeText
21116
+ }).click();
21117
+ await page.waitForTimeout(300);
21118
+ const placeholder = 2 === params.link.urlType ? "粘贴红包封面链接" : "粘贴公众号文章链接";
21119
+ await page.locator(`.link-input-wrap input[placeholder="${placeholder}"]`).fill(params.link.link);
21120
+ await page.waitForTimeout(500);
21121
+ task.logger.info(`已设置${linkTypeText}: ${params.link.link}`);
21122
+ }
21123
+ if (params.event) {
21124
+ task.logger.info(`选择活动: ${params.event.eventName}`);
21125
+ await page.locator(".post-activity-wrap .activity-display").click();
21126
+ await page.waitForTimeout(500);
21127
+ await page.locator(".activity-filter-wrap .weui-desktop-form__input[placeholder='搜索活动']").fill(params.event.eventName);
21128
+ await page.waitForTimeout(500);
21129
+ const searchLoading = page.locator(".search-loading");
21130
+ await searchLoading.waitFor({
21131
+ state: "hidden",
21132
+ timeout: 5000
21133
+ }).catch(()=>{
21134
+ task.logger.warn("活动搜索加载超时,继续尝试选择");
21135
+ });
21136
+ const activityItem = page.locator(".option-item .activity-item .activity-item-info .name").filter({
21137
+ hasText: params.event.eventName
21138
+ });
21139
+ const count = await activityItem.count();
21140
+ if (count > 0) {
21141
+ await activityItem.first().click();
21142
+ await page.waitForTimeout(300);
21143
+ task.logger.info(`已选择活动: ${params.event.eventName}`);
21144
+ } else {
21145
+ task.logger.warn(`未找到活动: ${params.event.eventName},将不参与活动`);
21146
+ await page.locator(".post-activity-wrap .activity-display").click();
21147
+ await page.waitForTimeout(300);
21148
+ }
21149
+ }
21150
+ if (params.scheduledTime) {
21151
+ task.logger.info("设置定时发布");
21152
+ const timingRadio = page.locator(".weui-desktop-form__check-label").filter({
21153
+ hasNotText: "不定时"
21154
+ }).first();
21155
+ await timingRadio.click();
21156
+ await page.waitForTimeout(500);
21157
+ const instance = page.locator(".weui-desktop-picker__date");
21158
+ await instance.click();
21159
+ const dateD = utils_TimeFormatter.format(1000 * params.scheduledTime, "d");
21160
+ const nowMonth = utils_TimeFormatter.format(Date.now(), "MM月");
21161
+ const nowMonthText = utils_TimeFormatter.format(Date.now(), "M月");
21162
+ const month = utils_TimeFormatter.format(1000 * params.scheduledTime, "MM月");
21163
+ const monthLocator = await page.locator("weui-desktop-picker__panel__label").filter({
21164
+ hasText: month
21165
+ }).first();
21166
+ if (!monthLocator) {
21167
+ await page.locator(".weui-desktop-picker__panel__label").filter({
21168
+ hasText: nowMonth
21169
+ }).first().click();
21170
+ await page.waitForTimeout(500);
21171
+ await page.locator(".weui-desktop-picker__table-row td a").filter({
21172
+ hasText: nowMonthText
21173
+ }).first().click();
21174
+ }
21175
+ await page.waitForTimeout(500);
21176
+ await page.locator(".weui-desktop-picker__table-row td a").filter({
21177
+ hasText: dateD
21178
+ }).first().click();
21179
+ await page.locator(".weui-desktop-form__input-wrp input[placeholder*='请选择时间']").fill(utils_TimeFormatter.format(1000 * params.scheduledTime, "hh:mm"));
21180
+ await page.locator("i.weui-desktop-icon__time").click();
21181
+ await page.locator(".post-time-wrap .form-item .label").filter({
21182
+ hasText: "发表时间"
21183
+ }).click();
21184
+ }
21185
+ if (params.tagInfo) {
21186
+ task.logger.info(`设置视频标注: tagType=${params.tagInfo.tagType}`);
21187
+ await page.locator(".mark-tag-select").click();
21188
+ await page.waitForTimeout(300);
21189
+ const tagTypeTextMap = {
21190
+ 0: "无需标注",
21191
+ 1: "含AI生成内容",
21192
+ 2: "内容包含营销广告",
21193
+ 3: "内容为虚构剧情,仅供娱乐",
21194
+ 5: "内容为自行拍摄",
21195
+ 7: "内容为转载",
21196
+ 8: "个人观点,仅供参考"
21197
+ };
21198
+ const tagText = tagTypeTextMap[params.tagInfo.tagType];
21199
+ if (tagText) {
21200
+ await page.locator(".mark-tag-option .option-main").filter({
21201
+ hasText: tagText
21202
+ }).click();
21203
+ await page.waitForTimeout(300);
21204
+ if (5 === params.tagInfo.tagType) {
21205
+ const shootInfo = params.tagInfo.shootInfo;
21206
+ if (shootInfo) {
21207
+ task.logger.info("填写拍摄时间和地点...");
21208
+ await page.waitForTimeout(500);
21209
+ if (shootInfo.postTimestamp) {
21210
+ task.logger.info(`设置拍摄时间: ${shootInfo.postTimestamp}`);
21211
+ const timestamp = 1000 * parseInt(shootInfo.postTimestamp, 10);
21212
+ const date = new Date(timestamp);
21213
+ await page.locator(".original-dialog-content .weui-desktop-picker__date input[placeholder*='请选择拍摄时间']").click();
21214
+ await page.waitForTimeout(300);
21215
+ const dayNum = date.getDate();
21216
+ await page.locator(".weui-desktop-picker__table a").filter({
21217
+ hasText: new RegExp(`^\\s*${dayNum}\\s*$`)
21218
+ }).first().click();
21219
+ await page.waitForTimeout(300);
21220
+ }
21221
+ if (shootInfo.countryCode || shootInfo.provinceCode || shootInfo.cityCode) {
21222
+ task.logger.info("设置拍摄地点...");
21223
+ await page.locator(".original-dialog-content .weui-desktop-form__dropdowncascade .weui-desktop-form__dropdowncascade__dt").click();
21224
+ await page.waitForTimeout(300);
21225
+ if (1156 === shootInfo.countryCode) {
21226
+ await page.locator(".weui-desktop-dropdown__list-ele .weui-desktop-dropdown__list-ele__text").filter({
21227
+ hasText: "中国"
21228
+ }).click();
21229
+ await page.waitForTimeout(300);
21230
+ task.logger.warn("RPA 模式下暂不支持选择具体省份和城市,仅选择了国家");
21231
+ } else task.logger.warn(`不支持的国家代码: ${shootInfo.countryCode},跳过地点设置`);
21232
+ }
21233
+ const confirmBtn = await waitForElement(".weui-desktop-dialog .weui-desktop-btn_primary");
21234
+ if (confirmBtn) {
21235
+ await confirmBtn.click();
21236
+ await page.waitForTimeout(300);
21237
+ }
21238
+ } else task.logger.warn("tagType=5 需要提供 shootInfo 字段(拍摄时间和地点)");
21239
+ }
21240
+ if (7 === params.tagInfo.tagType) {
21241
+ const repostSource = params.tagInfo.repostSource;
21242
+ if (repostSource) {
21243
+ task.logger.info(`填写转载来源: ${repostSource}`);
21244
+ await page.waitForTimeout(500);
21245
+ await page.locator(".repost-dialog-content .repost-textarea").fill(repostSource);
21246
+ await page.waitForTimeout(300);
21247
+ const confirmBtn = await waitForElement(".weui-desktop-dialog .weui-desktop-btn_primary");
21248
+ if (confirmBtn) {
21249
+ await confirmBtn.click();
21250
+ await page.waitForTimeout(300);
21251
+ }
21252
+ } else task.logger.warn("tagType=7 需要提供 repostSource 字段(转载来源)");
21253
+ }
21254
+ } else task.logger.warn(`未知的 tagType: ${params.tagInfo.tagType},跳过标注设置`);
21255
+ }
21256
+ task.logger.info("准备发布...");
21257
+ await page.waitForTimeout(500);
21258
+ let videoId = "";
21259
+ const handleResponse = async (response)=>{
21260
+ const url = response.url();
21261
+ if (url.includes("/post/post_create")) {
21262
+ const jsonResponse = await response.json();
21263
+ page.off("response", handleResponse);
21264
+ videoId = jsonResponse.object?.id || jsonResponse.data?.objectId || "";
21265
+ }
21266
+ };
21267
+ page.on("response", handleResponse);
21268
+ task._timerRecord.PrePublish = Date.now();
21269
+ 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";
21270
+ task.logger.info("等待视频上传完成(预览区媒体操作栏出现)...");
21271
+ const uploadTimeout = 600000;
21272
+ const uploadWaitStart = Date.now();
21273
+ let lastProgressLog = 0;
21274
+ while(true){
21275
+ const ready = await page.evaluate((selector)=>{
21276
+ const host = document.querySelector("#container-wrap > div.container-center > div > wujie-app");
21277
+ const root = host?.shadowRoot;
21278
+ if (!root) return false;
21279
+ return !!root.querySelector(selector);
21280
+ }, MEDIA_OPR_SELECTOR);
21281
+ if (ready) break;
21282
+ const elapsed = Date.now() - uploadWaitStart;
21283
+ if (elapsed > uploadTimeout) throw new Error(`视频上传超时,预览区未就绪(已等待 ${Math.round(elapsed / 1000)}s)`);
21284
+ if (elapsed - lastProgressLog >= 15000) {
21285
+ lastProgressLog = elapsed;
21286
+ task.logger.info(`视频仍在上传中... 已等待 ${Math.round(elapsed / 1000)}s`);
21287
+ }
21288
+ await page.waitForTimeout(1000);
21289
+ }
21290
+ task.logger.info(`视频上传完成(等待 ${Math.round((Date.now() - uploadWaitStart) / 1000)}s)`);
21291
+ const clicked = await page.evaluate(()=>{
21292
+ const host = document.querySelector("#container-wrap > div.container-center > div > wujie-app");
21293
+ const root = host?.shadowRoot;
21294
+ if (!root) return "未找到 wujie-app shadowRoot";
21295
+ const btns = Array.from(root.querySelectorAll(".form-btns .weui-desktop-btn"));
21296
+ const target = btns.find((el)=>(el.textContent || "").includes("发表"));
21297
+ if (!target) return "未找到发表按钮";
21298
+ if (target.classList.contains("weui-desktop-btn_disabled")) return "发表按钮仍处于禁用状态";
21299
+ target.click();
21300
+ return null;
21301
+ });
21302
+ if (clicked) throw new Error(clicked);
21303
+ task.logger.info("已点击发布按钮,等待响应...");
21304
+ try {
21305
+ await page.waitForURL((url)=>url.href !== page.url(), {
21306
+ timeout: 30000
21307
+ });
21308
+ task.logger.info(`发布成功,页面已跳转: ${page.url()}`);
21309
+ } catch {
21310
+ task.logger.warn("等待页面跳转超时,可能发布失败或网络慢,继续关闭页面");
21311
+ }
21312
+ await page.close();
21313
+ return (0, share_namespaceObject.success)(videoId, "发布成功");
21314
+ } catch (error) {
21315
+ let errorMsg = error instanceof Error ? error.message : String(error);
21316
+ if (errorMsg.includes("context or browser has been closed")) errorMsg = "浏览器上下文已被关闭";
21317
+ task.logger.error(`微信视频号视频发布失败: ${errorMsg}`);
21318
+ return (0, share_namespaceObject.response)(414, `微信视频号视频发布失败: ${errorMsg}`, "");
21319
+ }
21320
+ };
21321
+ const ShipinhaoPublishVideoParamsSchema = ActionCommonParamsSchema.extend({
21322
+ videoPath: schemas_string().min(1),
21323
+ videoMetadata: schemas_object({
21324
+ duration: schemas_number().positive(),
21325
+ width: schemas_number().int().positive(),
21326
+ height: schemas_number().int().positive(),
21327
+ fileSize: schemas_number().int().positive(),
21328
+ path: schemas_string().min(1).optional(),
21329
+ fileName: schemas_string().min(1)
21330
+ }),
21331
+ coverPath: schemas_string().min(1),
21332
+ verticalCoverPath: schemas_string().min(1).optional(),
21333
+ description: schemas_string(),
21334
+ title: schemas_string().optional(),
21335
+ scheduledTime: schemas_number().int().positive().optional(),
21336
+ isImmediatelyPublish: schemas_boolean().optional(),
21337
+ topics: schemas_array(schemas_string()).optional(),
21338
+ mentionedUsers: schemas_array(schemas_object({
21339
+ nickname: schemas_string()
21340
+ })).optional(),
21341
+ collection: schemas_object({
21342
+ collectionId: schemas_string(),
21343
+ collectionName: schemas_string()
21344
+ }).optional(),
21345
+ event: schemas_object({
21346
+ eventTopicId: schemas_string(),
21347
+ eventName: schemas_string(),
21348
+ eventCreatorNickname: schemas_string().optional()
21349
+ }).optional(),
21350
+ link: schemas_object({
21351
+ link: schemas_string(),
21352
+ title: schemas_string(),
21353
+ urlType: schemas_number().int().default(1)
21354
+ }).optional(),
21355
+ tagInfo: looseObject({
21356
+ tagType: schemas_number().int()
21357
+ }).optional(),
21358
+ originalFlag: union([
21359
+ literal(0),
21360
+ literal(1)
21361
+ ]).optional(),
21362
+ postWithMemberZoneLink: union([
21363
+ literal(0),
21364
+ literal(1)
21365
+ ]).optional(),
21366
+ location: schemas_object({
21367
+ latitude: schemas_number(),
21368
+ longitude: schemas_number(),
21369
+ city: schemas_string(),
21370
+ poiName: schemas_string().optional(),
21371
+ address: schemas_string().optional(),
21372
+ poiClassifyId: schemas_string().optional()
21373
+ }).optional()
21374
+ });
21375
+ const shipinhaoPublishVideo = async (task, params)=>{
21376
+ task.logger.info(`[shipinhaoPublishVideo] actionType: ${params.actionType}`);
21377
+ if ("rpa" === params.actionType) return shipinhaoPublishVideo_rpa_rpaAction(task, params);
21378
+ if ("mockApi" === params.actionType) return shipinhaoPublishVideo_mock_mockAction(task, params);
21379
+ return executeAction(shipinhaoPublishVideo_mock_mockAction, shipinhaoPublishVideo_rpa_rpaAction)(task, params);
21380
+ };
21381
+ const ShipinhaoSendMsgParamsSchema = ActionCommonParamsSchema.extend({
21382
+ toUsername: schemas_string().min(1, "接收者用户名不能为空"),
21383
+ sessionId: schemas_string().min(1, "会话ID不能为空"),
21384
+ msgType: schemas_enum([
21385
+ "TEXT",
21386
+ "IMAGE"
21387
+ ], {
21388
+ message: "消息类型必须是 TEXT 或 IMAGE"
21389
+ }),
21390
+ content: schemas_string().optional(),
21391
+ imageInfo: schemas_object({
21392
+ pathOrUrl: schemas_string().min(1, "图片路径或URL不能为空")
21393
+ }).optional()
21394
+ });
21395
+ const shipinhaoSendMsg_CHUNK_SIZE = 524288;
21396
+ async function shipinhaoSendMsg_getUserInfo(cookieStr, http) {
21397
+ const url = `https://channels.weixin.qq.com/cgi-bin/mmfinderassistant-bin/auth/auth_data?_rid=${rid()}`;
21398
+ const headers = {
21399
+ referer: "https://channels.weixin.qq.com/micro/interaction/private_msg",
21400
+ cookie: cookieStr,
21401
+ Origin: "https://channels.weixin.qq.com"
21402
+ };
21403
+ return await http.api({
21404
+ method: "get",
21405
+ url,
21406
+ headers
21407
+ }, {
21408
+ retries: 3,
21409
+ retryDelay: 1000,
21410
+ timeout: 10000
21411
+ });
21412
+ }
21413
+ const shipinhaoSendMsg = async (_task, params)=>{
21414
+ if (!params.sessionId) return (0, share_namespaceObject.response)(414, "sessionId 不能为空", void 0);
21415
+ if (!params.toUsername) return (0, share_namespaceObject.response)(414, "接收者用户名不能为空", void 0);
21416
+ if (!params.msgType) return (0, share_namespaceObject.response)(414, "消息类型不能为空", void 0);
21417
+ if (![
21418
+ "TEXT",
21419
+ "IMAGE"
21420
+ ].includes(params.msgType)) return (0, share_namespaceObject.response)(414, "消息类型必须是 TEXT 或 IMAGE", void 0);
21421
+ if ("TEXT" === params.msgType) {
21422
+ if (!params.content || "" === params.content.trim()) return (0, share_namespaceObject.response)(414, "消息内容不能为空", void 0);
21423
+ }
21424
+ if ("IMAGE" === params.msgType) {
21425
+ if (!params.imageInfo?.pathOrUrl) return (0, share_namespaceObject.response)(414, "图片路径或URL不能为空", void 0);
21426
+ }
21427
+ if (!params.extraParam) return (0, share_namespaceObject.response)(414, "缺少 extraParam 参数", void 0);
21428
+ if (!params.extraParam.fingerPrintDeviceId || !params.extraParam.aId || !params.extraParam.uin) return (0, share_namespaceObject.response)(414, "fingerPrintDeviceId、aId 和 uin 不能为空", void 0);
21429
+ const cookieStr = params.cookies.map((it)=>`${it.name}=${it.value}`).join(";");
21430
+ const headers = {
21431
+ cookie: cookieStr,
21432
+ referer: "https://channels.weixin.qq.com/micro/interaction/private_msg",
21433
+ origin: "https://channels.weixin.qq.com",
21434
+ "content-type": "application/json",
21435
+ "finger-print-device-id": params.extraParam.fingerPrintDeviceId,
21436
+ "x-wechat-uin": params.extraParam.uin
21437
+ };
21438
+ const http = new Http({
21439
+ headers
21440
+ });
21441
+ const urlParams = new URLSearchParams({
21442
+ _aid: params.extraParam.aId,
21443
+ _rid: rid(),
21444
+ _pageUrl: "https://channels.weixin.qq.com/micro/interaction/private_msg"
21445
+ }).toString();
21446
+ const generateCliMsgId = ()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (s)=>{
21447
+ const t = 16 * Math.random() | 0;
21448
+ return ("x" === s ? t : 3 & t | 8).toString(16);
21449
+ });
21450
+ let fromUsername = params.extraParam.finderUserName;
21451
+ if (!fromUsername) {
21452
+ _task.logger.info("未提供 finderUserName,尝试获取用户信息");
21453
+ const userInfoRes = await shipinhaoSendMsg_getUserInfo(cookieStr, http);
21454
+ if (!userInfoRes.data?.finderUser?.finderUsername) return (0, share_namespaceObject.response)(userInfoRes.errCode || -1, userInfoRes.errMsg || "获取用户信息失败", {});
21455
+ fromUsername = userInfoRes.data.finderUser.finderUsername;
21456
+ _task.logger.info(`获取到用户名: ${fromUsername}`);
21457
+ }
21458
+ let imgMsg;
21459
+ if ("IMAGE" === params.msgType) {
21460
+ let imageBuffer;
21461
+ const imagePath = params.imageInfo.pathOrUrl;
21462
+ try {
21463
+ if (imagePath.startsWith("http://") || imagePath.startsWith("https://")) {
21464
+ const resp = await external_axios_default().get(imagePath, {
21465
+ responseType: "arraybuffer"
21466
+ });
21467
+ imageBuffer = Buffer.from(resp.data);
21468
+ } else {
21469
+ const filePath = imagePath.startsWith("file://") ? imagePath.slice(7) : imagePath;
21470
+ imageBuffer = Buffer.from(await external_node_fs_default().promises.readFile(filePath));
21471
+ }
21472
+ } catch (err) {
21473
+ _task.logger.error(`读取图片失败: ${err instanceof Error ? err.message : String(err)}`);
21474
+ return (0, share_namespaceObject.response)(414, USER_MESSAGE.IMAGE_UPLOAD_FAILED, void 0);
21475
+ }
21476
+ const md5 = (0, external_node_crypto_namespaceObject.createHash)("md5").update(imageBuffer).digest("hex");
19614
21477
  const timestamp = Date.now().toString();
19615
- const totalChunks = Math.ceil(imageBuffer.length / CHUNK_SIZE);
21478
+ const totalChunks = Math.ceil(imageBuffer.length / shipinhaoSendMsg_CHUNK_SIZE);
19616
21479
  console.log(`分片上传md5${md5}`);
19617
21480
  let lastRes;
19618
21481
  for(let i = 0; i < totalChunks; i++){
19619
- const chunkBuffer = imageBuffer.slice(i * CHUNK_SIZE, (i + 1) * CHUNK_SIZE);
21482
+ const chunkBuffer = imageBuffer.slice(i * shipinhaoSendMsg_CHUNK_SIZE, (i + 1) * shipinhaoSendMsg_CHUNK_SIZE);
19620
21483
  const requestData = {
19621
21484
  content: `data:application/octet-stream;base64,${chunkBuffer.toString("base64")}`,
19622
21485
  chunk: i,
@@ -20069,6 +21932,13 @@ var __webpack_exports__ = {};
20069
21932
  const uploadImages = async (images)=>await Promise.all(images.map(async (url)=>{
20070
21933
  const fileName = (0, share_namespaceObject.getFilenameFromUrl)(url);
20071
21934
  const image = await (0, share_namespaceObject.downloadImage)(url, external_node_path_default().join(tmpCachePath, fileName));
21935
+ const stats = external_node_fs_default().statSync(image);
21936
+ const maxSize = 20971520;
21937
+ if (stats.size > maxSize) throw {
21938
+ code: 414,
21939
+ message: "头条号平台:单张图片不得超过 20MB",
21940
+ data: ""
21941
+ };
20072
21942
  const formData = new (external_form_data_default())();
20073
21943
  formData.append("image", external_node_fs_default().createReadStream(image));
20074
21944
  const response = await http.api({
@@ -22119,18 +23989,10 @@ var __webpack_exports__ = {};
22119
23989
  });
22120
23990
  } catch (error) {
22121
23991
  const handledError = Http.handleApiError(error);
22122
- const isProxyOrNetworkError = [
22123
- 599,
22124
- 500,
22125
- 502,
22126
- 503,
22127
- 504
22128
- ].includes(handledError.code);
22129
- if (isProxyOrNetworkError) {
22130
- const isProxyRequest = handledError.extra?.isProxyRequest === true;
22131
- const errorType = 599 === handledError.code || isProxyRequest ? "代理错误" : "网络错误";
22132
- const message = `文章发布失败,${errorType}:${handledError.message}${task.debug ? ` ${http.proxyInfo}` : ""}`;
22133
- task.logger.error(`[weixinPublish] ${errorType},直接返回: ${message}`, stringifyError(handledError));
23992
+ const classified = classifyPublishError(handledError);
23993
+ if (classified) {
23994
+ const message = `${classified.userMessage}${task.debug ? ` ${http.proxyInfo}` : ""}`;
23995
+ task.logger.error(`[weixinPublish] ${classified.category},直接返回: ${handledError.message} (code=${handledError.code})`, stringifyError(handledError));
22134
23996
  await updateTaskState?.({
22135
23997
  state: share_namespaceObject.TaskState.FAILED,
22136
23998
  error: message
@@ -23360,6 +25222,12 @@ var __webpack_exports__ = {};
23360
25222
  const fileName = (0, share_namespaceObject.getFilenameFromUrl)(url);
23361
25223
  const localUrl = await (0, share_namespaceObject.downloadImage)(url, external_node_path_default().join(tmpCachePath, fileName));
23362
25224
  const fileBuffer = external_node_fs_default().readFileSync(localUrl);
25225
+ const maxSize = 33554432;
25226
+ if (fileBuffer.byteLength > maxSize) throw {
25227
+ code: 414,
25228
+ message: "小红书平台:单张图片不得超过 32MB",
25229
+ data: ""
25230
+ };
23363
25231
  let width = 0;
23364
25232
  let height = 0;
23365
25233
  try {
@@ -23598,6 +25466,7 @@ var __webpack_exports__ = {};
23598
25466
  });
23599
25467
  return (0, share_namespaceObject.success)(data, message);
23600
25468
  }
25469
+ task.logger.info(`[xiaohongshuPublish] publishData: ${JSON.stringify(publishData)} `);
23601
25470
  let publishResult;
23602
25471
  try {
23603
25472
  publishResult = await proxyHttp.api({
@@ -23608,23 +25477,15 @@ var __webpack_exports__ = {};
23608
25477
  defaultErrorMsg: "文章发布异常,请稍后重试。"
23609
25478
  }, {
23610
25479
  retries: 2,
23611
- retryDelay: 500,
23612
- timeout: 12000
25480
+ retryDelay: 3000,
25481
+ timeout: 30000
23613
25482
  });
23614
25483
  } catch (error) {
23615
25484
  const handledError = Http.handleApiError(error);
23616
- const isProxyOrNetworkError = [
23617
- 599,
23618
- 500,
23619
- 502,
23620
- 503,
23621
- 504
23622
- ].includes(handledError.code);
23623
- if (isProxyOrNetworkError) {
23624
- const isProxyRequest = handledError.extra?.isProxyRequest === true;
23625
- const errorType = 599 === handledError.code || isProxyRequest ? "代理错误" : "网络错误";
23626
- const message = `文章发布失败,${errorType}:${handledError.message}${task.debug ? ` ${http.proxyInfo}` : ""}`;
23627
- task.logger.error(`[xiaohongshuPublish] ${errorType},直接返回: ${message}`, stringifyError(handledError));
25485
+ const classified = classifyPublishError(handledError);
25486
+ if (classified) {
25487
+ const message = `${classified.userMessage}${task.debug ? ` ${http.proxyInfo}` : ""}`;
25488
+ task.logger.error(`[xiaohongshuPublish] ${classified.category},直接返回: ${handledError.message} (code=${handledError.code})`, stringifyError(handledError));
23628
25489
  await updateTaskState?.({
23629
25490
  state: share_namespaceObject.TaskState.FAILED,
23630
25491
  error: message
@@ -25320,6 +27181,14 @@ var __webpack_exports__ = {};
25320
27181
  this.task = task;
25321
27182
  this.task.logger.info(`当前包版本:Share=>${package_json_default().version} Action=>${package_namespaceObject.i8}`);
25322
27183
  }
27184
+ getActionVersionMarker() {
27185
+ return {
27186
+ version: package_namespaceObject.i8,
27187
+ shareVersion: package_json_default().version,
27188
+ marker: `Action_${package_namespaceObject.i8}_${package_json_default().version}`,
27189
+ timestamp: new Date().toLocaleString()
27190
+ };
27191
+ }
25323
27192
  async bindTask(func, params) {
25324
27193
  let responseData;
25325
27194
  this.task.isBeta = this.task?.isFeatOn ? this.task?.isFeatOn(BetaFlag) : false;
@@ -25543,6 +27412,9 @@ var __webpack_exports__ = {};
25543
27412
  shipinhaoPublish(params) {
25544
27413
  return this.bindTask(shipinhaoPublish, params);
25545
27414
  }
27415
+ shipinhaoPublishVideo(params) {
27416
+ return this.bindTask(shipinhaoPublishVideo, params);
27417
+ }
25546
27418
  douyinGetTopics(params) {
25547
27419
  return this.bindTask(douyinGetTopics, params);
25548
27420
  }
@@ -25603,4 +27475,4 @@ if (__webpack_exports__.__esModule) Object.defineProperty(__webpack_export_targe
25603
27475
  });
25604
27476
 
25605
27477
  //# sourceMappingURL=index.js.map
25606
- //# debugId=4505f4f9-b586-5fae-8a9f-3ce0ceb72967
27478
+ //# debugId=4653233b-4a56-52c6-8a3b-2a28934c66cb