@iflyrpa/actions 4.0.9 → 4.1.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/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]="8315ee33-ea9b-5a8e-92af-cf3835f6ed70")}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.1"}');
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,130 @@ 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 THROTTLE_MAP_MAX_KEYS = 500;
4456
+ const pruneThrottleMap = (now)=>{
4457
+ if (lastSentAt.size < THROTTLE_MAP_MAX_KEYS) return;
4458
+ for (const [key, at] of lastSentAt)if (now - at >= ALARM_THROTTLE_MS) lastSentAt.delete(key);
4459
+ };
4460
+ const postFeishuWebhook = (webhookUrl, payload)=>external_axios_default().post(webhookUrl, payload, {
4461
+ headers: {
4462
+ "Content-Type": "application/json"
4463
+ },
4464
+ timeout: 10000
4465
+ });
4466
+ const buildFeishuPostMessage = (report)=>{
4467
+ const content = [
4468
+ [
4469
+ {
4470
+ tag: "text",
4471
+ text: `平台:${report.platform || "未知平台"}`
4472
+ }
4473
+ ],
4474
+ [
4475
+ {
4476
+ tag: "text",
4477
+ text: `错误信息:${report.msg || "未知错误信息"}`
4478
+ }
4479
+ ],
4480
+ [
4481
+ {
4482
+ tag: "text",
4483
+ text: `错误类型:${report.errorType || "未知错误类型"}`
4484
+ }
4485
+ ],
4486
+ [
4487
+ {
4488
+ tag: "text",
4489
+ text: `阶段:${report.stage || "未知阶段"}`
4490
+ }
4491
+ ],
4492
+ [
4493
+ {
4494
+ tag: "text",
4495
+ text: `等级:${report.level}`
4496
+ }
4497
+ ],
4498
+ [
4499
+ {
4500
+ tag: "text",
4501
+ text: `来源:${report.source}`
4502
+ }
4503
+ ]
4504
+ ];
4505
+ if (void 0 !== report.code && null !== report.code) content.push([
4506
+ {
4507
+ tag: "text",
4508
+ text: `接口错误码:${report.code}`
4509
+ }
4510
+ ]);
4511
+ if (report.url) content.push([
4512
+ {
4513
+ tag: "text",
4514
+ text: `地址:${report.url}`
4515
+ }
4516
+ ]);
4517
+ if ("alarm" === report.level) content.push([
4518
+ {
4519
+ tag: "at",
4520
+ user_id: "all"
4521
+ }
4522
+ ]);
4523
+ return {
4524
+ msg_type: "post",
4525
+ content: {
4526
+ post: {
4527
+ zh_cn: {
4528
+ title: report.title || "RPA异常",
4529
+ content
4530
+ }
4531
+ }
4532
+ }
4533
+ };
4534
+ };
4535
+ const reportFeishuAlarm = (report)=>{
4536
+ try {
4537
+ const key = `${report.platform}|${report.source}|${report.stage}|${report.errorType}|${report.code ?? ""}`;
4538
+ const now = Date.now();
4539
+ const last = lastSentAt.get(key);
4540
+ if (last && now - last < ALARM_THROTTLE_MS) return;
4541
+ pruneThrottleMap(now);
4542
+ lastSentAt.set(key, now);
4543
+ postFeishuWebhook(RPA_ERROR_WEBHOOK_URL, buildFeishuPostMessage(report)).catch(()=>{});
4544
+ } catch {}
4545
+ };
4423
4546
  const external_socks_proxy_agent_namespaceObject = require("socks-proxy-agent");
4424
4547
  const PROXY_CREDENTIALS = [
4425
4548
  {
@@ -4522,9 +4645,20 @@ var __webpack_exports__ = {};
4522
4645
  url: "https://fetdev.iflysec.com/ip-pool/pool/eip/proxy",
4523
4646
  data: params
4524
4647
  }).catch((err)=>{
4648
+ reportFeishuAlarm({
4649
+ level: "alarm",
4650
+ platform: "ip-pool",
4651
+ source: "proxy",
4652
+ stage: "POST /ip-pool/pool/eip/proxy",
4653
+ errorType: "PROXY_REQUEST_FAILED",
4654
+ code: err?.code,
4655
+ msg: `请求代理失败:${err.message},区域:${addr ?? "-"},AccountId:${accountId ?? "-"}`,
4656
+ url: "https://fetdev.iflysec.com/ip-pool/pool/eip/proxy",
4657
+ title: "代理异常"
4658
+ });
4525
4659
  throw {
4526
4660
  code: 414,
4527
- message: `请求代理失败:${err.message}`,
4661
+ message: USER_MESSAGE.PROXY_UNAVAILABLE,
4528
4662
  data: {}
4529
4663
  };
4530
4664
  });
@@ -4544,12 +4678,53 @@ var __webpack_exports__ = {};
4544
4678
  } : null;
4545
4679
  return proxyAgent;
4546
4680
  }
4681
+ const ALARM_STATUS = new Set([
4682
+ 401,
4683
+ 403,
4684
+ 429,
4685
+ 461,
4686
+ 471
4687
+ ]);
4688
+ const HTTP_STATUS_MESSAGE = {
4689
+ 400: "请求参数错误,请检查参数格式是否正确!",
4690
+ 401: "登录状态已失效,请重新登录后重试!",
4691
+ 403: "没有访问权限,账号可能受限或签名已失效!",
4692
+ 404: "请求的资源不存在,请检查接口地址!",
4693
+ 405: "请求方法不被允许,请检查接口调用方式!",
4694
+ 406: "服务端无法返回可接受的内容格式!",
4695
+ 407: "代理需要身份验证,请检查代理配置!",
4696
+ 408: "请求超时,请检查网络连接!",
4697
+ 409: "请求冲突,资源状态已变更,请刷新后重试!",
4698
+ 410: "请求的资源已被移除!",
4699
+ 412: "请求前置条件不满足,请刷新后重试!",
4700
+ 413: "提交内容过大,请压缩或分批后重试!",
4701
+ 414: "请求地址过长,请检查参数!",
4702
+ 415: "不支持的内容类型,请检查请求格式!",
4703
+ 422: "请求内容校验失败,请检查参数内容!",
4704
+ 423: "资源已被锁定,请稍后重试!",
4705
+ 429: "请求过于频繁,请稍后重试!",
4706
+ 431: "请求头过大,请清理 Cookie 后重试!",
4707
+ 451: "内容不合规或因法律原因被拒绝!",
4708
+ 461: "账号可能受限,请在网页上完成验证后重试!",
4709
+ 471: "账号可能受限,请在网页上完成验证后重试!",
4710
+ 500: "服务器内部错误,请稍后重试!",
4711
+ 501: "服务端不支持该请求,请稍后重试!",
4712
+ 502: "网关错误,请稍后重试!",
4713
+ 503: "服务暂时不可用,请稍后重试!",
4714
+ 504: "网关超时,请稍后重试!",
4715
+ 507: "服务端存储空间不足,请稍后重试!",
4716
+ 509: "服务带宽超限,请稍后重试!",
4717
+ 520: "服务端返回未知错误,请稍后重试!",
4718
+ 521: "源站拒绝连接,请稍后重试!",
4719
+ 522: "源站连接超时,请稍后重试!",
4720
+ 524: "源站响应超时,请稍后重试!"
4721
+ };
4547
4722
  class Http {
4548
4723
  static handleApiError(error) {
4549
4724
  if (error && "object" == typeof error && "code" in error && "message" in error) return error;
4550
4725
  return {
4551
4726
  code: 500,
4552
- message: error instanceof Error ? error.message : "未知错误",
4727
+ message: USER_MESSAGE.SYSTEM_ERROR,
4553
4728
  data: error
4554
4729
  };
4555
4730
  }
@@ -4604,6 +4779,18 @@ var __webpack_exports__ = {};
4604
4779
  const verifyDecision = error.response?.headers?.["x-tt-verify-passport-decision"];
4605
4780
  if (verifyDecision) this.logger?.warn(`[403 验证决策] x-tt-verify-passport-decision: ${verifyDecision}`);
4606
4781
  }
4782
+ if (error.response?.status === 461 || error.response?.status === 471) {
4783
+ const h = error.response?.headers ?? {};
4784
+ const pick = (name)=>h[name] ?? h[name.toLowerCase()];
4785
+ this.logger?.warn(`[${error.response.status} 风控验证] URL: ${error.config?.url} Verifytype: ${pick("Verifytype") ?? "-"} Verifyuuid: ${pick("Verifyuuid") ?? "-"} Verifybiz: ${pick("Verifybiz") ?? "-"}`);
4786
+ this.logger?.warn(`[${error.response.status} 响应头] ${JSON.stringify(h)}`);
4787
+ errorResponse.extra = {
4788
+ ...errorResponse.extra,
4789
+ verifyType: pick("Verifytype"),
4790
+ verifyUuid: pick("Verifyuuid"),
4791
+ verifyBiz: pick("Verifybiz")
4792
+ };
4793
+ }
4607
4794
  if (error.response?.data) {
4608
4795
  if ("object" == typeof error.response.data) {
4609
4796
  const serverError = error.response.data;
@@ -4634,11 +4821,17 @@ var __webpack_exports__ = {};
4634
4821
  _message = "DNS 查询超时,请稍后重试!";
4635
4822
  break;
4636
4823
  case "ERR_BAD_REQUEST":
4637
- _message = "请求出现错误,请检查请求参数!";
4638
- break;
4824
+ {
4825
+ const status = error.response?.status;
4826
+ _message = status && HTTP_STATUS_MESSAGE[status] || `请求失败,状态码${status ?? "unknown"}!`;
4827
+ break;
4828
+ }
4639
4829
  case "ERR_BAD_RESPONSE":
4640
- _message = `服务器响应异常 (${error.response?.status ?? "unknown"}),请稍后重试!`;
4641
- break;
4830
+ {
4831
+ const status = error.response?.status;
4832
+ _message = status && HTTP_STATUS_MESSAGE[status] || `服务器响应异常 (${status ?? "unknown"}),请稍后重试!`;
4833
+ break;
4834
+ }
4642
4835
  case "ERR_CANCELED":
4643
4836
  errorResponse.code = 414;
4644
4837
  _message = "请求连接超时,请稍候重试!";
@@ -4649,11 +4842,14 @@ var __webpack_exports__ = {};
4649
4842
  }
4650
4843
  break;
4651
4844
  default:
4652
- this.logger?.debug(`未处理的网络错误代码: ${error.code} ${error.message}`, {
4653
- errorString: stringifyError(error)
4654
- });
4655
- _message = `网络错误: ${error.message}`;
4656
- break;
4845
+ {
4846
+ this.logger?.debug(`未处理的网络错误代码: ${error.code} ${error.message}`, {
4847
+ errorString: stringifyError(error)
4848
+ });
4849
+ const status = error.response?.status;
4850
+ _message = status && HTTP_STATUS_MESSAGE[status] || USER_MESSAGE.NETWORK_ERROR;
4851
+ break;
4852
+ }
4657
4853
  }
4658
4854
  }
4659
4855
  if (error.code && !error.response?.data) errorResponse.message = _message || errorResponse.message;
@@ -4663,29 +4859,62 @@ var __webpack_exports__ = {};
4663
4859
  errorResponse.message = message;
4664
4860
  }
4665
4861
  if (error.message.includes("Proxy connection ended")) errorResponse.message = "所在区域代理连接超时,请更换区域或稍后重试!";
4862
+ errorResponse.extra = {
4863
+ ...errorResponse.extra,
4864
+ alarmStatus: error.response?.status,
4865
+ alarmErrorCode: error.code
4866
+ };
4666
4867
  throw errorResponse;
4667
4868
  });
4668
4869
  }
4870
+ reportRequestFailure(config, error, attempts) {
4871
+ const status = error.extra?.alarmStatus;
4872
+ const axiosCode = error.extra?.alarmErrorCode;
4873
+ const method = (config.method || "get").toUpperCase();
4874
+ const url = config.url || "-";
4875
+ const retriedSuffix = attempts > 0 ? `(已重试${attempts}次仍失败)` : "";
4876
+ reportFeishuAlarm({
4877
+ level: status && ALARM_STATUS.has(status) ? "alarm" : "warning",
4878
+ platform: this.platform || "unknown",
4879
+ source: "http",
4880
+ stage: `${method} ${url}`,
4881
+ errorType: status ? `HTTP_${status}` : axiosCode || "NETWORK_ERROR",
4882
+ code: error.code,
4883
+ msg: `${error.message}${retriedSuffix}`,
4884
+ url: config.url,
4885
+ title: "RPA接口异常"
4886
+ });
4887
+ }
4669
4888
  async api(config, options) {
4670
4889
  const retries = options?.retries ?? 0;
4671
4890
  const retryDelay = options?.retryDelay ?? 500;
4672
- const reqTimeout = options?.timeout ?? 30000;
4891
+ const reqTimeout = options?.timeout ?? 60000;
4892
+ const externalSignal = options?.signal;
4673
4893
  let agent;
4674
4894
  const sessionRt = async (Rtimes)=>{
4675
4895
  try {
4676
4896
  this.proxyInfo = agent ? `${agent.ip}:${agent.port}` : void 0;
4677
4897
  const controller = new AbortController();
4678
4898
  const timeoutId = setTimeout(()=>controller.abort(), reqTimeout + 500);
4899
+ const forwardAbort = ()=>controller.abort();
4900
+ if (externalSignal) {
4901
+ if (externalSignal.aborted) controller.abort();
4902
+ else externalSignal.addEventListener("abort", forwardAbort, {
4903
+ once: true
4904
+ });
4905
+ }
4679
4906
  const response = await this.apiClient({
4680
4907
  ...config,
4681
4908
  timeout: reqTimeout,
4682
4909
  signal: controller.signal,
4910
+ onUploadProgress: options?.onUploadProgress,
4683
4911
  ...agent ? {
4684
4912
  httpAgent: agent.agent,
4685
4913
  httpsAgent: agent.agent
4686
4914
  } : {}
4687
4915
  }).finally(()=>{
4688
4916
  clearTimeout(timeoutId);
4917
+ externalSignal?.removeEventListener("abort", forwardAbort);
4689
4918
  });
4690
4919
  return response.data;
4691
4920
  } catch (error) {
@@ -4700,10 +4929,12 @@ var __webpack_exports__ = {};
4700
4929
  ].includes(handledError.code);
4701
4930
  if (Rtimes < retries && isRetry) {
4702
4931
  const url = config.url || "";
4703
- this.logger?.warn(`进入第${Rtimes + 1}次重试!错误码: ${handledError.code}, 请求地址: ${url}`);
4704
- await new Promise((resolve)=>setTimeout(resolve, retryDelay));
4932
+ const backoff = Math.min(retryDelay * 2 ** Rtimes, 5000);
4933
+ this.logger?.warn(`进入第${Rtimes + 1}次重试!错误码: ${handledError.code}, 等待: ${backoff}ms, 请求地址: ${url}`);
4934
+ await new Promise((resolve)=>setTimeout(resolve, backoff));
4705
4935
  return sessionRt(Rtimes + 1);
4706
4936
  }
4937
+ this.reportRequestFailure(config, handledError, Rtimes);
4707
4938
  return Promise.reject(handledError);
4708
4939
  }
4709
4940
  };
@@ -5432,7 +5663,7 @@ var __webpack_exports__ = {};
5432
5663
  Number.MAX_VALUE
5433
5664
  ]
5434
5665
  };
5435
- function pick(schema, mask) {
5666
+ function util_pick(schema, mask) {
5436
5667
  const currDef = schema._zod.def;
5437
5668
  const def = mergeDefs(schema._zod.def, {
5438
5669
  get shape () {
@@ -5802,7 +6033,7 @@ var __webpack_exports__ = {};
5802
6033
  const xid = /^[0-9a-vA-V]{20}$/;
5803
6034
  const ksuid = /^[A-Za-z0-9]{27}$/;
5804
6035
  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)?)?)$/;
6036
+ 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
6037
  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
6038
  const regexes_uuid = (version)=>{
5808
6039
  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 +6719,7 @@ var __webpack_exports__ = {};
6488
6719
  $ZodStringFormat.init(inst, def);
6489
6720
  });
6490
6721
  const $ZodISODuration = /*@__PURE__*/ $constructor("$ZodISODuration", (inst, def)=>{
6491
- def.pattern ?? (def.pattern = duration);
6722
+ def.pattern ?? (def.pattern = regexes_duration);
6492
6723
  $ZodStringFormat.init(inst, def);
6493
6724
  });
6494
6725
  const $ZodIPv4 = /*@__PURE__*/ $constructor("$ZodIPv4", (inst, def)=>{
@@ -8413,7 +8644,7 @@ var __webpack_exports__ = {};
8413
8644
  inst.extend = (incoming)=>extend(inst, incoming);
8414
8645
  inst.safeExtend = (incoming)=>safeExtend(inst, incoming);
8415
8646
  inst.merge = (other)=>merge(inst, other);
8416
- inst.pick = (mask)=>pick(inst, mask);
8647
+ inst.pick = (mask)=>util_pick(inst, mask);
8417
8648
  inst.omit = (mask)=>omit(inst, mask);
8418
8649
  inst.partial = (...args)=>partial(ZodOptional, inst, args[0]);
8419
8650
  inst.required = (...args)=>required(ZodNonOptional, inst, args[0]);
@@ -8426,6 +8657,14 @@ var __webpack_exports__ = {};
8426
8657
  };
8427
8658
  return new ZodObject(def);
8428
8659
  }
8660
+ function looseObject(shape, params) {
8661
+ return new ZodObject({
8662
+ type: "object",
8663
+ shape,
8664
+ catchall: unknown(),
8665
+ ...normalizeParams(params)
8666
+ });
8667
+ }
8429
8668
  const ZodUnion = /*@__PURE__*/ $constructor("ZodUnion", (inst, def)=>{
8430
8669
  $ZodUnion.init(inst, def);
8431
8670
  ZodType.init(inst, def);
@@ -9124,6 +9363,13 @@ var __webpack_exports__ = {};
9124
9363
  data: ""
9125
9364
  };
9126
9365
  const image = await (0, share_namespaceObject.downloadImage)(url, external_node_path_default().join(tmpCachePath, fileName));
9366
+ const stats = external_node_fs_default().statSync(image);
9367
+ const maxSize = 5242880;
9368
+ if (stats.size > maxSize) throw {
9369
+ code: 414,
9370
+ message: "百家号平台:单张图片不得超过 5MB",
9371
+ data: ""
9372
+ };
9127
9373
  const formData = new (external_form_data_default())();
9128
9374
  formData.append("org_file_name", fileName);
9129
9375
  formData.append("type", "image");
@@ -9796,7 +10042,8 @@ var __webpack_exports__ = {};
9796
10042
  },
9797
10043
  _task.logger,
9798
10044
  params.proxyLoc,
9799
- params.accountId
10045
+ params.accountId,
10046
+ "xiaohongshu"
9800
10047
  ];
9801
10048
  const http = new Http(...args);
9802
10049
  const fans = {
@@ -9810,8 +10057,8 @@ var __webpack_exports__ = {};
9810
10057
  url: "https://creator.xiaohongshu.com/api/galaxy/creator/home/personal_info"
9811
10058
  }, {
9812
10059
  retries: 3,
9813
- retryDelay: 20,
9814
- timeout: 3000
10060
+ retryDelay: 300,
10061
+ timeout: 30000
9815
10062
  });
9816
10063
  fans.fans_count = Number(res.data.fans_count);
9817
10064
  fans.digg_count = Number(res.data.faved_count);
@@ -10948,7 +11195,8 @@ var __webpack_exports__ = {};
10948
11195
  },
10949
11196
  _task.logger,
10950
11197
  params.proxyLoc,
10951
- params.accountId
11198
+ params.accountId,
11199
+ "xiaohongshu"
10952
11200
  ];
10953
11201
  const http = new Http(...args);
10954
11202
  http.addResponseInterceptor((response)=>{
@@ -10996,8 +11244,8 @@ var __webpack_exports__ = {};
10996
11244
  headers: loginBaseXsHeader
10997
11245
  }, {
10998
11246
  retries: 3,
10999
- retryDelay: 20,
11000
- timeout: 5000
11247
+ retryDelay: 300,
11248
+ timeout: 30000
11001
11249
  }).catch((e)=>{
11002
11250
  const clientTimestamp = Date.now();
11003
11251
  const serverDate = e?.extra?.serverDate;
@@ -11029,8 +11277,8 @@ var __webpack_exports__ = {};
11029
11277
  headers: webSessionXsHeader
11030
11278
  }, {
11031
11279
  retries: 3,
11032
- retryDelay: 20,
11033
- timeout: 5000
11280
+ retryDelay: 300,
11281
+ timeout: 30000
11034
11282
  });
11035
11283
  const [baseInfo, web_session] = await Promise.all([
11036
11284
  _baseInfo,
@@ -11122,6 +11370,10 @@ var __webpack_exports__ = {};
11122
11370
  };
11123
11371
  return (0, share_namespaceObject.success)(data, message);
11124
11372
  };
11373
+ const extractEncFileKey = (downloadUrl)=>{
11374
+ if (!downloadUrl) return "";
11375
+ return downloadUrl.split("encfilekey=")[1]?.split("&")[0] || "";
11376
+ };
11125
11377
  const rid = ()=>`${Math.floor(Date.now() / 1e3).toString(16)}-${[
11126
11378
  ...Array(8)
11127
11379
  ].map(()=>Math.floor(16 * Math.random()).toString(16)).join("")}`;
@@ -12407,7 +12659,7 @@ var __webpack_exports__ = {};
12407
12659
  });
12408
12660
  const qrData = qrCodeResponse?.data;
12409
12661
  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}`, "");
12662
+ if (qrData?.error_code !== 0) return (0, share_namespaceObject.response)(414, USER_MESSAGE.QRCODE_FETCH_FAILED, "");
12411
12663
  return (0, share_namespaceObject.response)(0, "获取二维码成功", {
12412
12664
  qrcode: qrData.qrcode,
12413
12665
  token: qrData.token,
@@ -12422,7 +12674,7 @@ var __webpack_exports__ = {};
12422
12674
  } catch (err) {
12423
12675
  const msg = err instanceof Error ? err.message : String(err);
12424
12676
  task.logger.warn(`[douyinGetVerifyQrCode] 获取二维码失败: ${msg}`);
12425
- return (0, share_namespaceObject.response)(500, `获取二维码失败: ${msg}`, "");
12677
+ return (0, share_namespaceObject.response)(500, USER_MESSAGE.QRCODE_FETCH_FAILED, "");
12426
12678
  }
12427
12679
  };
12428
12680
  const DouyinGetWorkListParamsSchema = ActionCommonParamsSchema.extend({
@@ -13261,6 +13513,11 @@ var __webpack_exports__ = {};
13261
13513
  }
13262
13514
  async getImageInfo(localPath) {
13263
13515
  const stats = external_node_fs_default().statSync(localPath);
13516
+ const maxSize = 52428800;
13517
+ if (stats.size > maxSize) {
13518
+ external_node_path_default().basename(localPath);
13519
+ throw new Error("抖音平台:单张图片不得超过 50MB");
13520
+ }
13264
13521
  let width = 1080;
13265
13522
  let height = 1920;
13266
13523
  try {
@@ -13741,18 +13998,10 @@ var __webpack_exports__ = {};
13741
13998
  });
13742
13999
  } catch (error) {
13743
14000
  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));
14001
+ const classified = classifyPublishError(handledError);
14002
+ if (classified) {
14003
+ const message = `${classified.userMessage}${task.debug ? ` ${http.proxyInfo}` : ""}`;
14004
+ task.logger.error(`[douyinPublish] ${classified.category},直接返回: ${handledError.message} (code=${handledError.code})`, stringifyError(handledError));
13756
14005
  await updateTaskState?.({
13757
14006
  state: share_namespaceObject.TaskState.FAILED,
13758
14007
  error: message
@@ -15284,7 +15533,8 @@ var __webpack_exports__ = {};
15284
15533
  },
15285
15534
  _task.logger,
15286
15535
  params.proxyLoc,
15287
- params.accountId
15536
+ params.accountId,
15537
+ "xiaohongshu"
15288
15538
  ];
15289
15539
  const http = new Http(...args);
15290
15540
  let unreadCount = {
@@ -15313,8 +15563,8 @@ var __webpack_exports__ = {};
15313
15563
  headers: xsHeader
15314
15564
  }, {
15315
15565
  retries: 3,
15316
- retryDelay: 20,
15317
- timeout: 3000
15566
+ retryDelay: 300,
15567
+ timeout: 30000
15318
15568
  });
15319
15569
  const isSuccess = 0 === res.code;
15320
15570
  if (isSuccess) unreadCount = res.data;
@@ -15470,7 +15720,7 @@ var __webpack_exports__ = {};
15470
15720
  }
15471
15721
  const errMsg = error instanceof Error ? error.message : String(error);
15472
15722
  _task.logger.error(`抖音账号数据获取失败: ${errMsg}`);
15473
- return types_errorResponse(errMsg || "抖音账号数据获取失败");
15723
+ return types_errorResponse(USER_MESSAGE.DOUYIN_ACCOUNT_FETCH_FAILED);
15474
15724
  }
15475
15725
  }
15476
15726
  async function getShipinhaoData(_task, params) {
@@ -15601,7 +15851,7 @@ var __webpack_exports__ = {};
15601
15851
  }
15602
15852
  const errMsg = error instanceof Error ? error.message : String(error);
15603
15853
  _task.logger.error(`视频号账号数据获取失败: ${errMsg}`);
15604
- return types_errorResponse(errMsg || "视频号账号数据获取失败");
15854
+ return types_errorResponse(USER_MESSAGE.SHIPINHAO_ACCOUNT_FETCH_FAILED);
15605
15855
  }
15606
15856
  }
15607
15857
  async function getToutiaoData(_task, params) {
@@ -15727,7 +15977,8 @@ var __webpack_exports__ = {};
15727
15977
  },
15728
15978
  _task.logger,
15729
15979
  params.proxyLoc,
15730
- params.accountId
15980
+ params.accountId,
15981
+ "xiaohongshu"
15731
15982
  ];
15732
15983
  const http = new Http(...args);
15733
15984
  const xsEncrypt = new Xhshow();
@@ -15743,8 +15994,8 @@ var __webpack_exports__ = {};
15743
15994
  url: "https://creator.xiaohongshu.com/api/galaxy/creator/home/personal_info"
15744
15995
  }, {
15745
15996
  retries: 3,
15746
- retryDelay: 20,
15747
- timeout: 3000
15997
+ retryDelay: 300,
15998
+ timeout: 30000
15748
15999
  }),
15749
16000
  http.api({
15750
16001
  method: "get",
@@ -15753,8 +16004,8 @@ var __webpack_exports__ = {};
15753
16004
  headers: sevenDataXsHeader
15754
16005
  }, {
15755
16006
  retries: 3,
15756
- retryDelay: 20,
15757
- timeout: 3000
16007
+ retryDelay: 300,
16008
+ timeout: 30000
15758
16009
  })
15759
16010
  ]);
15760
16011
  const xhsData = {
@@ -16042,7 +16293,9 @@ var __webpack_exports__ = {};
16042
16293
  } : null
16043
16294
  }, "百家号文章数据获取成功");
16044
16295
  } catch (error) {
16045
- return searchPublishInfo_types_errorResponse(error instanceof Error ? error.message : "百家号文章数据获取失败");
16296
+ const errMsg = error instanceof Error ? error.message : String(error);
16297
+ _task.logger.error(`百家号文章数据获取失败: ${errMsg}`);
16298
+ return searchPublishInfo_types_errorResponse(USER_MESSAGE.BJH_POST_FETCH_FAILED);
16046
16299
  }
16047
16300
  }
16048
16301
  async function handleDouyinData(_task, params) {
@@ -16137,7 +16390,9 @@ var __webpack_exports__ = {};
16137
16390
  } : null
16138
16391
  }, "抖音数据获取成功");
16139
16392
  } catch (error) {
16140
- return searchPublishInfo_types_errorResponse(error instanceof Error ? error.message : "抖音数据获取失败");
16393
+ const errMsg = error instanceof Error ? error.message : String(error);
16394
+ _task.logger.error(`抖音作品数据获取失败: ${errMsg}`);
16395
+ return searchPublishInfo_types_errorResponse(USER_MESSAGE.DOUYIN_POST_FETCH_FAILED);
16141
16396
  }
16142
16397
  }
16143
16398
  async function handleShipinhaoData(_task, params) {
@@ -16302,8 +16557,9 @@ var __webpack_exports__ = {};
16302
16557
  }, "视频号数据获取成功");
16303
16558
  } catch (error) {
16304
16559
  const errMsg = error instanceof Error ? error.message : String(error);
16560
+ _task.logger.error(`视频号作品数据获取失败: ${errMsg}`);
16305
16561
  if (errMsg.startsWith("AUTH_ERROR:")) return searchPublishInfo_types_errorResponse("视频号数据获取失败,请检查账号状态", 414);
16306
- return searchPublishInfo_types_errorResponse(errMsg || "视频号数据获取失败");
16562
+ return searchPublishInfo_types_errorResponse(USER_MESSAGE.SHIPINHAO_POST_FETCH_FAILED);
16307
16563
  }
16308
16564
  }
16309
16565
  async function handleToutiaoData(_task, params) {
@@ -16388,7 +16644,9 @@ var __webpack_exports__ = {};
16388
16644
  } : null
16389
16645
  }, "头条号文章文章获取成功");
16390
16646
  } catch (error) {
16391
- return searchPublishInfo_types_errorResponse(error instanceof Error ? error.message : "头条号文章数据获取失败");
16647
+ const errMsg = error instanceof Error ? error.message : String(error);
16648
+ _task.logger.error(`头条号文章数据获取失败: ${errMsg}`);
16649
+ return searchPublishInfo_types_errorResponse(USER_MESSAGE.TT_POST_FETCH_FAILED);
16392
16650
  }
16393
16651
  }
16394
16652
  const external_node_vm_namespaceObject = require("node:vm");
@@ -18765,18 +19023,10 @@ var __webpack_exports__ = {};
18765
19023
  });
18766
19024
  } catch (error) {
18767
19025
  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));
19026
+ const classified = classifyPublishError(handledError);
19027
+ if (classified) {
19028
+ const message = `${classified.userMessage}${task.debug ? ` ${http.proxyInfo}` : ""}`;
19029
+ task.logger.error(`[shipinhaoPublish] ${classified.category},直接返回: ${handledError.message} (code=${handledError.code})`, stringifyError(handledError));
18780
19030
  await updateTaskState?.({
18781
19031
  state: share_namespaceObject.TaskState.FAILED,
18782
19032
  error: message
@@ -18794,7 +19044,7 @@ var __webpack_exports__ = {};
18794
19044
  const resultMsg = publishResult.data?.baseResp?.errmsg ?? publishResult.errMsg;
18795
19045
  if (0 === resultCode) {
18796
19046
  task.logger.info("[shipinhaoPublish] 发布成功");
18797
- const publishId = uploadedImages[0]?.thumbUrl?.split("encfilekey=")[1]?.split("&")[0] || "";
19047
+ const publishId = extractEncFileKey(uploadedImages[0]?.thumbUrl);
18798
19048
  await updateTaskState?.({
18799
19049
  state: share_namespaceObject.TaskState.SUCCESS,
18800
19050
  result: {
@@ -19516,165 +19766,1754 @@ var __webpack_exports__ = {};
19516
19766
  if ("server" === params.actionType) return rpa_server_rpaAction_Server(task, params);
19517
19767
  return executeAction(shipinhaoPublish_mock_mockAction, rpa_server_rpaAction_Server)(task, params);
19518
19768
  };
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
19549
- });
19769
+ function auth_getTimeStamp(length) {
19770
+ return Date.now().toString().substring(0, length);
19550
19771
  }
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);
19564
- }
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
19575
- };
19576
- const http = new Http({
19577
- headers
19578
- });
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);
19587
- });
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}`);
19595
- }
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));
19609
- }
19610
- } catch (err) {
19611
- return (0, share_namespaceObject.response)(414, `读取图片失败: ${err instanceof Error ? err.message : String(err)}`, void 0);
19612
- }
19613
- const md5 = (0, external_node_crypto_namespaceObject.createHash)("md5").update(imageBuffer).digest("hex");
19614
- const timestamp = Date.now().toString();
19615
- const totalChunks = Math.ceil(imageBuffer.length / CHUNK_SIZE);
19616
- console.log(`分片上传md5${md5}`);
19617
- let lastRes;
19618
- for(let i = 0; i < totalChunks; i++){
19619
- const chunkBuffer = imageBuffer.slice(i * CHUNK_SIZE, (i + 1) * CHUNK_SIZE);
19620
- const requestData = {
19621
- content: `data:application/octet-stream;base64,${chunkBuffer.toString("base64")}`,
19622
- chunk: i,
19623
- chunks: totalChunks,
19624
- fromUsername,
19625
- toUsername: params.toUsername,
19626
- aesKey: "U2FsdGVkX18cwrWR73LMGhBcmAX8xoNTgbmgkZBYkEs=",
19627
- mediaSize: imageBuffer.length,
19628
- mediaType: 3,
19629
- md5,
19630
- timestamp,
19631
- _log_finder_uin: "",
19632
- _log_finder_id: params.extraParam.finderUserName || "",
19633
- rawKeyBuff: null,
19634
- pluginSessionId: null,
19635
- scene: 7,
19636
- reqScene: 7
19637
- };
19638
- lastRes = await http.api({
19639
- method: "post",
19640
- url: `https://channels.weixin.qq.com/micro/interaction/cgi-bin/mmfinderassistant-bin/private-msg/upload-media-info?${urlParams}`,
19641
- data: requestData
19642
- });
19643
- console.log(`分片上传 ${i + 1}/${totalChunks} 响应:`, lastRes);
19644
- if (lastRes?.errCode !== 0 && i < totalChunks - 1) return (0, share_namespaceObject.response)(414, lastRes?.errMsg || `第 ${i + 1}/${totalChunks} 分片上传失败`, void 0);
19645
- }
19646
- if (lastRes?.errCode !== 0) return (0, share_namespaceObject.response)(414, lastRes?.errMsg || "上传图片失败", void 0);
19647
- const uploadedImgMsg = lastRes.data?.imgMsg;
19648
- imgMsg = {
19649
- aeskey: uploadedImgMsg.aesKey ?? uploadedImgMsg.aeskey,
19650
- url: uploadedImgMsg.cdnUrl ?? uploadedImgMsg.url,
19651
- hdSize: uploadedImgMsg.hdSize ?? uploadedImgMsg.size,
19652
- midSize: uploadedImgMsg.midSize ?? uploadedImgMsg.size,
19653
- thumbSize: uploadedImgMsg.thumbSize ?? uploadedImgMsg.size,
19654
- thumbHeight: uploadedImgMsg.thumbHeight ?? uploadedImgMsg.height,
19655
- thumbWidth: uploadedImgMsg.thumbWidth ?? uploadedImgMsg.width,
19656
- md5: uploadedImgMsg.md5
19657
- };
19658
- }
19659
- console.log("发送私信请求参数1111", {
19660
- sessionId: params.sessionId,
19661
- fromUsername
19662
- });
19663
- const sendRes = await http.api({
19772
+ async function auth_getUserInfo(cookies, http) {
19773
+ return http.api({
19664
19774
  method: "post",
19665
- url: `https://channels.weixin.qq.com/micro/interaction/cgi-bin/mmfinderassistant-bin/private-msg/send-private-msg?${urlParams}`,
19775
+ url: "https://channels.weixin.qq.com/cgi-bin/mmfinderassistant-bin/auth/auth_data",
19666
19776
  data: {
19667
- timestamp: Date.now().toString(),
19777
+ timestamp: auth_getTimeStamp(13),
19668
19778
  _log_finder_uin: "",
19669
- _log_finder_id: params.extraParam.finderUserName || "",
19779
+ _log_finder_id: "",
19670
19780
  rawKeyBuff: null,
19671
19781
  pluginSessionId: null,
19672
19782
  scene: 7,
19673
- reqScene: 7,
19674
- msgPack: {
19675
- sessionId: params.sessionId,
19676
- fromUsername,
19677
- toUsername: params.toUsername,
19783
+ reqScene: 7
19784
+ },
19785
+ headers: {
19786
+ cookie: cookies,
19787
+ referer: "https://channels.weixin.qq.com",
19788
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
19789
+ },
19790
+ defaultErrorMsg: "获取用户信息失败"
19791
+ });
19792
+ }
19793
+ async function auth_getUploadAuthKey(cookies, finderUsername, http) {
19794
+ return http.api({
19795
+ method: "post",
19796
+ url: "https://channels.weixin.qq.com/cgi-bin/mmfinderassistant-bin/helper/helper_upload_params",
19797
+ data: {
19798
+ timestamp: auth_getTimeStamp(13),
19799
+ _log_finder_id: finderUsername,
19800
+ rawKeyBuff: null
19801
+ },
19802
+ headers: {
19803
+ cookie: cookies,
19804
+ referer: "https://channels.weixin.qq.com",
19805
+ Accept: "application/json, text/plain, */*",
19806
+ "Content-Type": "application/json",
19807
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
19808
+ },
19809
+ defaultErrorMsg: "获取上传认证密钥失败"
19810
+ });
19811
+ }
19812
+ class ShipinhaoAuthError extends Error {
19813
+ constructor(message, errCode){
19814
+ super(message), this.errCode = errCode;
19815
+ this.name = "ShipinhaoAuthError";
19816
+ }
19817
+ }
19818
+ async function getShipinhaoUploadAuth(cookies, http) {
19819
+ const userInfo = await auth_getUserInfo(cookies, http);
19820
+ if (0 !== userInfo.errCode || !userInfo.data?.finderUser) {
19821
+ const isLoginExpired = 300333 === userInfo.errCode || 300334 === userInfo.errCode;
19822
+ throw new ShipinhaoAuthError(isLoginExpired ? "登录失效" : userInfo.errMsg || "获取用户信息失败", userInfo.errCode || 500);
19823
+ }
19824
+ const finderUsername = userInfo.data.finderUser.finderUsername;
19825
+ const authKeyResponse = await auth_getUploadAuthKey(cookies, finderUsername, http);
19826
+ if (0 !== authKeyResponse.errCode || !authKeyResponse.data?.authKey) throw new ShipinhaoAuthError(`获取上传认证参数失败: ${authKeyResponse.errMsg}`, authKeyResponse.errCode || 500);
19827
+ const uin = authKeyResponse.data.uin;
19828
+ if (!uin) throw new ShipinhaoAuthError("获取用户 uin 失败", 500);
19829
+ const videoFileType = authKeyResponse.data.videoFileType || 20302;
19830
+ const pictureFileType = authKeyResponse.data.pictureFileType || 20304;
19831
+ return {
19832
+ uin,
19833
+ authKey: authKeyResponse.data.authKey,
19834
+ finderUsername,
19835
+ videoFileType,
19836
+ pictureFileType
19837
+ };
19838
+ }
19839
+ const MENTION_TEXT_SUFFIX = "\u0020";
19840
+ const MENTION_XML_SUFFIX = "\u2005";
19841
+ function payload_buildDescription(params) {
19842
+ let description = params.description || "";
19843
+ for (const topic of params.topics || [])description += `#${topic}`;
19844
+ for (const user of params.mentionedUsers || [])description += `@${user.nickname}${MENTION_TEXT_SUFFIX}`;
19845
+ return description;
19846
+ }
19847
+ function buildMentionedUser(mentionedUsers) {
19848
+ return (mentionedUsers || []).map((user)=>({
19849
+ nickname: `${user.nickname}${MENTION_TEXT_SUFFIX}`
19850
+ }));
19851
+ }
19852
+ function payload_buildTopicXml(params) {
19853
+ const values = [];
19854
+ let atIndex = null;
19855
+ if (params.description) values.push(`<![CDATA[${params.description}]]>`);
19856
+ for (const topic of params.topics || [])values.push(`<topic><![CDATA[#${topic}#]]></topic>`);
19857
+ for (const user of params.mentionedUsers || []){
19858
+ if (null === atIndex) atIndex = values.length;
19859
+ values.push(`<![CDATA[@${user.nickname}${MENTION_XML_SUFFIX}]]>`);
19860
+ }
19861
+ let xml = "<finder>";
19862
+ xml += "<version>1</version>";
19863
+ xml += `<valuecount>${values.length}</valuecount>`;
19864
+ xml += `<style><at>${atIndex ?? ""}</at></style>`;
19865
+ values.forEach((value, index)=>{
19866
+ xml += `<value${index}>${value}</value${index}>`;
19867
+ });
19868
+ xml += "</finder>";
19869
+ return xml;
19870
+ }
19871
+ function payload_buildLocation(location) {
19872
+ if (!location) return {
19873
+ latitude: 0,
19874
+ longitude: 0,
19875
+ city: "",
19876
+ poiName: "",
19877
+ address: "",
19878
+ poiClassifyId: ""
19879
+ };
19880
+ return {
19881
+ latitude: location.latitude,
19882
+ longitude: location.longitude,
19883
+ city: location.city,
19884
+ poiName: location.poiName || "",
19885
+ address: location.address || "",
19886
+ poiClassifyId: location.poiClassifyId || ""
19887
+ };
19888
+ }
19889
+ function buildTopic(params) {
19890
+ const topic = {
19891
+ finderTopicInfo: payload_buildTopicXml(params)
19892
+ };
19893
+ if (params.collection) {
19894
+ topic.collectionId = params.collection.collectionId;
19895
+ topic.collectionName = params.collection.collectionName;
19896
+ }
19897
+ return topic;
19898
+ }
19899
+ function buildEvent(event) {
19900
+ if (!event) return {};
19901
+ return {
19902
+ eventTopicId: event.eventTopicId,
19903
+ eventName: event.eventName,
19904
+ eventCreatorNickname: event.eventCreatorNickname || ""
19905
+ };
19906
+ }
19907
+ function buildExtReading(link) {
19908
+ if (!link) return {
19909
+ link: "",
19910
+ title: "",
19911
+ urlType: 1
19912
+ };
19913
+ return {
19914
+ link: link.link.replace(/[\s\u200b]/g, ""),
19915
+ title: link.title,
19916
+ urlType: link.urlType ?? 1
19917
+ };
19918
+ }
19919
+ function buildTagInfo(tagInfo, tagKey) {
19920
+ return {
19921
+ ...tagInfo,
19922
+ tagKey
19923
+ };
19924
+ }
19925
+ const CHUNK_SIZE = 8388608;
19926
+ const UPLOAD_STAGE_TIMEOUT = 180000;
19927
+ const DEFAULT_TUNING = {
19928
+ metaTimeout: UPLOAD_STAGE_TIMEOUT,
19929
+ partTimeout: UPLOAD_STAGE_TIMEOUT,
19930
+ partRetries: 3,
19931
+ completeTimeout: UPLOAD_STAGE_TIMEOUT
19932
+ };
19933
+ async function uploader_uploadFile(opts) {
19934
+ const { filePath, fileType, uin, authKey, http, logger, tuning } = opts;
19935
+ const stat = external_node_fs_default().statSync(filePath);
19936
+ const fileSize = stat.size;
19937
+ const fileName = filePath.split(/[\\/]/).pop() || "file";
19938
+ const metaTimeout = tuning?.metaTimeout ?? DEFAULT_TUNING.metaTimeout;
19939
+ const partTimeout = tuning?.partTimeout ?? DEFAULT_TUNING.partTimeout;
19940
+ const partRetries = tuning?.partRetries ?? DEFAULT_TUNING.partRetries;
19941
+ const completeTimeout = tuning?.completeTimeout ?? DEFAULT_TUNING.completeTimeout;
19942
+ logger?.info(`[shipinhaoPublishVideo] 开始上传: ${fileName} (${fileSize} B, filetype=${fileType})`);
19943
+ const fileMd5 = await computeFileMd5(filePath);
19944
+ const taskId = generateTaskId(fileName, fileSize, fileMd5);
19945
+ const baseUrl = "https://finderassistancea.video.qq.com";
19946
+ const headers = {
19947
+ Authorization: authKey
19948
+ };
19949
+ const xArgs = `apptype=251&filetype=${fileType}&weixinnum=${uin}&filekey=${encodeURIComponent(fileName)}&filesize=${fileSize}&taskid=${taskId}&scene=2`;
19950
+ const chunkCount = Math.ceil(fileSize / CHUNK_SIZE);
19951
+ const blockPartLength = [];
19952
+ for(let i = 0; i < chunkCount; i++)blockPartLength.push(Math.min((i + 1) * CHUNK_SIZE, fileSize));
19953
+ logger?.info(`[shipinhaoPublishVideo] 视频分片: ${chunkCount} 片`);
19954
+ const applyRes = await http.api({
19955
+ method: "PUT",
19956
+ url: `${baseUrl}/applyuploaddfs`,
19957
+ headers: {
19958
+ ...headers,
19959
+ "X-Arguments": xArgs
19960
+ },
19961
+ data: {
19962
+ BlockSum: chunkCount,
19963
+ BlockPartLength: blockPartLength
19964
+ }
19965
+ }, {
19966
+ timeout: metaTimeout,
19967
+ retries: 2,
19968
+ retryDelay: 2000
19969
+ });
19970
+ if (!applyRes.UploadID && !applyRes.ListPartsResult) throw new Error("申请 UploadID 失败: " + JSON.stringify(applyRes));
19971
+ let uploadId = applyRes.UploadID;
19972
+ const uploadedParts = new Set();
19973
+ if (applyRes.ListPartsResult) {
19974
+ const parts = Array.isArray(applyRes.ListPartsResult.Part) ? applyRes.ListPartsResult.Part : applyRes.ListPartsResult.Part ? [
19975
+ applyRes.ListPartsResult.Part
19976
+ ] : [];
19977
+ for (const p of parts)uploadedParts.add(p.PartNumber);
19978
+ const retryRes = await http.api({
19979
+ method: "PUT",
19980
+ url: `${baseUrl}/applyuploaddfs`,
19981
+ headers: {
19982
+ ...headers,
19983
+ "X-Arguments": xArgs
19984
+ },
19985
+ data: {
19986
+ BlockSum: chunkCount,
19987
+ BlockPartLength: blockPartLength
19988
+ }
19989
+ }, {
19990
+ timeout: metaTimeout,
19991
+ retries: 2,
19992
+ retryDelay: 2000
19993
+ });
19994
+ uploadId = retryRes.UploadID;
19995
+ if (!uploadId) throw new Error("续传获取 UploadID 失败");
19996
+ }
19997
+ const partInfo = [];
19998
+ const fd = external_node_fs_default().openSync(filePath, "r");
19999
+ try {
20000
+ for(let i = 0; i < chunkCount; i++){
20001
+ const partNumber = i + 1;
20002
+ if (uploadedParts.has(partNumber)) {
20003
+ const existing = applyRes.ListPartsResult.Part.find((p)=>p.PartNumber === partNumber);
20004
+ if (existing) {
20005
+ partInfo.push({
20006
+ PartNumber: partNumber,
20007
+ ETag: existing.ETag
20008
+ });
20009
+ continue;
20010
+ }
20011
+ }
20012
+ const start = i * CHUNK_SIZE;
20013
+ const end = Math.min(start + CHUNK_SIZE, fileSize);
20014
+ const chunkSize = end - start;
20015
+ const chunk = Buffer.alloc(chunkSize);
20016
+ external_node_fs_default().readSync(fd, chunk, 0, chunkSize, start);
20017
+ const chunkMd5 = external_node_crypto_default().createHash("md5").update(chunk).digest("hex");
20018
+ const partStart = Date.now();
20019
+ await http.api({
20020
+ method: "PUT",
20021
+ url: `${baseUrl}/uploadpartdfs?PartNumber=${partNumber}&UploadID=${encodeURIComponent(uploadId)}`,
20022
+ headers: {
20023
+ ...headers,
20024
+ "X-Arguments": xArgs.replace(/scene=2/, "scene=0"),
20025
+ "Content-MD5": chunkMd5
20026
+ },
20027
+ data: chunk
20028
+ }, {
20029
+ timeout: partTimeout,
20030
+ retries: partRetries,
20031
+ retryDelay: 2000
20032
+ });
20033
+ Date.now();
20034
+ partInfo.push({
20035
+ PartNumber: partNumber,
20036
+ ETag: `"${chunkMd5}"`
20037
+ });
20038
+ }
20039
+ } finally{
20040
+ external_node_fs_default().closeSync(fd);
20041
+ }
20042
+ const completeRes = await http.api({
20043
+ method: "POST",
20044
+ url: `${baseUrl}/completepartuploaddfs?UploadID=${encodeURIComponent(uploadId)}`,
20045
+ headers: {
20046
+ ...headers,
20047
+ "X-Arguments": xArgs
20048
+ },
20049
+ data: {
20050
+ TransFlag: "0_0",
20051
+ PartInfo: partInfo
20052
+ }
20053
+ }, {
20054
+ timeout: completeTimeout,
20055
+ retries: 1,
20056
+ retryDelay: 3000
20057
+ });
20058
+ if (!completeRes.DownloadURL) throw new Error("合并分片失败: " + JSON.stringify(completeRes));
20059
+ logger?.info(`[shipinhaoPublishVideo] ${fileName} 上传成功`);
20060
+ return {
20061
+ downloadUrl: completeRes.DownloadURL,
20062
+ md5: fileMd5,
20063
+ fileSize
20064
+ };
20065
+ }
20066
+ async function computeFileMd5(filePath) {
20067
+ return new Promise((resolve, reject)=>{
20068
+ const hash = external_node_crypto_default().createHash("md5");
20069
+ const stream = external_node_fs_default().createReadStream(filePath);
20070
+ stream.on("data", (chunk)=>hash.update(chunk));
20071
+ stream.on("end", ()=>resolve(hash.digest("hex")));
20072
+ stream.on("error", reject);
20073
+ });
20074
+ }
20075
+ function generateTaskId(fileName, fileSize, fileMd5) {
20076
+ const input = `${fileName}-${fileSize}-${fileMd5}`;
20077
+ return external_node_crypto_default().createHash("md5").update(input).digest("hex").slice(0, 32);
20078
+ }
20079
+ const MAX_METADATA_BOX_SIZE = 268435456;
20080
+ function readBoxHeader(fd, offset, limit) {
20081
+ if (offset + 8 > limit) return null;
20082
+ const head = Buffer.alloc(16);
20083
+ const read = external_node_fs_default().readSync(fd, head, 0, 16, offset);
20084
+ if (read < 8) return null;
20085
+ let size = head.readUInt32BE(0);
20086
+ const type = head.toString("latin1", 4, 8);
20087
+ let headerSize = 8;
20088
+ if (1 === size) {
20089
+ if (read < 16) return null;
20090
+ size = head.readUInt32BE(8) * 2 ** 32 + head.readUInt32BE(12);
20091
+ headerSize = 16;
20092
+ } else if (0 === size) size = limit - offset;
20093
+ if (size < headerSize || offset + size > limit) return null;
20094
+ return {
20095
+ type,
20096
+ size,
20097
+ headerSize
20098
+ };
20099
+ }
20100
+ function parseVideoMeta(filePath) {
20101
+ let fd;
20102
+ let fileSize;
20103
+ try {
20104
+ fd = external_node_fs_default().openSync(filePath, "r");
20105
+ } catch {
20106
+ return null;
20107
+ }
20108
+ try {
20109
+ fileSize = external_node_fs_default().fstatSync(fd).size;
20110
+ const state = {
20111
+ movie: null,
20112
+ tracks: [],
20113
+ trexDefaults: new Map(),
20114
+ fragmentDurations: new Map(),
20115
+ trafTrackId: 0,
20116
+ trafDefaultSampleDuration: 0
20117
+ };
20118
+ let offset = 0;
20119
+ while(offset + 8 <= fileSize){
20120
+ const header = readBoxHeader(fd, offset, fileSize);
20121
+ if (!header) break;
20122
+ if ("moov" === header.type || "moof" === header.type) {
20123
+ const bodyLength = header.size - header.headerSize;
20124
+ if (bodyLength > 0 && bodyLength <= MAX_METADATA_BOX_SIZE) {
20125
+ const body = Buffer.alloc(bodyLength);
20126
+ const read = external_node_fs_default().readSync(fd, body, 0, bodyLength, offset + header.headerSize);
20127
+ state.trafTrackId = 0;
20128
+ state.trafDefaultSampleDuration = 0;
20129
+ walkBoxes(body.subarray(0, read), 0, read, state);
20130
+ }
20131
+ }
20132
+ offset += header.size;
20133
+ }
20134
+ const { movie, tracks } = state;
20135
+ const video = tracks.find((t)=>"vide" === t.handler) || tracks.find((t)=>t.width > 0 && t.height > 0);
20136
+ if (!video) return null;
20137
+ let { width, height } = video;
20138
+ if (90 === video.rotation || 270 === video.rotation) [width, height] = [
20139
+ height,
20140
+ width
20141
+ ];
20142
+ return {
20143
+ width: Math.round(width),
20144
+ height: Math.round(height),
20145
+ duration: resolveDuration(movie, video, state.fragmentDurations),
20146
+ rotation: video.rotation,
20147
+ fileSize,
20148
+ codec: video.codec
20149
+ };
20150
+ } catch {
20151
+ return null;
20152
+ } finally{
20153
+ try {
20154
+ external_node_fs_default().closeSync(fd);
20155
+ } catch {}
20156
+ }
20157
+ }
20158
+ function walkBoxes(buf, start, end, state) {
20159
+ let off = start;
20160
+ while(off + 8 <= end){
20161
+ let size = buf.readUInt32BE(off);
20162
+ const type = buf.toString("latin1", off + 4, off + 8);
20163
+ let headerSize = 8;
20164
+ if (1 === size) {
20165
+ if (off + 16 > end) break;
20166
+ const hi = buf.readUInt32BE(off + 8);
20167
+ const lo = buf.readUInt32BE(off + 12);
20168
+ size = hi * 2 ** 32 + lo;
20169
+ headerSize = 16;
20170
+ } else if (0 === size) size = end - off;
20171
+ if (size < headerSize || off + size > end) break;
20172
+ const bodyStart = off + headerSize;
20173
+ const bodyEnd = off + size;
20174
+ switch(type){
20175
+ case "trak":
20176
+ case "mdia":
20177
+ case "minf":
20178
+ case "stbl":
20179
+ case "mvex":
20180
+ case "traf":
20181
+ walkBoxes(buf, bodyStart, bodyEnd, state);
20182
+ break;
20183
+ case "mvhd":
20184
+ state.movie = parseMvhd(buf, bodyStart, bodyEnd);
20185
+ break;
20186
+ case "tkhd":
20187
+ state.tracks.push({
20188
+ ...parseTkhd(buf, bodyStart, bodyEnd),
20189
+ handler: null,
20190
+ codec: null,
20191
+ timescale: 0,
20192
+ mdhdDuration: 0,
20193
+ sttsDuration: 0
20194
+ });
20195
+ break;
20196
+ case "mdhd":
20197
+ {
20198
+ const mdhd = parseMvhd(buf, bodyStart, bodyEnd);
20199
+ if (mdhd && state.tracks.length) {
20200
+ const track = state.tracks[state.tracks.length - 1];
20201
+ track.timescale = mdhd.timescale;
20202
+ track.mdhdDuration = mdhd.duration;
20203
+ }
20204
+ break;
20205
+ }
20206
+ case "hdlr":
20207
+ if (bodyEnd - bodyStart >= 12 && state.tracks.length) state.tracks[state.tracks.length - 1].handler = buf.toString("latin1", bodyStart + 8, bodyStart + 12);
20208
+ break;
20209
+ case "stsd":
20210
+ {
20211
+ const codec = parseStsdCodec(buf, bodyStart, bodyEnd);
20212
+ if (codec && state.tracks.length) state.tracks[state.tracks.length - 1].codec = codec;
20213
+ break;
20214
+ }
20215
+ case "stts":
20216
+ if (state.tracks.length) state.tracks[state.tracks.length - 1].sttsDuration = parseSttsDuration(buf, bodyStart, bodyEnd);
20217
+ break;
20218
+ case "trex":
20219
+ if (bodyStart + 20 > bodyEnd) break;
20220
+ state.trexDefaults.set(buf.readUInt32BE(bodyStart + 4), buf.readUInt32BE(bodyStart + 12));
20221
+ break;
20222
+ case "tfhd":
20223
+ {
20224
+ const tfhd = parseTfhd(buf, bodyStart, bodyEnd);
20225
+ state.trafTrackId = tfhd.trackId;
20226
+ state.trafDefaultSampleDuration = tfhd.defaultSampleDuration || state.trexDefaults.get(tfhd.trackId) || 0;
20227
+ break;
20228
+ }
20229
+ case "trun":
20230
+ {
20231
+ const duration = parseTrunDuration(buf, bodyStart, bodyEnd, state.trafDefaultSampleDuration);
20232
+ state.fragmentDurations.set(state.trafTrackId, (state.fragmentDurations.get(state.trafTrackId) || 0) + duration);
20233
+ break;
20234
+ }
20235
+ }
20236
+ off += size;
20237
+ }
20238
+ }
20239
+ const UNKNOWN_DURATION_32 = 0xffffffff;
20240
+ function isUsableDuration(duration) {
20241
+ return duration > 0 && duration !== UNKNOWN_DURATION_32;
20242
+ }
20243
+ function resolveDuration(movie, video, fragmentDurations) {
20244
+ if (movie && movie.timescale && isUsableDuration(movie.duration)) return movie.duration / movie.timescale;
20245
+ if (video.timescale) {
20246
+ if (isUsableDuration(video.mdhdDuration)) return video.mdhdDuration / video.timescale;
20247
+ if (video.sttsDuration > 0) return video.sttsDuration / video.timescale;
20248
+ const fragment = fragmentDurations.get(video.trackId) ?? (1 === fragmentDurations.size ? [
20249
+ ...fragmentDurations.values()
20250
+ ][0] : 0);
20251
+ if (fragment > 0) return fragment / video.timescale;
20252
+ }
20253
+ return 0;
20254
+ }
20255
+ function parseSttsDuration(buf, start, end) {
20256
+ if (start + 8 > end) return 0;
20257
+ const entryCount = buf.readUInt32BE(start + 4);
20258
+ let total = 0;
20259
+ for(let i = 0; i < entryCount; i++){
20260
+ const off = start + 8 + 8 * i;
20261
+ if (off + 8 > end) break;
20262
+ total += buf.readUInt32BE(off) * buf.readUInt32BE(off + 4);
20263
+ }
20264
+ return total;
20265
+ }
20266
+ function parseTfhd(buf, start, end) {
20267
+ if (start + 8 > end) return {
20268
+ trackId: 0,
20269
+ defaultSampleDuration: 0
20270
+ };
20271
+ const flags = buf.readUIntBE(start + 1, 3);
20272
+ const trackId = buf.readUInt32BE(start + 4);
20273
+ let off = start + 8;
20274
+ if (0x000001 & flags) off += 8;
20275
+ if (0x000002 & flags) off += 4;
20276
+ if (0x000008 & flags && off + 4 <= end) return {
20277
+ trackId,
20278
+ defaultSampleDuration: buf.readUInt32BE(off)
20279
+ };
20280
+ return {
20281
+ trackId,
20282
+ defaultSampleDuration: 0
20283
+ };
20284
+ }
20285
+ function parseTrunDuration(buf, start, end, defaultSampleDuration) {
20286
+ if (start + 8 > end) return 0;
20287
+ const flags = buf.readUIntBE(start + 1, 3);
20288
+ const sampleCount = buf.readUInt32BE(start + 4);
20289
+ let off = start + 8;
20290
+ if (0x000001 & flags) off += 4;
20291
+ if (0x000004 & flags) off += 4;
20292
+ const hasDuration = (0x000100 & flags) !== 0;
20293
+ if (!hasDuration) return sampleCount * defaultSampleDuration;
20294
+ const entrySize = 4 + ((0x000200 & flags) !== 0 ? 4 : 0) + ((0x000400 & flags) !== 0 ? 4 : 0) + ((0x000800 & flags) !== 0 ? 4 : 0);
20295
+ let total = 0;
20296
+ for(let i = 0; i < sampleCount; i++){
20297
+ const entryOff = off + i * entrySize;
20298
+ if (entryOff + 4 > end) break;
20299
+ total += buf.readUInt32BE(entryOff);
20300
+ }
20301
+ return total;
20302
+ }
20303
+ function parseStsdCodec(buf, start, end) {
20304
+ if (start + 16 > end) return null;
20305
+ if (0 === buf.readUInt32BE(start + 4)) return null;
20306
+ return buf.toString("latin1", start + 12, start + 16).toLowerCase();
20307
+ }
20308
+ function parseMvhd(buf, start, end) {
20309
+ const version = buf.readUInt8(start);
20310
+ if (1 === version) {
20311
+ if (start + 28 > end) return null;
20312
+ const timescale = buf.readUInt32BE(start + 20);
20313
+ const hi = buf.readUInt32BE(start + 24);
20314
+ const lo = buf.readUInt32BE(start + 28);
20315
+ return {
20316
+ timescale,
20317
+ duration: hi * 2 ** 32 + lo
20318
+ };
20319
+ }
20320
+ if (start + 20 > end) return null;
20321
+ return {
20322
+ timescale: buf.readUInt32BE(start + 12),
20323
+ duration: buf.readUInt32BE(start + 16)
20324
+ };
20325
+ }
20326
+ function parseTkhd(buf, start, end) {
20327
+ const version = buf.readUInt8(start);
20328
+ const afterDuration = 1 === version ? 36 : 24;
20329
+ const matrixOff = start + afterDuration + 16;
20330
+ const whOff = matrixOff + 36;
20331
+ const trackIdOff = start + (1 === version ? 20 : 12);
20332
+ const trackId = trackIdOff + 4 <= end ? buf.readUInt32BE(trackIdOff) : 0;
20333
+ if (whOff + 8 > end) return {
20334
+ trackId,
20335
+ width: 0,
20336
+ height: 0,
20337
+ rotation: 0
20338
+ };
20339
+ const width = buf.readUInt32BE(whOff) / 65536;
20340
+ const height = buf.readUInt32BE(whOff + 4) / 65536;
20341
+ const a = buf.readInt32BE(matrixOff) / 65536;
20342
+ const b = buf.readInt32BE(matrixOff + 4) / 65536;
20343
+ let rotation = 0;
20344
+ if (Math.abs(a) < 0.01 && Math.abs(b - 1) < 0.01) rotation = 90;
20345
+ else if (Math.abs(a + 1) < 0.01 && Math.abs(b) < 0.01) rotation = 180;
20346
+ else if (Math.abs(a) < 0.01 && Math.abs(b + 1) < 0.01) rotation = 270;
20347
+ return {
20348
+ trackId,
20349
+ width,
20350
+ height,
20351
+ rotation
20352
+ };
20353
+ }
20354
+ function parseVideoCodec(filePath) {
20355
+ return parseVideoMeta(filePath)?.codec ?? null;
20356
+ }
20357
+ function buildVideoMetaFromParams(filePath, metadata) {
20358
+ return {
20359
+ width: Math.round(metadata.width),
20360
+ height: Math.round(metadata.height),
20361
+ duration: metadata.duration,
20362
+ rotation: 0,
20363
+ fileSize: metadata.fileSize,
20364
+ codec: parseVideoCodec(filePath)
20365
+ };
20366
+ }
20367
+ const MAX_DURATION_SECONDS = 28800;
20368
+ const MAX_FILE_SIZE = 21474836480;
20369
+ const ALLOWED_EXTENSIONS = [
20370
+ ".mp4"
20371
+ ];
20372
+ const ALLOWED_CODECS = [
20373
+ "avc1",
20374
+ "avc3"
20375
+ ];
20376
+ const MIN_TITLE_LENGTH = 6;
20377
+ const MAX_TITLE_LENGTH = 16;
20378
+ function formatFileSize(bytes) {
20379
+ if (bytes < 1048576) return `${(bytes / 1024).toFixed(2)} KB`;
20380
+ if (bytes < 1073741824) return `${(bytes / 1024 / 1024).toFixed(2)} MB`;
20381
+ return `${(bytes / 1024 / 1024 / 1024).toFixed(2)} GB`;
20382
+ }
20383
+ function formatDuration(seconds) {
20384
+ const total = Math.round(seconds);
20385
+ const h = Math.floor(total / 3600);
20386
+ const m = Math.floor(total % 3600 / 60);
20387
+ const s = total % 60;
20388
+ if (h > 0) return `${h}小时${m}分${s}秒`;
20389
+ if (m > 0) return `${m}分${s}秒`;
20390
+ return `${s}秒`;
20391
+ }
20392
+ function validateShipinhaoVideo(filePath, meta) {
20393
+ const fileName = external_node_path_default().basename(filePath);
20394
+ const ext = external_node_path_default().extname(fileName).toLowerCase();
20395
+ if (!ALLOWED_EXTENSIONS.includes(ext)) return `视频格式不支持:${fileName}。视频号仅支持 MP4/H.264 格式,请转换后重试。`;
20396
+ if (meta.duration > MAX_DURATION_SECONDS) return `视频时长超过限制:${fileName}(${formatDuration(meta.duration)})。视频号视频时长不能超过 8 小时,请剪辑后重试。`;
20397
+ if (meta.fileSize > MAX_FILE_SIZE) return `视频大小超过限制:${fileName}(${formatFileSize(meta.fileSize)})。视频号视频不能超过 20GB,请压缩后重试。`;
20398
+ if (meta.codec && !ALLOWED_CODECS.includes(meta.codec)) return `视频编码不支持:${fileName}(${meta.codec})。视频号仅支持 H.264 编码,请转码后重试。`;
20399
+ return null;
20400
+ }
20401
+ function validateShipinhaoTitle(title) {
20402
+ if (void 0 === title) return null;
20403
+ const trimmed = title.trim();
20404
+ if ("" === trimmed) return null;
20405
+ const length = [
20406
+ ...trimmed
20407
+ ].length;
20408
+ if (length < MIN_TITLE_LENGTH || length > MAX_TITLE_LENGTH) return `视频号标题需要在 ${MIN_TITLE_LENGTH}-${MAX_TITLE_LENGTH} 个字符之间,当前 ${length} 个字符,请调整后重试。`;
20409
+ return null;
20410
+ }
20411
+ const POST_CREATE_PAGE_URL = "https://channels.weixin.qq.com/micro/content/post/create";
20412
+ const MICRO_CONTENT_BASE = "https://channels.weixin.qq.com/micro/content/cgi-bin/mmfinderassistant-bin";
20413
+ function resolveClientContext(params, fallbackUin) {
20414
+ const extra = params.extraParam || {};
20415
+ const deviceIdCookie = params.cookies.find((c)=>"device_id" === c.name || "finger_print_device_id" === c.name)?.value;
20416
+ return {
20417
+ aId: "string" == typeof extra.aId ? extra.aId : "",
20418
+ fingerPrintDeviceId: "string" == typeof extra.fingerPrintDeviceId ? extra.fingerPrintDeviceId : deviceIdCookie || "",
20419
+ uin: "string" == typeof extra.uin ? extra.uin : String(fallbackUin)
20420
+ };
20421
+ }
20422
+ function buildPublishHeaders(cookieString, client) {
20423
+ const headers = {
20424
+ cookie: cookieString,
20425
+ referer: POST_CREATE_PAGE_URL,
20426
+ origin: "https://channels.weixin.qq.com",
20427
+ "content-type": "application/json"
20428
+ };
20429
+ if (client.fingerPrintDeviceId) headers["finger-print-device-id"] = client.fingerPrintDeviceId;
20430
+ if (client.uin) headers["x-wechat-uin"] = client.uin;
20431
+ return headers;
20432
+ }
20433
+ function buildPublishQuery(client) {
20434
+ const query = {
20435
+ _rid: rid(),
20436
+ _pageUrl: POST_CREATE_PAGE_URL
20437
+ };
20438
+ if (client.aId) query._aid = client.aId;
20439
+ return query;
20440
+ }
20441
+ function buildCommonBody(finderUsername) {
20442
+ return {
20443
+ timestamp: String(Date.now()),
20444
+ _log_finder_uin: "",
20445
+ _log_finder_id: finderUsername,
20446
+ rawKeyBuff: "",
20447
+ pluginSessionId: null,
20448
+ scene: 7,
20449
+ reqScene: 7
20450
+ };
20451
+ }
20452
+ async function getTraceKey(auth, client, http, logger) {
20453
+ const res = await http.api({
20454
+ method: "POST",
20455
+ url: `${MICRO_CONTENT_BASE}/post/get-finder-post-trace-key`,
20456
+ params: buildPublishQuery(client),
20457
+ data: {
20458
+ objectId: "",
20459
+ ...buildCommonBody(auth.finderUsername)
20460
+ },
20461
+ defaultErrorMsg: "获取 traceKey 失败"
20462
+ });
20463
+ if (0 !== res.errCode || !res.data?.traceKey) {
20464
+ logger.error("[getTraceKey] 获取失败:", JSON.stringify(res));
20465
+ throw new Error(`获取 traceKey 失败: ${JSON.stringify(res)}`);
20466
+ }
20467
+ return res.data.traceKey;
20468
+ }
20469
+ async function getObjectTagKey(auth, client, http, logger) {
20470
+ try {
20471
+ const res = await http.api({
20472
+ method: "POST",
20473
+ url: `${MICRO_CONTENT_BASE}/post/finder_get_object_tag_list`,
20474
+ params: buildPublishQuery(client),
20475
+ data: {
20476
+ source: 1,
20477
+ ...buildCommonBody(auth.finderUsername)
20478
+ },
20479
+ defaultErrorMsg: "获取内容声明标注失败"
20480
+ });
20481
+ if (0 !== res.errCode || !res.data?.tagKey) {
20482
+ logger.warn(`[getObjectTagKey] 未取到 tagKey: ${JSON.stringify(res)}`);
20483
+ return null;
20484
+ }
20485
+ return res.data.tagKey;
20486
+ } catch (error) {
20487
+ logger.warn(`[getObjectTagKey] 获取 tagKey 异常: ${stringifyError(error)}`);
20488
+ return null;
20489
+ }
20490
+ }
20491
+ async function submitAndPollTranscode(opts) {
20492
+ const { videoUrl, videoMeta, traceKey, uploadStartTime, uploadEndTime, finderUsername, client, http, logger } = opts;
20493
+ const finderUrl = videoUrl.includes("wxapp.tc.qq.com") ? `https://finder.video.qq.com${videoUrl.split("qq.com")[1]}` : videoUrl;
20494
+ logger.info(`[submitAndPollTranscode] 视频尺寸: ${videoMeta.width}x${videoMeta.height}, 时长: ${videoMeta.duration}s`);
20495
+ const submitRes = await http.api({
20496
+ method: "POST",
20497
+ url: `${MICRO_CONTENT_BASE}/post/post_clip_video`,
20498
+ params: buildPublishQuery(client),
20499
+ data: {
20500
+ url: finderUrl,
20501
+ timeStart: 0,
20502
+ cropDuration: 0,
20503
+ height: videoMeta.height,
20504
+ width: videoMeta.width,
20505
+ x: 0,
20506
+ y: 0,
20507
+ clipOriginVideoInfo: {
20508
+ width: videoMeta.width,
20509
+ height: videoMeta.height,
20510
+ duration: videoMeta.duration,
20511
+ fileSize: videoMeta.fileSize
20512
+ },
20513
+ traceInfo: {
20514
+ traceKey,
20515
+ uploadCdnStart: uploadStartTime,
20516
+ uploadCdnEnd: uploadEndTime
20517
+ },
20518
+ targetWidth: videoMeta.width,
20519
+ targetHeight: videoMeta.height,
20520
+ type: 4,
20521
+ useAstraThumbCover: 1,
20522
+ ...buildCommonBody(finderUsername)
20523
+ },
20524
+ defaultErrorMsg: "提交转码失败"
20525
+ });
20526
+ if (0 !== submitRes.errCode || !submitRes.data?.clipKey) {
20527
+ logger.error("[submitAndPollTranscode] 提交转码失败:", JSON.stringify(submitRes));
20528
+ throw new Error(`提交转码失败: ${JSON.stringify(submitRes)}`);
20529
+ }
20530
+ const { clipKey, draftId } = submitRes.data;
20531
+ const pollInterval = 5000;
20532
+ const pollBudget = Math.min(1800000, 300000 + 1000 * Math.ceil(1.5 * videoMeta.duration));
20533
+ const maxPolls = Math.ceil(pollBudget / pollInterval);
20534
+ let pollCount = 0;
20535
+ while(pollCount < maxPolls){
20536
+ await sleep(pollInterval);
20537
+ pollCount++;
20538
+ const pollRes = await http.api({
20539
+ method: "POST",
20540
+ url: `${MICRO_CONTENT_BASE}/post/post_clip_video_result`,
20541
+ params: buildPublishQuery(client),
20542
+ data: {
20543
+ clipKey,
20544
+ draftId,
20545
+ ...buildCommonBody(finderUsername)
20546
+ },
20547
+ defaultErrorMsg: "转码轮询失败"
20548
+ }, {
20549
+ timeout: 60000,
20550
+ retries: 2,
20551
+ retryDelay: 3000
20552
+ });
20553
+ if (0 !== pollRes.errCode) {
20554
+ logger.error(`[submitAndPollTranscode] 转码轮询失败 (poll ${pollCount}):`, JSON.stringify(pollRes));
20555
+ throw new Error(`转码轮询失败 (poll ${pollCount}): ${JSON.stringify(pollRes)}`);
20556
+ }
20557
+ const { flag, url, width, height, duration, md5, fileSize } = pollRes.data || {};
20558
+ if (1 === flag) {
20559
+ if (!url || !width || !height || !duration || !md5 || !fileSize) {
20560
+ logger.error("[submitAndPollTranscode] 转码完成但返回数据不完整:", JSON.stringify(pollRes.data));
20561
+ throw new Error(`转码完成但返回数据不完整: ${JSON.stringify(pollRes.data)}`);
20562
+ }
20563
+ logger.info(`[submitAndPollTranscode] 转码完成! 用时: ${pollCount * pollInterval / 1000}s`);
20564
+ return {
20565
+ clipKey,
20566
+ url,
20567
+ width,
20568
+ height,
20569
+ duration,
20570
+ md5,
20571
+ fileSize
20572
+ };
20573
+ }
20574
+ if (2 === flag) ;
20575
+ else {
20576
+ logger.error(`[submitAndPollTranscode] 转码失败,未知 flag=${flag}:`, JSON.stringify(pollRes.data));
20577
+ throw new Error(`转码失败,未知 flag=${flag}: ${JSON.stringify(pollRes.data)}`);
20578
+ }
20579
+ }
20580
+ logger.error(`[submitAndPollTranscode] 转码超时,已轮询 ${maxPolls} 次,用时: ${maxPolls * pollInterval / 1000}s`);
20581
+ throw new Error(`转码超时 (${maxPolls * pollInterval / 1000}s)`);
20582
+ }
20583
+ async function publishVideo(opts) {
20584
+ const { params, auth, client, clipResult, videoUpload, coverUpload, verticalCoverUpload, videoMeta, traceKey, tagKey, uploadStartTime, uploadEndTime, proxyHttp, logger } = opts;
20585
+ const toFinderUrl = (url)=>url.includes("wxapp.tc.qq.com") ? `https://finder.video.qq.com${url.split("qq.com")[1]}` : url;
20586
+ const thumbFinderUrl = toFinderUrl(coverUpload.downloadUrl);
20587
+ const coverFinderUrl = toFinderUrl(verticalCoverUpload.downloadUrl);
20588
+ const md5sumUuid = external_node_crypto_default().randomUUID();
20589
+ const description = params.description;
20590
+ const objectDesc = {
20591
+ mpTitle: "",
20592
+ description,
20593
+ extReading: buildExtReading(params.link),
20594
+ mediaType: 4,
20595
+ location: payload_buildLocation(params.location),
20596
+ topic: buildTopic({
20597
+ description: params.description,
20598
+ topics: params.topics,
20599
+ mentionedUsers: params.mentionedUsers,
20600
+ collection: params.collection
20601
+ }),
20602
+ event: buildEvent(params.event),
20603
+ mentionedUser: buildMentionedUser(params.mentionedUsers),
20604
+ media: [
20605
+ {
20606
+ url: clipResult.url,
20607
+ fileSize: clipResult.fileSize,
20608
+ thumbUrl: thumbFinderUrl,
20609
+ fullThumbUrl: thumbFinderUrl,
20610
+ coverUrl: coverFinderUrl,
20611
+ fullCoverUrl: coverFinderUrl,
20612
+ shareCoverUrl: coverFinderUrl,
20613
+ mediaType: 4,
20614
+ videoPlayLen: Math.round(clipResult.duration),
20615
+ width: clipResult.width,
20616
+ height: clipResult.height,
20617
+ md5sum: md5sumUuid,
20618
+ cardShowStyle: 2,
20619
+ urlCdnTaskId: clipResult.clipKey
20620
+ }
20621
+ ],
20622
+ shortTitle: params.title ? [
20623
+ {
20624
+ shortTitle: params.title
20625
+ }
20626
+ ] : [],
20627
+ member: {}
20628
+ };
20629
+ const publishData = {
20630
+ objectType: 0,
20631
+ longitude: 0,
20632
+ latitude: 0,
20633
+ feedLongitude: 0,
20634
+ feedLatitude: 0,
20635
+ originalFlag: params.originalFlag ?? 0,
20636
+ topics: params.topics || [],
20637
+ isFullPost: 1,
20638
+ handleFlag: 2,
20639
+ videoClipTaskId: clipResult.clipKey,
20640
+ traceInfo: {
20641
+ traceKey,
20642
+ uploadCdnStart: uploadStartTime,
20643
+ uploadCdnEnd: uploadEndTime
20644
+ },
20645
+ objectDesc,
20646
+ report: {
20647
+ clipKey: clipResult.clipKey,
20648
+ draftId: clipResult.clipKey,
20649
+ ...buildCommonBody(auth.finderUsername),
20650
+ height: videoMeta.height,
20651
+ width: videoMeta.width,
20652
+ duration: videoMeta.duration,
20653
+ fileSize: videoUpload.fileSize,
20654
+ uploadCost: (uploadEndTime - uploadStartTime) * 1000
20655
+ },
20656
+ postFlag: 0,
20657
+ mode: 1,
20658
+ clientid: external_node_crypto_default().randomUUID(),
20659
+ ...buildCommonBody(auth.finderUsername)
20660
+ };
20661
+ if (params.scheduledTime) publishData.effectiveTime = params.scheduledTime;
20662
+ if (params.tagInfo && tagKey) publishData.tagInfo = buildTagInfo(params.tagInfo, tagKey);
20663
+ const publishRes = await proxyHttp.api({
20664
+ method: "POST",
20665
+ url: `${MICRO_CONTENT_BASE}/post/post_create`,
20666
+ params: buildPublishQuery(client),
20667
+ data: publishData,
20668
+ defaultErrorMsg: "发布视频失败"
20669
+ });
20670
+ logger.info(`[publishVideo] 发布结果: errCode=${publishRes.errCode}, baseResp.errcode=${publishRes.data?.baseResp?.errcode}`);
20671
+ return publishRes;
20672
+ }
20673
+ function sleep(ms) {
20674
+ return new Promise((resolve)=>setTimeout(resolve, ms));
20675
+ }
20676
+ async function resolveLocalCoverPath(coverPath, label, tmpCachePath, logger) {
20677
+ if (!/^https?:\/\//i.test(coverPath)) return coverPath;
20678
+ const fileName = (0, share_namespaceObject.getFilenameFromUrl)(coverPath);
20679
+ const savePath = external_node_path_default().join(tmpCachePath, `${Date.now()}-${label}-${fileName}`);
20680
+ await (0, share_namespaceObject.downloadImage)(coverPath, savePath);
20681
+ return savePath;
20682
+ }
20683
+ const shipinhaoPublishVideo_mock_mockAction = async (task, params)=>{
20684
+ const updateTaskState = task.taskStageStore?.update?.bind(task.taskStageStore, task.taskId || "");
20685
+ let currentStep = "初始化";
20686
+ try {
20687
+ currentStep = "解析认证信息";
20688
+ const cookieString = params.cookies.map((c)=>`${c.name}=${c.value}`).join("; ");
20689
+ const http = new Http({
20690
+ headers: {
20691
+ cookie: cookieString
20692
+ }
20693
+ });
20694
+ currentStep = "验证发布参数";
20695
+ if (!params.videoPath) return (0, share_namespaceObject.response)(414, "视频文件路径不能为空", "");
20696
+ if (!params.coverPath) return (0, share_namespaceObject.response)(414, "横屏封面图片路径不能为空", "");
20697
+ currentStep = "获取上传认证";
20698
+ const auth = await getShipinhaoUploadAuth(cookieString, http);
20699
+ const client = resolveClientContext(params, auth.uin);
20700
+ const publishHeaders = buildPublishHeaders(cookieString, client);
20701
+ const microHttp = new Http({
20702
+ headers: publishHeaders
20703
+ });
20704
+ const args = [
20705
+ {
20706
+ headers: publishHeaders
20707
+ },
20708
+ task.logger,
20709
+ params.proxyLoc,
20710
+ params.accountId,
20711
+ "shipinhao"
20712
+ ];
20713
+ const proxyHttp = new Http(...args);
20714
+ currentStep = "组装视频元数据";
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
+ currentStep = "校验视频限制";
20718
+ const validationError = validateShipinhaoVideo(params.videoPath, videoMeta);
20719
+ if (validationError) {
20720
+ await updateTaskState?.({
20721
+ state: share_namespaceObject.TaskState.FAILED,
20722
+ error: validationError
20723
+ });
20724
+ return (0, share_namespaceObject.response)(414, validationError, "");
20725
+ }
20726
+ currentStep = "校验标题";
20727
+ const titleError = validateShipinhaoTitle(params.title);
20728
+ if (titleError) {
20729
+ await updateTaskState?.({
20730
+ state: share_namespaceObject.TaskState.FAILED,
20731
+ error: titleError
20732
+ });
20733
+ return (0, share_namespaceObject.response)(414, titleError, "");
20734
+ }
20735
+ currentStep = "获取 traceKey";
20736
+ const traceKey = await getTraceKey(auth, client, microHttp, task.logger);
20737
+ let tagKey = null;
20738
+ if (params.tagInfo) {
20739
+ currentStep = "获取内容声明 tagKey";
20740
+ tagKey = await getObjectTagKey(auth, client, microHttp, task.logger);
20741
+ }
20742
+ const uploadStartTime = Math.floor(Date.now() / 1000);
20743
+ currentStep = "上传视频";
20744
+ const videoUpload = await uploader_uploadFile({
20745
+ filePath: params.videoPath,
20746
+ fileType: auth.videoFileType,
20747
+ uin: auth.uin,
20748
+ authKey: auth.authKey,
20749
+ http,
20750
+ logger: task.logger
20751
+ });
20752
+ const uploadEndTime = Math.floor(Date.now() / 1000);
20753
+ task.logger.info(`[shipinhaoPublishVideo] 耗时: ${uploadEndTime - uploadStartTime}s`);
20754
+ currentStep = "上传横屏封面";
20755
+ const localCoverPath = await resolveLocalCoverPath(params.coverPath, "横屏封面", task.getTmpPath(), task.logger);
20756
+ const coverUpload = await uploader_uploadFile({
20757
+ filePath: localCoverPath,
20758
+ fileType: auth.pictureFileType,
20759
+ uin: auth.uin,
20760
+ authKey: auth.authKey,
20761
+ http,
20762
+ logger: task.logger
20763
+ });
20764
+ let verticalCoverUpload = coverUpload;
20765
+ if (params.verticalCoverPath) {
20766
+ currentStep = "上传竖屏封面";
20767
+ const localVerticalPath = await resolveLocalCoverPath(params.verticalCoverPath, "竖屏封面", task.getTmpPath(), task.logger);
20768
+ verticalCoverUpload = await uploader_uploadFile({
20769
+ filePath: localVerticalPath,
20770
+ fileType: auth.pictureFileType,
20771
+ uin: auth.uin,
20772
+ authKey: auth.authKey,
20773
+ http,
20774
+ logger: task.logger
20775
+ });
20776
+ }
20777
+ currentStep = "提交转码";
20778
+ const clipResult = await submitAndPollTranscode({
20779
+ videoUrl: videoUpload.downloadUrl,
20780
+ videoMeta,
20781
+ traceKey,
20782
+ uploadStartTime,
20783
+ uploadEndTime,
20784
+ finderUsername: auth.finderUsername,
20785
+ client,
20786
+ http: microHttp,
20787
+ logger: task.logger
20788
+ });
20789
+ currentStep = "发布视频";
20790
+ let publishResult;
20791
+ try {
20792
+ publishResult = await publishVideo({
20793
+ params,
20794
+ auth,
20795
+ client,
20796
+ clipResult,
20797
+ videoUpload,
20798
+ coverUpload,
20799
+ verticalCoverUpload,
20800
+ videoMeta,
20801
+ traceKey,
20802
+ tagKey,
20803
+ uploadStartTime,
20804
+ uploadEndTime,
20805
+ proxyHttp,
20806
+ logger: task.logger
20807
+ });
20808
+ } catch (error) {
20809
+ const handledError = Http.handleApiError(error);
20810
+ task.logger.error(`[shipinhaoPublishVideo] 发布请求失败: ${handledError.message}`, stringifyError(handledError));
20811
+ const classified = classifyPublishError(handledError);
20812
+ if (classified) {
20813
+ const message = `${classified.userMessage}${task.debug ? ` ${http.proxyInfo}` : ""}`;
20814
+ await updateTaskState?.({
20815
+ state: share_namespaceObject.TaskState.FAILED,
20816
+ error: message
20817
+ });
20818
+ return {
20819
+ code: 414,
20820
+ data: "",
20821
+ message
20822
+ };
20823
+ }
20824
+ throw error;
20825
+ }
20826
+ task.logger.info(`[shipinhaoPublishVideo] publishResult: ${JSON.stringify(publishResult)}`);
20827
+ const resultCode = publishResult.data?.baseResp?.errcode ?? publishResult.errCode;
20828
+ const resultMsg = publishResult.data?.baseResp?.errmsg ?? (0 === resultCode ? "发布成功" : `发布失败(errCode=${resultCode})`);
20829
+ if (0 === resultCode) {
20830
+ const publishId = extractEncFileKey(coverUpload.downloadUrl);
20831
+ if (!publishId) task.logger.error(`[shipinhaoPublishVideo] 封面 DownloadURL 中未解析到 encfilekey,关联 id 为空: ${coverUpload.downloadUrl}`);
20832
+ await updateTaskState?.({
20833
+ state: share_namespaceObject.TaskState.SUCCESS,
20834
+ result: {
20835
+ response: resultMsg
20836
+ }
20837
+ });
20838
+ reportLogger({
20839
+ token: params.huiwenToken || "",
20840
+ enverionment: task.enverionment || "development",
20841
+ postId: params.articleId,
20842
+ eip: proxyHttp.proxyInfo,
20843
+ accountId: params.accountId,
20844
+ uid: params.uid,
20845
+ publishParams: {
20846
+ videoPath: params.videoPath,
20847
+ coverPath: params.coverPath,
20848
+ verticalCoverPath: params.verticalCoverPath,
20849
+ title: params.title,
20850
+ topics: params.topics,
20851
+ mentionedUsers: params.mentionedUsers,
20852
+ collection: params.collection,
20853
+ event: params.event,
20854
+ link: params.link,
20855
+ tagInfo: params.tagInfo,
20856
+ originalFlag: params.originalFlag,
20857
+ scheduledTime: params.scheduledTime
20858
+ },
20859
+ platform: "shipinhao"
20860
+ });
20861
+ return (0, share_namespaceObject.response)(0, "发布成功", publishId);
20862
+ }
20863
+ let errorMessage = resultMsg;
20864
+ if (-11224 === resultCode) errorMessage = "视频号管理员完成实名且绑定手机号后才可以发表";
20865
+ else if (300333 === resultCode || 300334 === resultCode) errorMessage = "登录失效";
20866
+ else if (300330 === resultCode) errorMessage = "未登录";
20867
+ else if (300002 === resultCode) errorMessage = "官方平台在校验音乐/位置/定时信息时失败了,请重新编辑后发布";
20868
+ task.logger.error(`[shipinhaoPublishVideo] 发布失败: ${errorMessage} (errCode=${resultCode})`);
20869
+ await updateTaskState?.({
20870
+ state: share_namespaceObject.TaskState.FAILED,
20871
+ error: errorMessage
20872
+ });
20873
+ return (0, share_namespaceObject.response)(414, errorMessage, "");
20874
+ } catch (error) {
20875
+ const handledError = Http.handleApiError(error);
20876
+ const errorMsg = handledError.message || "发布失败,请稍后重试";
20877
+ task.logger.error(`[shipinhaoPublishVideo] 发布流程异常 [${currentStep}]: ${errorMsg}`, stringifyError(error), handledError.extra);
20878
+ await updateTaskState?.({
20879
+ state: share_namespaceObject.TaskState.FAILED,
20880
+ error: errorMsg
20881
+ });
20882
+ return (0, share_namespaceObject.response)(414, errorMsg, "");
20883
+ }
20884
+ };
20885
+ const shipinhaoPublishVideo_rpa_rpaAction = async (task, params)=>{
20886
+ task.logger.info("开始微信视频号视频发布(RPA 模式)");
20887
+ const videoMeta = buildVideoMetaFromParams(params.videoPath, params.videoMetadata);
20888
+ task.logger.info(`视频: ${videoMeta.width}×${videoMeta.height}, ${videoMeta.duration.toFixed(2)}s, ${(videoMeta.fileSize / 1024 / 1024).toFixed(2)}MB, codec=${videoMeta.codec || "unknown"}`);
20889
+ if (!videoMeta.codec) task.logger.warn("未能读取视频编码格式,跳过 H.264 预检,交由服务端判断");
20890
+ const validationError = validateShipinhaoVideo(params.videoPath, videoMeta);
20891
+ if (validationError) {
20892
+ task.logger.error(`视频校验未通过: ${validationError}`);
20893
+ return (0, share_namespaceObject.response)(414, validationError, "");
20894
+ }
20895
+ task.logger.info("视频校验通过");
20896
+ const titleError = validateShipinhaoTitle(params.title);
20897
+ if (titleError) {
20898
+ task.logger.error(`标题校验未通过: ${titleError}`);
20899
+ return (0, share_namespaceObject.response)(414, titleError, "");
20900
+ }
20901
+ const unsupported = [
20902
+ params.verticalCoverPath && "verticalCoverPath",
20903
+ params.collection && "collection",
20904
+ params.originalFlag && "originalFlag",
20905
+ params.postWithMemberZoneLink && "postWithMemberZoneLink"
20906
+ ].filter(Boolean);
20907
+ if (unsupported.length) task.logger.warn(`RPA 模式不支持以下参数,将被忽略: ${unsupported.join("、")};如需生效请使用 mockApi 模式`);
20908
+ if (params.tagInfo && 5 === params.tagInfo.tagType) {
20909
+ const shootInfo = params.tagInfo.shootInfo;
20910
+ if (shootInfo && (shootInfo.provinceCode || shootInfo.cityCode)) task.logger.warn("tagInfo.tagType=5 在 RPA 模式下仅支持拍摄时间和国家选择,省市选择需要使用 mockApi 模式");
20911
+ }
20912
+ const tmpCachePath = task.getTmpPath();
20913
+ const page = await task.createPage({
20914
+ url: "https://channels.weixin.qq.com/platform/post/create",
20915
+ show: task.debug,
20916
+ cookies: params.cookies
20917
+ });
20918
+ try {
20919
+ const waitForElement = async (selector, timeout = 10000)=>{
20920
+ try {
20921
+ const element = page.locator(selector);
20922
+ await element.waitFor({
20923
+ state: "visible",
20924
+ timeout
20925
+ });
20926
+ return element;
20927
+ } catch {
20928
+ task.logger.warn(`元素未找到: ${selector}`);
20929
+ return null;
20930
+ }
20931
+ };
20932
+ const retryAction = async (action, maxRetries = 3, delay = 1000)=>{
20933
+ let lastError;
20934
+ for(let i = 0; i < maxRetries; i++)try {
20935
+ return await action();
20936
+ } catch (error) {
20937
+ lastError = error;
20938
+ task.logger.warn(`重试 ${i + 1}/${maxRetries}: ${lastError.message}`);
20939
+ if (i < maxRetries - 1) await page.waitForTimeout(delay);
20940
+ }
20941
+ throw lastError;
20942
+ };
20943
+ task.logger.info("等待页面加载...");
20944
+ task.logger.info("检查登录状态...");
20945
+ if (task.debug) {
20946
+ task.logger.info(`当前页面 URL: ${page.url()}`);
20947
+ const title = await page.title();
20948
+ task.logger.info(`页面标题: ${title}`);
20949
+ }
20950
+ try {
20951
+ await page.waitForSelector(".post-edit-wrap", {
20952
+ state: "visible",
20953
+ timeout: 30000
20954
+ });
20955
+ task.logger.info("✓ 登录状态正常,找到编辑器容器");
20956
+ } catch {
20957
+ task.logger.error("✗ 未找到编辑器,可能登录失效");
20958
+ return {
20959
+ code: 414,
20960
+ message: "登录失效或页面加载异常",
20961
+ data: page.url()
20962
+ };
20963
+ }
20964
+ task.logger.info("页面加载完成,开始填充内容");
20965
+ task.logger.info("开始上传视频");
20966
+ await retryAction(async ()=>{
20967
+ const videoUploadSelectors = [
20968
+ '.ant-upload-btn input[type="file"][accept*="video"]',
20969
+ '.upload input[type="file"][accept*="video"]',
20970
+ 'input[type="file"][accept*="video"]'
20971
+ ];
20972
+ let uploadInput = null;
20973
+ if (task.debug) {
20974
+ const allFileInputs = await page.locator('input[type="file"]').count();
20975
+ task.logger.info(`页面中共找到 ${allFileInputs} 个文件上传输入框`);
20976
+ }
20977
+ for (const selector of videoUploadSelectors){
20978
+ const input = page.locator(selector);
20979
+ const count = await input.count();
20980
+ if (count > 0) {
20981
+ uploadInput = input.first();
20982
+ task.logger.info(`找到视频上传输入框: ${selector}`);
20983
+ break;
20984
+ }
20985
+ }
20986
+ if (!uploadInput) {
20987
+ task.logger.warn("未找到视频上传输入框,等待 3 秒后重试...");
20988
+ await page.waitForTimeout(3000);
20989
+ const anyFileInput = page.locator('input[type="file"]');
20990
+ const inputCount = await anyFileInput.count();
20991
+ if (inputCount > 0) {
20992
+ uploadInput = anyFileInput.first();
20993
+ task.logger.info(`找到文件输入框(共 ${inputCount} 个)`);
20994
+ } else {
20995
+ if (task.debug) {
20996
+ const screenshotPath = external_node_path_default().join(tmpCachePath, `upload-error-${Date.now()}.png`);
20997
+ await page.screenshot({
20998
+ path: screenshotPath,
20999
+ fullPage: true
21000
+ });
21001
+ task.logger.error(`未找到上传输入框,已截图保存至: ${screenshotPath}`);
21002
+ }
21003
+ throw new Error("未找到视频上传输入框");
21004
+ }
21005
+ }
21006
+ await uploadInput.setInputFiles(params.videoPath);
21007
+ task.logger.info("视频上传成功");
21008
+ await page.waitForTimeout(5000);
21009
+ });
21010
+ if (params.coverPath) {
21011
+ task.logger.info("开始上传封面");
21012
+ await retryAction(async ()=>{
21013
+ const coverUploadBtn = await waitForElement(".cover-upload-btn", 10000);
21014
+ if (coverUploadBtn) {
21015
+ const coverInput = page.locator('.cover-upload-btn input[type="file"]');
21016
+ await coverInput.setInputFiles(params.coverPath);
21017
+ task.logger.info("封面上传成功");
21018
+ await page.waitForTimeout(2000);
21019
+ }
21020
+ });
21021
+ }
21022
+ const descriptionText = payload_buildDescription({
21023
+ description: params.description,
21024
+ topics: params.topics,
21025
+ mentionedUsers: params.mentionedUsers
21026
+ });
21027
+ if (descriptionText) {
21028
+ task.logger.info("填写视频描述");
21029
+ await retryAction(async ()=>{
21030
+ const descEditor = await waitForElement(".input-editor", 10000);
21031
+ if (!descEditor) throw new Error("未找到描述编辑器");
21032
+ await descEditor.click();
21033
+ await page.waitForTimeout(500);
21034
+ await descEditor.evaluate((el)=>{
21035
+ el.textContent = "";
21036
+ });
21037
+ await page.waitForTimeout(300);
21038
+ task.logger.info("已清空编辑器内容");
21039
+ await descEditor.pressSequentially(descriptionText, {
21040
+ delay: 10
21041
+ });
21042
+ await page.waitForTimeout(500);
21043
+ task.logger.info("描述填写完成");
21044
+ });
21045
+ }
21046
+ if (params.title) {
21047
+ task.logger.info(`填写标题: ${params.title}`);
21048
+ const title = params.title;
21049
+ await retryAction(async ()=>{
21050
+ const titleInput = await waitForElement("#container-wrap div.form-item-body.short-title-wrap input", 10000);
21051
+ if (!titleInput) throw new Error("未找到标题输入框");
21052
+ await titleInput.click();
21053
+ await titleInput.clear({
21054
+ timeout: 3000
21055
+ });
21056
+ await titleInput.fill(title, {
21057
+ timeout: 5000
21058
+ });
21059
+ task.logger.info("标题填写完成");
21060
+ });
21061
+ }
21062
+ if (params.location) {
21063
+ task.logger.info(`选择地点: ${params.location.city}`);
21064
+ const instance = page.locator(".position-display-wrap");
21065
+ await instance.click();
21066
+ await page.waitForTimeout(1000);
21067
+ await page.locator(".location-filter-wrap input").fill(params.location.city);
21068
+ await page.waitForTimeout(2000);
21069
+ const poperInstance = page.locator(".location-filter-wrap .common-option-list-wrap .option-item");
21070
+ await poperInstance.nth(1).waitFor();
21071
+ await poperInstance.nth(1).click();
21072
+ task.logger.info("地点选择完成");
21073
+ }
21074
+ if (params.collection) {
21075
+ task.logger.info(`选择合集: ${params.collection.collectionName}`);
21076
+ const instanceCollection = page.locator(".post-album-display-wrap");
21077
+ await instanceCollection.click();
21078
+ await page.waitForTimeout(1000);
21079
+ page.locator(".post-album-wrap .option-item").filter({
21080
+ hasText: params.collection.collectionName
21081
+ }).first().click({
21082
+ force: true
21083
+ });
21084
+ }
21085
+ if (params.link) {
21086
+ task.logger.info(`设置扩展阅读链接: ${params.link.title}`);
21087
+ await page.locator(".post-link-wrap .link-display-wrap").click();
21088
+ await page.waitForTimeout(300);
21089
+ const linkTypeText = 2 === params.link.urlType ? "红包封面" : "公众号文章";
21090
+ await page.locator(".link-option-item .title-wrap span").filter({
21091
+ hasText: linkTypeText
21092
+ }).click();
21093
+ await page.waitForTimeout(300);
21094
+ const placeholder = 2 === params.link.urlType ? "粘贴红包封面链接" : "粘贴公众号文章链接";
21095
+ await page.locator(`.link-input-wrap input[placeholder="${placeholder}"]`).fill(params.link.link);
21096
+ await page.waitForTimeout(500);
21097
+ task.logger.info(`已设置${linkTypeText}: ${params.link.link}`);
21098
+ }
21099
+ if (params.event) {
21100
+ task.logger.info(`选择活动: ${params.event.eventName}`);
21101
+ await page.locator(".post-activity-wrap .activity-display").click();
21102
+ await page.waitForTimeout(500);
21103
+ await page.locator(".activity-filter-wrap .weui-desktop-form__input[placeholder='搜索活动']").fill(params.event.eventName);
21104
+ await page.waitForTimeout(500);
21105
+ const searchLoading = page.locator(".search-loading");
21106
+ await searchLoading.waitFor({
21107
+ state: "hidden",
21108
+ timeout: 5000
21109
+ }).catch(()=>{
21110
+ task.logger.warn("活动搜索加载超时,继续尝试选择");
21111
+ });
21112
+ const activityItem = page.locator(".option-item .activity-item .activity-item-info .name").filter({
21113
+ hasText: params.event.eventName
21114
+ });
21115
+ const count = await activityItem.count();
21116
+ if (count > 0) {
21117
+ await activityItem.first().click();
21118
+ await page.waitForTimeout(300);
21119
+ task.logger.info(`已选择活动: ${params.event.eventName}`);
21120
+ } else {
21121
+ task.logger.warn(`未找到活动: ${params.event.eventName},将不参与活动`);
21122
+ await page.locator(".post-activity-wrap .activity-display").click();
21123
+ await page.waitForTimeout(300);
21124
+ }
21125
+ }
21126
+ if (params.scheduledTime) {
21127
+ task.logger.info("设置定时发布");
21128
+ const timingRadio = page.locator(".weui-desktop-form__check-label").filter({
21129
+ hasNotText: "不定时"
21130
+ }).first();
21131
+ await timingRadio.click();
21132
+ await page.waitForTimeout(500);
21133
+ const instance = page.locator(".weui-desktop-picker__date");
21134
+ await instance.click();
21135
+ const dateD = utils_TimeFormatter.format(1000 * params.scheduledTime, "d");
21136
+ const nowMonth = utils_TimeFormatter.format(Date.now(), "MM月");
21137
+ const nowMonthText = utils_TimeFormatter.format(Date.now(), "M月");
21138
+ const month = utils_TimeFormatter.format(1000 * params.scheduledTime, "MM月");
21139
+ const monthLocator = await page.locator("weui-desktop-picker__panel__label").filter({
21140
+ hasText: month
21141
+ }).first();
21142
+ if (!monthLocator) {
21143
+ await page.locator(".weui-desktop-picker__panel__label").filter({
21144
+ hasText: nowMonth
21145
+ }).first().click();
21146
+ await page.waitForTimeout(500);
21147
+ await page.locator(".weui-desktop-picker__table-row td a").filter({
21148
+ hasText: nowMonthText
21149
+ }).first().click();
21150
+ }
21151
+ await page.waitForTimeout(500);
21152
+ await page.locator(".weui-desktop-picker__table-row td a").filter({
21153
+ hasText: dateD
21154
+ }).first().click();
21155
+ await page.locator(".weui-desktop-form__input-wrp input[placeholder*='请选择时间']").fill(utils_TimeFormatter.format(1000 * params.scheduledTime, "hh:mm"));
21156
+ await page.locator("i.weui-desktop-icon__time").click();
21157
+ await page.locator(".post-time-wrap .form-item .label").filter({
21158
+ hasText: "发表时间"
21159
+ }).click();
21160
+ }
21161
+ if (params.tagInfo) {
21162
+ task.logger.info(`设置视频标注: tagType=${params.tagInfo.tagType}`);
21163
+ await page.locator(".mark-tag-select").click();
21164
+ await page.waitForTimeout(300);
21165
+ const tagTypeTextMap = {
21166
+ 0: "无需标注",
21167
+ 1: "含AI生成内容",
21168
+ 2: "内容包含营销广告",
21169
+ 3: "内容为虚构剧情,仅供娱乐",
21170
+ 5: "内容为自行拍摄",
21171
+ 7: "内容为转载",
21172
+ 8: "个人观点,仅供参考"
21173
+ };
21174
+ const tagText = tagTypeTextMap[params.tagInfo.tagType];
21175
+ if (tagText) {
21176
+ await page.locator(".mark-tag-option .option-main").filter({
21177
+ hasText: tagText
21178
+ }).click();
21179
+ await page.waitForTimeout(300);
21180
+ if (5 === params.tagInfo.tagType) {
21181
+ const shootInfo = params.tagInfo.shootInfo;
21182
+ if (shootInfo) {
21183
+ task.logger.info("填写拍摄时间和地点...");
21184
+ await page.waitForTimeout(500);
21185
+ if (shootInfo.postTimestamp) {
21186
+ task.logger.info(`设置拍摄时间: ${shootInfo.postTimestamp}`);
21187
+ const timestamp = 1000 * parseInt(shootInfo.postTimestamp, 10);
21188
+ const date = new Date(timestamp);
21189
+ await page.locator(".original-dialog-content .weui-desktop-picker__date input[placeholder*='请选择拍摄时间']").click();
21190
+ await page.waitForTimeout(300);
21191
+ const dayNum = date.getDate();
21192
+ await page.locator(".weui-desktop-picker__table a").filter({
21193
+ hasText: new RegExp(`^\\s*${dayNum}\\s*$`)
21194
+ }).first().click();
21195
+ await page.waitForTimeout(300);
21196
+ }
21197
+ if (shootInfo.countryCode || shootInfo.provinceCode || shootInfo.cityCode) {
21198
+ task.logger.info("设置拍摄地点...");
21199
+ await page.locator(".original-dialog-content .weui-desktop-form__dropdowncascade .weui-desktop-form__dropdowncascade__dt").click();
21200
+ await page.waitForTimeout(300);
21201
+ if (1156 === shootInfo.countryCode) {
21202
+ await page.locator(".weui-desktop-dropdown__list-ele .weui-desktop-dropdown__list-ele__text").filter({
21203
+ hasText: "中国"
21204
+ }).click();
21205
+ await page.waitForTimeout(300);
21206
+ task.logger.warn("RPA 模式下暂不支持选择具体省份和城市,仅选择了国家");
21207
+ } else task.logger.warn(`不支持的国家代码: ${shootInfo.countryCode},跳过地点设置`);
21208
+ }
21209
+ const confirmBtn = await waitForElement(".weui-desktop-dialog .weui-desktop-btn_primary");
21210
+ if (confirmBtn) {
21211
+ await confirmBtn.click();
21212
+ await page.waitForTimeout(300);
21213
+ }
21214
+ } else task.logger.warn("tagType=5 需要提供 shootInfo 字段(拍摄时间和地点)");
21215
+ }
21216
+ if (7 === params.tagInfo.tagType) {
21217
+ const repostSource = params.tagInfo.repostSource;
21218
+ if (repostSource) {
21219
+ task.logger.info(`填写转载来源: ${repostSource}`);
21220
+ await page.waitForTimeout(500);
21221
+ await page.locator(".repost-dialog-content .repost-textarea").fill(repostSource);
21222
+ await page.waitForTimeout(300);
21223
+ const confirmBtn = await waitForElement(".weui-desktop-dialog .weui-desktop-btn_primary");
21224
+ if (confirmBtn) {
21225
+ await confirmBtn.click();
21226
+ await page.waitForTimeout(300);
21227
+ }
21228
+ } else task.logger.warn("tagType=7 需要提供 repostSource 字段(转载来源)");
21229
+ }
21230
+ } else task.logger.warn(`未知的 tagType: ${params.tagInfo.tagType},跳过标注设置`);
21231
+ }
21232
+ task.logger.info("准备发布...");
21233
+ await page.waitForTimeout(500);
21234
+ let videoId = "";
21235
+ const handleResponse = async (response)=>{
21236
+ const url = response.url();
21237
+ if (url.includes("/post/post_create")) {
21238
+ const jsonResponse = await response.json();
21239
+ page.off("response", handleResponse);
21240
+ videoId = jsonResponse.object?.id || jsonResponse.data?.objectId || "";
21241
+ }
21242
+ };
21243
+ page.on("response", handleResponse);
21244
+ task._timerRecord.PrePublish = Date.now();
21245
+ 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";
21246
+ task.logger.info("等待视频上传完成(预览区媒体操作栏出现)...");
21247
+ const uploadTimeout = 600000;
21248
+ const uploadWaitStart = Date.now();
21249
+ let lastProgressLog = 0;
21250
+ while(true){
21251
+ const ready = await page.evaluate((selector)=>{
21252
+ const host = document.querySelector("#container-wrap > div.container-center > div > wujie-app");
21253
+ const root = host?.shadowRoot;
21254
+ if (!root) return false;
21255
+ return !!root.querySelector(selector);
21256
+ }, MEDIA_OPR_SELECTOR);
21257
+ if (ready) break;
21258
+ const elapsed = Date.now() - uploadWaitStart;
21259
+ if (elapsed > uploadTimeout) throw new Error(`视频上传超时,预览区未就绪(已等待 ${Math.round(elapsed / 1000)}s)`);
21260
+ if (elapsed - lastProgressLog >= 15000) {
21261
+ lastProgressLog = elapsed;
21262
+ task.logger.info(`视频仍在上传中... 已等待 ${Math.round(elapsed / 1000)}s`);
21263
+ }
21264
+ await page.waitForTimeout(1000);
21265
+ }
21266
+ task.logger.info(`视频上传完成(等待 ${Math.round((Date.now() - uploadWaitStart) / 1000)}s)`);
21267
+ const clicked = await page.evaluate(()=>{
21268
+ const host = document.querySelector("#container-wrap > div.container-center > div > wujie-app");
21269
+ const root = host?.shadowRoot;
21270
+ if (!root) return "未找到 wujie-app shadowRoot";
21271
+ const btns = Array.from(root.querySelectorAll(".form-btns .weui-desktop-btn"));
21272
+ const target = btns.find((el)=>(el.textContent || "").includes("发表"));
21273
+ if (!target) return "未找到发表按钮";
21274
+ if (target.classList.contains("weui-desktop-btn_disabled")) return "发表按钮仍处于禁用状态";
21275
+ target.click();
21276
+ return null;
21277
+ });
21278
+ if (clicked) throw new Error(clicked);
21279
+ task.logger.info("已点击发布按钮,等待响应...");
21280
+ try {
21281
+ await page.waitForURL((url)=>url.href !== page.url(), {
21282
+ timeout: 30000
21283
+ });
21284
+ task.logger.info(`发布成功,页面已跳转: ${page.url()}`);
21285
+ } catch {
21286
+ task.logger.warn("等待页面跳转超时,可能发布失败或网络慢,继续关闭页面");
21287
+ }
21288
+ await page.close();
21289
+ return (0, share_namespaceObject.success)(videoId, "发布成功");
21290
+ } catch (error) {
21291
+ let errorMsg = error instanceof Error ? error.message : String(error);
21292
+ if (errorMsg.includes("context or browser has been closed")) errorMsg = "浏览器上下文已被关闭";
21293
+ task.logger.error(`微信视频号视频发布失败: ${errorMsg}`);
21294
+ return (0, share_namespaceObject.response)(414, `微信视频号视频发布失败: ${errorMsg}`, "");
21295
+ }
21296
+ };
21297
+ const ShipinhaoPublishVideoParamsSchema = ActionCommonParamsSchema.extend({
21298
+ videoPath: schemas_string().min(1),
21299
+ videoMetadata: schemas_object({
21300
+ duration: schemas_number().positive(),
21301
+ width: schemas_number().int().positive(),
21302
+ height: schemas_number().int().positive(),
21303
+ fileSize: schemas_number().int().positive(),
21304
+ path: schemas_string().min(1).optional(),
21305
+ fileName: schemas_string().min(1)
21306
+ }),
21307
+ coverPath: schemas_string().min(1),
21308
+ verticalCoverPath: schemas_string().min(1).optional(),
21309
+ description: schemas_string(),
21310
+ title: schemas_string().optional(),
21311
+ scheduledTime: schemas_number().int().positive().optional(),
21312
+ isImmediatelyPublish: schemas_boolean().optional(),
21313
+ topics: schemas_array(schemas_string()).optional(),
21314
+ mentionedUsers: schemas_array(schemas_object({
21315
+ nickname: schemas_string()
21316
+ })).optional(),
21317
+ collection: schemas_object({
21318
+ collectionId: schemas_string(),
21319
+ collectionName: schemas_string()
21320
+ }).optional(),
21321
+ event: schemas_object({
21322
+ eventTopicId: schemas_string(),
21323
+ eventName: schemas_string(),
21324
+ eventCreatorNickname: schemas_string().optional()
21325
+ }).optional(),
21326
+ link: schemas_object({
21327
+ link: schemas_string(),
21328
+ title: schemas_string(),
21329
+ urlType: schemas_number().int().default(1)
21330
+ }).optional(),
21331
+ tagInfo: looseObject({
21332
+ tagType: schemas_number().int()
21333
+ }).optional(),
21334
+ originalFlag: union([
21335
+ literal(0),
21336
+ literal(1)
21337
+ ]).optional(),
21338
+ postWithMemberZoneLink: union([
21339
+ literal(0),
21340
+ literal(1)
21341
+ ]).optional(),
21342
+ location: schemas_object({
21343
+ latitude: schemas_number(),
21344
+ longitude: schemas_number(),
21345
+ city: schemas_string(),
21346
+ poiName: schemas_string().optional(),
21347
+ address: schemas_string().optional(),
21348
+ poiClassifyId: schemas_string().optional()
21349
+ }).optional()
21350
+ });
21351
+ const shipinhaoPublishVideo = async (task, params)=>{
21352
+ task.logger.info(`[shipinhaoPublishVideo] actionType: ${params.actionType}`);
21353
+ if ("rpa" === params.actionType) return shipinhaoPublishVideo_rpa_rpaAction(task, params);
21354
+ if ("mockApi" === params.actionType) return shipinhaoPublishVideo_mock_mockAction(task, params);
21355
+ return executeAction(shipinhaoPublishVideo_mock_mockAction, shipinhaoPublishVideo_rpa_rpaAction)(task, params);
21356
+ };
21357
+ const ShipinhaoSendMsgParamsSchema = ActionCommonParamsSchema.extend({
21358
+ toUsername: schemas_string().min(1, "接收者用户名不能为空"),
21359
+ sessionId: schemas_string().min(1, "会话ID不能为空"),
21360
+ msgType: schemas_enum([
21361
+ "TEXT",
21362
+ "IMAGE"
21363
+ ], {
21364
+ message: "消息类型必须是 TEXT 或 IMAGE"
21365
+ }),
21366
+ content: schemas_string().optional(),
21367
+ imageInfo: schemas_object({
21368
+ pathOrUrl: schemas_string().min(1, "图片路径或URL不能为空")
21369
+ }).optional()
21370
+ });
21371
+ const shipinhaoSendMsg_CHUNK_SIZE = 524288;
21372
+ async function shipinhaoSendMsg_getUserInfo(cookieStr, http) {
21373
+ const url = `https://channels.weixin.qq.com/cgi-bin/mmfinderassistant-bin/auth/auth_data?_rid=${rid()}`;
21374
+ const headers = {
21375
+ referer: "https://channels.weixin.qq.com/micro/interaction/private_msg",
21376
+ cookie: cookieStr,
21377
+ Origin: "https://channels.weixin.qq.com"
21378
+ };
21379
+ return await http.api({
21380
+ method: "get",
21381
+ url,
21382
+ headers
21383
+ }, {
21384
+ retries: 3,
21385
+ retryDelay: 1000,
21386
+ timeout: 10000
21387
+ });
21388
+ }
21389
+ const shipinhaoSendMsg = async (_task, params)=>{
21390
+ if (!params.sessionId) return (0, share_namespaceObject.response)(414, "sessionId 不能为空", void 0);
21391
+ if (!params.toUsername) return (0, share_namespaceObject.response)(414, "接收者用户名不能为空", void 0);
21392
+ if (!params.msgType) return (0, share_namespaceObject.response)(414, "消息类型不能为空", void 0);
21393
+ if (![
21394
+ "TEXT",
21395
+ "IMAGE"
21396
+ ].includes(params.msgType)) return (0, share_namespaceObject.response)(414, "消息类型必须是 TEXT 或 IMAGE", void 0);
21397
+ if ("TEXT" === params.msgType) {
21398
+ if (!params.content || "" === params.content.trim()) return (0, share_namespaceObject.response)(414, "消息内容不能为空", void 0);
21399
+ }
21400
+ if ("IMAGE" === params.msgType) {
21401
+ if (!params.imageInfo?.pathOrUrl) return (0, share_namespaceObject.response)(414, "图片路径或URL不能为空", void 0);
21402
+ }
21403
+ if (!params.extraParam) return (0, share_namespaceObject.response)(414, "缺少 extraParam 参数", void 0);
21404
+ if (!params.extraParam.fingerPrintDeviceId || !params.extraParam.aId || !params.extraParam.uin) return (0, share_namespaceObject.response)(414, "fingerPrintDeviceId、aId 和 uin 不能为空", void 0);
21405
+ const cookieStr = params.cookies.map((it)=>`${it.name}=${it.value}`).join(";");
21406
+ const headers = {
21407
+ cookie: cookieStr,
21408
+ referer: "https://channels.weixin.qq.com/micro/interaction/private_msg",
21409
+ origin: "https://channels.weixin.qq.com",
21410
+ "content-type": "application/json",
21411
+ "finger-print-device-id": params.extraParam.fingerPrintDeviceId,
21412
+ "x-wechat-uin": params.extraParam.uin
21413
+ };
21414
+ const http = new Http({
21415
+ headers
21416
+ });
21417
+ const urlParams = new URLSearchParams({
21418
+ _aid: params.extraParam.aId,
21419
+ _rid: rid(),
21420
+ _pageUrl: "https://channels.weixin.qq.com/micro/interaction/private_msg"
21421
+ }).toString();
21422
+ const generateCliMsgId = ()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (s)=>{
21423
+ const t = 16 * Math.random() | 0;
21424
+ return ("x" === s ? t : 3 & t | 8).toString(16);
21425
+ });
21426
+ let fromUsername = params.extraParam.finderUserName;
21427
+ if (!fromUsername) {
21428
+ _task.logger.info("未提供 finderUserName,尝试获取用户信息");
21429
+ const userInfoRes = await shipinhaoSendMsg_getUserInfo(cookieStr, http);
21430
+ if (!userInfoRes.data?.finderUser?.finderUsername) return (0, share_namespaceObject.response)(userInfoRes.errCode || -1, userInfoRes.errMsg || "获取用户信息失败", {});
21431
+ fromUsername = userInfoRes.data.finderUser.finderUsername;
21432
+ _task.logger.info(`获取到用户名: ${fromUsername}`);
21433
+ }
21434
+ let imgMsg;
21435
+ if ("IMAGE" === params.msgType) {
21436
+ let imageBuffer;
21437
+ const imagePath = params.imageInfo.pathOrUrl;
21438
+ try {
21439
+ if (imagePath.startsWith("http://") || imagePath.startsWith("https://")) {
21440
+ const resp = await external_axios_default().get(imagePath, {
21441
+ responseType: "arraybuffer"
21442
+ });
21443
+ imageBuffer = Buffer.from(resp.data);
21444
+ } else {
21445
+ const filePath = imagePath.startsWith("file://") ? imagePath.slice(7) : imagePath;
21446
+ imageBuffer = Buffer.from(await external_node_fs_default().promises.readFile(filePath));
21447
+ }
21448
+ } catch (err) {
21449
+ _task.logger.error(`读取图片失败: ${err instanceof Error ? err.message : String(err)}`);
21450
+ return (0, share_namespaceObject.response)(414, USER_MESSAGE.IMAGE_UPLOAD_FAILED, void 0);
21451
+ }
21452
+ const md5 = (0, external_node_crypto_namespaceObject.createHash)("md5").update(imageBuffer).digest("hex");
21453
+ const timestamp = Date.now().toString();
21454
+ const totalChunks = Math.ceil(imageBuffer.length / shipinhaoSendMsg_CHUNK_SIZE);
21455
+ console.log(`分片上传md5${md5}`);
21456
+ let lastRes;
21457
+ for(let i = 0; i < totalChunks; i++){
21458
+ const chunkBuffer = imageBuffer.slice(i * shipinhaoSendMsg_CHUNK_SIZE, (i + 1) * shipinhaoSendMsg_CHUNK_SIZE);
21459
+ const requestData = {
21460
+ content: `data:application/octet-stream;base64,${chunkBuffer.toString("base64")}`,
21461
+ chunk: i,
21462
+ chunks: totalChunks,
21463
+ fromUsername,
21464
+ toUsername: params.toUsername,
21465
+ aesKey: "U2FsdGVkX18cwrWR73LMGhBcmAX8xoNTgbmgkZBYkEs=",
21466
+ mediaSize: imageBuffer.length,
21467
+ mediaType: 3,
21468
+ md5,
21469
+ timestamp,
21470
+ _log_finder_uin: "",
21471
+ _log_finder_id: params.extraParam.finderUserName || "",
21472
+ rawKeyBuff: null,
21473
+ pluginSessionId: null,
21474
+ scene: 7,
21475
+ reqScene: 7
21476
+ };
21477
+ lastRes = await http.api({
21478
+ method: "post",
21479
+ url: `https://channels.weixin.qq.com/micro/interaction/cgi-bin/mmfinderassistant-bin/private-msg/upload-media-info?${urlParams}`,
21480
+ data: requestData
21481
+ });
21482
+ console.log(`分片上传 ${i + 1}/${totalChunks} 响应:`, lastRes);
21483
+ if (lastRes?.errCode !== 0 && i < totalChunks - 1) return (0, share_namespaceObject.response)(414, lastRes?.errMsg || `第 ${i + 1}/${totalChunks} 分片上传失败`, void 0);
21484
+ }
21485
+ if (lastRes?.errCode !== 0) return (0, share_namespaceObject.response)(414, lastRes?.errMsg || "上传图片失败", void 0);
21486
+ const uploadedImgMsg = lastRes.data?.imgMsg;
21487
+ imgMsg = {
21488
+ aeskey: uploadedImgMsg.aesKey ?? uploadedImgMsg.aeskey,
21489
+ url: uploadedImgMsg.cdnUrl ?? uploadedImgMsg.url,
21490
+ hdSize: uploadedImgMsg.hdSize ?? uploadedImgMsg.size,
21491
+ midSize: uploadedImgMsg.midSize ?? uploadedImgMsg.size,
21492
+ thumbSize: uploadedImgMsg.thumbSize ?? uploadedImgMsg.size,
21493
+ thumbHeight: uploadedImgMsg.thumbHeight ?? uploadedImgMsg.height,
21494
+ thumbWidth: uploadedImgMsg.thumbWidth ?? uploadedImgMsg.width,
21495
+ md5: uploadedImgMsg.md5
21496
+ };
21497
+ }
21498
+ console.log("发送私信请求参数1111", {
21499
+ sessionId: params.sessionId,
21500
+ fromUsername
21501
+ });
21502
+ const sendRes = await http.api({
21503
+ method: "post",
21504
+ url: `https://channels.weixin.qq.com/micro/interaction/cgi-bin/mmfinderassistant-bin/private-msg/send-private-msg?${urlParams}`,
21505
+ data: {
21506
+ timestamp: Date.now().toString(),
21507
+ _log_finder_uin: "",
21508
+ _log_finder_id: params.extraParam.finderUserName || "",
21509
+ rawKeyBuff: null,
21510
+ pluginSessionId: null,
21511
+ scene: 7,
21512
+ reqScene: 7,
21513
+ msgPack: {
21514
+ sessionId: params.sessionId,
21515
+ fromUsername,
21516
+ toUsername: params.toUsername,
19678
21517
  cliMsgId: generateCliMsgId(),
19679
21518
  msgType: "TEXT" === params.msgType ? 1 : 3,
19680
21519
  imgMsg: "IMAGE" === params.msgType ? imgMsg : void 0,
@@ -20069,6 +21908,13 @@ var __webpack_exports__ = {};
20069
21908
  const uploadImages = async (images)=>await Promise.all(images.map(async (url)=>{
20070
21909
  const fileName = (0, share_namespaceObject.getFilenameFromUrl)(url);
20071
21910
  const image = await (0, share_namespaceObject.downloadImage)(url, external_node_path_default().join(tmpCachePath, fileName));
21911
+ const stats = external_node_fs_default().statSync(image);
21912
+ const maxSize = 20971520;
21913
+ if (stats.size > maxSize) throw {
21914
+ code: 414,
21915
+ message: "头条号平台:单张图片不得超过 20MB",
21916
+ data: ""
21917
+ };
20072
21918
  const formData = new (external_form_data_default())();
20073
21919
  formData.append("image", external_node_fs_default().createReadStream(image));
20074
21920
  const response = await http.api({
@@ -22119,18 +23965,10 @@ var __webpack_exports__ = {};
22119
23965
  });
22120
23966
  } catch (error) {
22121
23967
  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));
23968
+ const classified = classifyPublishError(handledError);
23969
+ if (classified) {
23970
+ const message = `${classified.userMessage}${task.debug ? ` ${http.proxyInfo}` : ""}`;
23971
+ task.logger.error(`[weixinPublish] ${classified.category},直接返回: ${handledError.message} (code=${handledError.code})`, stringifyError(handledError));
22134
23972
  await updateTaskState?.({
22135
23973
  state: share_namespaceObject.TaskState.FAILED,
22136
23974
  error: message
@@ -23360,6 +25198,12 @@ var __webpack_exports__ = {};
23360
25198
  const fileName = (0, share_namespaceObject.getFilenameFromUrl)(url);
23361
25199
  const localUrl = await (0, share_namespaceObject.downloadImage)(url, external_node_path_default().join(tmpCachePath, fileName));
23362
25200
  const fileBuffer = external_node_fs_default().readFileSync(localUrl);
25201
+ const maxSize = 33554432;
25202
+ if (fileBuffer.byteLength > maxSize) throw {
25203
+ code: 414,
25204
+ message: "小红书平台:单张图片不得超过 32MB",
25205
+ data: ""
25206
+ };
23363
25207
  let width = 0;
23364
25208
  let height = 0;
23365
25209
  try {
@@ -23598,6 +25442,7 @@ var __webpack_exports__ = {};
23598
25442
  });
23599
25443
  return (0, share_namespaceObject.success)(data, message);
23600
25444
  }
25445
+ task.logger.info(`[xiaohongshuPublish] publishData: ${JSON.stringify(publishData)} `);
23601
25446
  let publishResult;
23602
25447
  try {
23603
25448
  publishResult = await proxyHttp.api({
@@ -23608,23 +25453,15 @@ var __webpack_exports__ = {};
23608
25453
  defaultErrorMsg: "文章发布异常,请稍后重试。"
23609
25454
  }, {
23610
25455
  retries: 2,
23611
- retryDelay: 500,
23612
- timeout: 12000
25456
+ retryDelay: 3000,
25457
+ timeout: 30000
23613
25458
  });
23614
25459
  } catch (error) {
23615
25460
  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));
25461
+ const classified = classifyPublishError(handledError);
25462
+ if (classified) {
25463
+ const message = `${classified.userMessage}${task.debug ? ` ${http.proxyInfo}` : ""}`;
25464
+ task.logger.error(`[xiaohongshuPublish] ${classified.category},直接返回: ${handledError.message} (code=${handledError.code})`, stringifyError(handledError));
23628
25465
  await updateTaskState?.({
23629
25466
  state: share_namespaceObject.TaskState.FAILED,
23630
25467
  error: message
@@ -25320,6 +27157,14 @@ var __webpack_exports__ = {};
25320
27157
  this.task = task;
25321
27158
  this.task.logger.info(`当前包版本:Share=>${package_json_default().version} Action=>${package_namespaceObject.i8}`);
25322
27159
  }
27160
+ getActionVersionMarker() {
27161
+ return {
27162
+ version: package_namespaceObject.i8,
27163
+ shareVersion: package_json_default().version,
27164
+ marker: `Action_${package_namespaceObject.i8}_${package_json_default().version}`,
27165
+ timestamp: new Date().toLocaleString()
27166
+ };
27167
+ }
25323
27168
  async bindTask(func, params) {
25324
27169
  let responseData;
25325
27170
  this.task.isBeta = this.task?.isFeatOn ? this.task?.isFeatOn(BetaFlag) : false;
@@ -25543,6 +27388,9 @@ var __webpack_exports__ = {};
25543
27388
  shipinhaoPublish(params) {
25544
27389
  return this.bindTask(shipinhaoPublish, params);
25545
27390
  }
27391
+ shipinhaoPublishVideo(params) {
27392
+ return this.bindTask(shipinhaoPublishVideo, params);
27393
+ }
25546
27394
  douyinGetTopics(params) {
25547
27395
  return this.bindTask(douyinGetTopics, params);
25548
27396
  }
@@ -25603,4 +27451,4 @@ if (__webpack_exports__.__esModule) Object.defineProperty(__webpack_export_targe
25603
27451
  });
25604
27452
 
25605
27453
  //# sourceMappingURL=index.js.map
25606
- //# debugId=4505f4f9-b586-5fae-8a9f-3ce0ceb72967
27454
+ //# debugId=8315ee33-ea9b-5a8e-92af-cf3835f6ed70