@iflyrpa/actions 4.0.9 → 4.1.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs 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]="b0f81db0-8823-5f32-bb7c-d4b4fe6dea37")}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]="8d2e6460-75c8-5b65-9b60-d4269a0ff597")}catch(e){}}();
3
3
  import * as __WEBPACK_EXTERNAL_MODULE_crypto__ from "crypto";
4
4
  import * as __WEBPACK_EXTERNAL_MODULE_fs__ from "fs";
5
5
  import * as __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_package_json_58ae5f06__ from "@iflyrpa/share/package.json";
@@ -4352,8 +4352,124 @@ function __webpack_require__(moduleId) {
4352
4352
  return module;
4353
4353
  };
4354
4354
  })();
4355
- var package_namespaceObject = {
4356
- i8: "4.0.9"
4355
+ var package_namespaceObject = JSON.parse('{"i8":"4.1.0-beta.0"}');
4356
+ const USER_MESSAGE = {
4357
+ PROXY_UNAVAILABLE: "代理暂时不可用,请稍后重试或使用本地IP",
4358
+ NETWORK_ERROR: "网络异常,请稍后重试",
4359
+ SYSTEM_ERROR: "系统异常,请稍后重试或联系客服",
4360
+ PUBLISH_NETWORK: "发布失败,网络不稳定,请稍后重试",
4361
+ DOUYIN_ACCOUNT_FETCH_FAILED: "抖音数据获取失败,请稍后重试",
4362
+ SHIPINHAO_ACCOUNT_FETCH_FAILED: "视频号数据获取失败,请稍后重试",
4363
+ DOUYIN_POST_FETCH_FAILED: "抖音作品数据获取失败,请稍后重试",
4364
+ SHIPINHAO_POST_FETCH_FAILED: "视频号作品数据获取失败,请稍后重试",
4365
+ BJH_POST_FETCH_FAILED: "百家号作品数据获取失败,请稍后重试",
4366
+ TT_POST_FETCH_FAILED: "头条号作品数据获取失败,请稍后重试",
4367
+ QRCODE_FETCH_FAILED: "认证二维码获取失败,请稍后重试",
4368
+ IMAGE_UPLOAD_FAILED: "图片上传失败,请稍后重试或联系客服"
4369
+ };
4370
+ const NETWORK_CODES = [
4371
+ 500,
4372
+ 502,
4373
+ 503,
4374
+ 504
4375
+ ];
4376
+ function classifyPublishError(handledError) {
4377
+ const { code } = handledError;
4378
+ const isProxyRequest = handledError.extra?.isProxyRequest === true;
4379
+ if (!NETWORK_CODES.includes(code) && 599 !== code) return null;
4380
+ const category = 599 === code || isProxyRequest ? "代理错误" : "网络错误";
4381
+ return {
4382
+ category,
4383
+ userMessage: USER_MESSAGE.PUBLISH_NETWORK
4384
+ };
4385
+ }
4386
+ const RPA_ERROR_WEBHOOK_URL = "https://open.xfchat.iflytek.com/open-apis/bot/v2/hook/d202c0dc-5af5-40bc-83ed-abc677caa4a5";
4387
+ const ALARM_THROTTLE_MS = 60000;
4388
+ const lastSentAt = new Map();
4389
+ const postFeishuWebhook = (webhookUrl, payload)=>__WEBPACK_EXTERNAL_MODULE_axios__["default"].post(webhookUrl, payload, {
4390
+ headers: {
4391
+ "Content-Type": "application/json"
4392
+ },
4393
+ timeout: 10000
4394
+ });
4395
+ const buildFeishuPostMessage = (report)=>{
4396
+ const content = [
4397
+ [
4398
+ {
4399
+ tag: "text",
4400
+ text: `平台:${report.platform || "未知平台"}`
4401
+ }
4402
+ ],
4403
+ [
4404
+ {
4405
+ tag: "text",
4406
+ text: `错误信息:${report.msg || "未知错误信息"}`
4407
+ }
4408
+ ],
4409
+ [
4410
+ {
4411
+ tag: "text",
4412
+ text: `错误类型:${report.errorType || "未知错误类型"}`
4413
+ }
4414
+ ],
4415
+ [
4416
+ {
4417
+ tag: "text",
4418
+ text: `阶段:${report.stage || "未知阶段"}`
4419
+ }
4420
+ ],
4421
+ [
4422
+ {
4423
+ tag: "text",
4424
+ text: `等级:${report.level}`
4425
+ }
4426
+ ],
4427
+ [
4428
+ {
4429
+ tag: "text",
4430
+ text: `来源:${report.source}`
4431
+ }
4432
+ ]
4433
+ ];
4434
+ if (void 0 !== report.code && null !== report.code) content.push([
4435
+ {
4436
+ tag: "text",
4437
+ text: `接口错误码:${report.code}`
4438
+ }
4439
+ ]);
4440
+ if (report.url) content.push([
4441
+ {
4442
+ tag: "text",
4443
+ text: `地址:${report.url}`
4444
+ }
4445
+ ]);
4446
+ if ("alarm" === report.level) content.push([
4447
+ {
4448
+ tag: "at",
4449
+ user_id: "all"
4450
+ }
4451
+ ]);
4452
+ return {
4453
+ msg_type: "post",
4454
+ content: {
4455
+ post: {
4456
+ zh_cn: {
4457
+ title: report.title || "RPA异常",
4458
+ content
4459
+ }
4460
+ }
4461
+ }
4462
+ };
4463
+ };
4464
+ const reportFeishuAlarm = (report)=>{
4465
+ try {
4466
+ const key = `${report.platform}|${report.source}|${report.errorType}|${report.code ?? ""}`;
4467
+ const now = Date.now();
4468
+ const last = lastSentAt.get(key);
4469
+ if (last && now - last < ALARM_THROTTLE_MS) return;
4470
+ lastSentAt.set(key, now);
4471
+ postFeishuWebhook(RPA_ERROR_WEBHOOK_URL, buildFeishuPostMessage(report)).catch(()=>{});
4472
+ } catch {}
4357
4473
  };
4358
4474
  const PROXY_CREDENTIALS = [
4359
4475
  {
@@ -4456,9 +4572,20 @@ async function ProxyAgent(task, addr, accountId, refresh) {
4456
4572
  url: "https://fetdev.iflysec.com/ip-pool/pool/eip/proxy",
4457
4573
  data: params
4458
4574
  }).catch((err)=>{
4575
+ reportFeishuAlarm({
4576
+ level: "alarm",
4577
+ platform: "ip-pool",
4578
+ source: "proxy",
4579
+ stage: "POST /ip-pool/pool/eip/proxy",
4580
+ errorType: "PROXY_REQUEST_FAILED",
4581
+ code: err?.code,
4582
+ msg: `请求代理失败:${err.message},区域:${addr ?? "-"},AccountId:${accountId ?? "-"}`,
4583
+ url: "https://fetdev.iflysec.com/ip-pool/pool/eip/proxy",
4584
+ title: "代理异常"
4585
+ });
4459
4586
  throw {
4460
4587
  code: 414,
4461
- message: `请求代理失败:${err.message}`,
4588
+ message: USER_MESSAGE.PROXY_UNAVAILABLE,
4462
4589
  data: {}
4463
4590
  };
4464
4591
  });
@@ -4478,12 +4605,53 @@ async function ProxyAgent(task, addr, accountId, refresh) {
4478
4605
  } : null;
4479
4606
  return proxyAgent;
4480
4607
  }
4608
+ const ALARM_STATUS = new Set([
4609
+ 401,
4610
+ 403,
4611
+ 429,
4612
+ 461,
4613
+ 471
4614
+ ]);
4615
+ const HTTP_STATUS_MESSAGE = {
4616
+ 400: "请求参数错误,请检查参数格式是否正确!",
4617
+ 401: "登录状态已失效,请重新登录后重试!",
4618
+ 403: "没有访问权限,账号可能受限或签名已失效!",
4619
+ 404: "请求的资源不存在,请检查接口地址!",
4620
+ 405: "请求方法不被允许,请检查接口调用方式!",
4621
+ 406: "服务端无法返回可接受的内容格式!",
4622
+ 407: "代理需要身份验证,请检查代理配置!",
4623
+ 408: "请求超时,请检查网络连接!",
4624
+ 409: "请求冲突,资源状态已变更,请刷新后重试!",
4625
+ 410: "请求的资源已被移除!",
4626
+ 412: "请求前置条件不满足,请刷新后重试!",
4627
+ 413: "提交内容过大,请压缩或分批后重试!",
4628
+ 414: "请求地址过长,请检查参数!",
4629
+ 415: "不支持的内容类型,请检查请求格式!",
4630
+ 422: "请求内容校验失败,请检查参数内容!",
4631
+ 423: "资源已被锁定,请稍后重试!",
4632
+ 429: "请求过于频繁,请稍后重试!",
4633
+ 431: "请求头过大,请清理 Cookie 后重试!",
4634
+ 451: "内容不合规或因法律原因被拒绝!",
4635
+ 461: "账号可能受限,请在网页上完成验证后重试!",
4636
+ 471: "账号可能受限,请在网页上完成验证后重试!",
4637
+ 500: "服务器内部错误,请稍后重试!",
4638
+ 501: "服务端不支持该请求,请稍后重试!",
4639
+ 502: "网关错误,请稍后重试!",
4640
+ 503: "服务暂时不可用,请稍后重试!",
4641
+ 504: "网关超时,请稍后重试!",
4642
+ 507: "服务端存储空间不足,请稍后重试!",
4643
+ 509: "服务带宽超限,请稍后重试!",
4644
+ 520: "服务端返回未知错误,请稍后重试!",
4645
+ 521: "源站拒绝连接,请稍后重试!",
4646
+ 522: "源站连接超时,请稍后重试!",
4647
+ 524: "源站响应超时,请稍后重试!"
4648
+ };
4481
4649
  class Http {
4482
4650
  static handleApiError(error) {
4483
4651
  if (error && "object" == typeof error && "code" in error && "message" in error) return error;
4484
4652
  return {
4485
4653
  code: 500,
4486
- message: error instanceof Error ? error.message : "未知错误",
4654
+ message: USER_MESSAGE.SYSTEM_ERROR,
4487
4655
  data: error
4488
4656
  };
4489
4657
  }
@@ -4538,6 +4706,18 @@ class Http {
4538
4706
  const verifyDecision = error.response?.headers?.["x-tt-verify-passport-decision"];
4539
4707
  if (verifyDecision) this.logger?.warn(`[403 验证决策] x-tt-verify-passport-decision: ${verifyDecision}`);
4540
4708
  }
4709
+ if (error.response?.status === 461 || error.response?.status === 471) {
4710
+ const h = error.response?.headers ?? {};
4711
+ const pick = (name)=>h[name] ?? h[name.toLowerCase()];
4712
+ this.logger?.warn(`[${error.response.status} 风控验证] URL: ${error.config?.url} Verifytype: ${pick("Verifytype") ?? "-"} Verifyuuid: ${pick("Verifyuuid") ?? "-"} Verifybiz: ${pick("Verifybiz") ?? "-"}`);
4713
+ this.logger?.warn(`[${error.response.status} 响应头] ${JSON.stringify(h)}`);
4714
+ errorResponse.extra = {
4715
+ ...errorResponse.extra,
4716
+ verifyType: pick("Verifytype"),
4717
+ verifyUuid: pick("Verifyuuid"),
4718
+ verifyBiz: pick("Verifybiz")
4719
+ };
4720
+ }
4541
4721
  if (error.response?.data) {
4542
4722
  if ("object" == typeof error.response.data) {
4543
4723
  const serverError = error.response.data;
@@ -4568,11 +4748,17 @@ class Http {
4568
4748
  _message = "DNS 查询超时,请稍后重试!";
4569
4749
  break;
4570
4750
  case "ERR_BAD_REQUEST":
4571
- _message = "请求出现错误,请检查请求参数!";
4572
- break;
4751
+ {
4752
+ const status = error.response?.status;
4753
+ _message = status && HTTP_STATUS_MESSAGE[status] || `请求失败,状态码${status ?? "unknown"}!`;
4754
+ break;
4755
+ }
4573
4756
  case "ERR_BAD_RESPONSE":
4574
- _message = `服务器响应异常 (${error.response?.status ?? "unknown"}),请稍后重试!`;
4575
- break;
4757
+ {
4758
+ const status = error.response?.status;
4759
+ _message = status && HTTP_STATUS_MESSAGE[status] || `服务器响应异常 (${status ?? "unknown"}),请稍后重试!`;
4760
+ break;
4761
+ }
4576
4762
  case "ERR_CANCELED":
4577
4763
  errorResponse.code = 414;
4578
4764
  _message = "请求连接超时,请稍候重试!";
@@ -4583,11 +4769,14 @@ class Http {
4583
4769
  }
4584
4770
  break;
4585
4771
  default:
4586
- this.logger?.debug(`未处理的网络错误代码: ${error.code} ${error.message}`, {
4587
- errorString: stringifyError(error)
4588
- });
4589
- _message = `网络错误: ${error.message}`;
4590
- break;
4772
+ {
4773
+ this.logger?.debug(`未处理的网络错误代码: ${error.code} ${error.message}`, {
4774
+ errorString: stringifyError(error)
4775
+ });
4776
+ const status = error.response?.status;
4777
+ _message = status && HTTP_STATUS_MESSAGE[status] || USER_MESSAGE.NETWORK_ERROR;
4778
+ break;
4779
+ }
4591
4780
  }
4592
4781
  }
4593
4782
  if (error.code && !error.response?.data) errorResponse.message = _message || errorResponse.message;
@@ -4597,29 +4786,51 @@ class Http {
4597
4786
  errorResponse.message = message;
4598
4787
  }
4599
4788
  if (error.message.includes("Proxy connection ended")) errorResponse.message = "所在区域代理连接超时,请更换区域或稍后重试!";
4789
+ const status = error.response?.status;
4790
+ reportFeishuAlarm({
4791
+ level: status && ALARM_STATUS.has(status) ? "alarm" : "warning",
4792
+ platform: this.platform || "unknown",
4793
+ source: "http",
4794
+ stage: `${(error.config?.method || "get").toUpperCase()} ${error.config?.url || "-"}`,
4795
+ errorType: status ? `HTTP_${status}` : error.code || "NETWORK_ERROR",
4796
+ code: errorResponse.code,
4797
+ msg: errorResponse.message,
4798
+ url: error.config?.url,
4799
+ title: "RPA接口异常"
4800
+ });
4600
4801
  throw errorResponse;
4601
4802
  });
4602
4803
  }
4603
4804
  async api(config, options) {
4604
4805
  const retries = options?.retries ?? 0;
4605
4806
  const retryDelay = options?.retryDelay ?? 500;
4606
- const reqTimeout = options?.timeout ?? 30000;
4807
+ const reqTimeout = options?.timeout ?? 60000;
4808
+ const externalSignal = options?.signal;
4607
4809
  let agent;
4608
4810
  const sessionRt = async (Rtimes)=>{
4609
4811
  try {
4610
4812
  this.proxyInfo = agent ? `${agent.ip}:${agent.port}` : void 0;
4611
4813
  const controller = new AbortController();
4612
4814
  const timeoutId = setTimeout(()=>controller.abort(), reqTimeout + 500);
4815
+ const forwardAbort = ()=>controller.abort();
4816
+ if (externalSignal) {
4817
+ if (externalSignal.aborted) controller.abort();
4818
+ else externalSignal.addEventListener("abort", forwardAbort, {
4819
+ once: true
4820
+ });
4821
+ }
4613
4822
  const response = await this.apiClient({
4614
4823
  ...config,
4615
4824
  timeout: reqTimeout,
4616
4825
  signal: controller.signal,
4826
+ onUploadProgress: options?.onUploadProgress,
4617
4827
  ...agent ? {
4618
4828
  httpAgent: agent.agent,
4619
4829
  httpsAgent: agent.agent
4620
4830
  } : {}
4621
4831
  }).finally(()=>{
4622
4832
  clearTimeout(timeoutId);
4833
+ externalSignal?.removeEventListener("abort", forwardAbort);
4623
4834
  });
4624
4835
  return response.data;
4625
4836
  } catch (error) {
@@ -5364,7 +5575,7 @@ const NUMBER_FORMAT_RANGES = {
5364
5575
  Number.MAX_VALUE
5365
5576
  ]
5366
5577
  };
5367
- function pick(schema, mask) {
5578
+ function util_pick(schema, mask) {
5368
5579
  const currDef = schema._zod.def;
5369
5580
  const def = mergeDefs(schema._zod.def, {
5370
5581
  get shape () {
@@ -5734,7 +5945,7 @@ const ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;
5734
5945
  const xid = /^[0-9a-vA-V]{20}$/;
5735
5946
  const ksuid = /^[A-Za-z0-9]{27}$/;
5736
5947
  const nanoid = /^[a-zA-Z0-9_-]{21}$/;
5737
- const duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
5948
+ 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)?)?)$/;
5738
5949
  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})$/;
5739
5950
  const regexes_uuid = (version)=>{
5740
5951
  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)$/;
@@ -6420,7 +6631,7 @@ const $ZodISOTime = /*@__PURE__*/ $constructor("$ZodISOTime", (inst, def)=>{
6420
6631
  $ZodStringFormat.init(inst, def);
6421
6632
  });
6422
6633
  const $ZodISODuration = /*@__PURE__*/ $constructor("$ZodISODuration", (inst, def)=>{
6423
- def.pattern ?? (def.pattern = duration);
6634
+ def.pattern ?? (def.pattern = regexes_duration);
6424
6635
  $ZodStringFormat.init(inst, def);
6425
6636
  });
6426
6637
  const $ZodIPv4 = /*@__PURE__*/ $constructor("$ZodIPv4", (inst, def)=>{
@@ -8345,7 +8556,7 @@ const ZodObject = /*@__PURE__*/ $constructor("ZodObject", (inst, def)=>{
8345
8556
  inst.extend = (incoming)=>extend(inst, incoming);
8346
8557
  inst.safeExtend = (incoming)=>safeExtend(inst, incoming);
8347
8558
  inst.merge = (other)=>merge(inst, other);
8348
- inst.pick = (mask)=>pick(inst, mask);
8559
+ inst.pick = (mask)=>util_pick(inst, mask);
8349
8560
  inst.omit = (mask)=>omit(inst, mask);
8350
8561
  inst.partial = (...args)=>partial(ZodOptional, inst, args[0]);
8351
8562
  inst.required = (...args)=>required(ZodNonOptional, inst, args[0]);
@@ -8358,6 +8569,14 @@ function schemas_object(shape, params) {
8358
8569
  };
8359
8570
  return new ZodObject(def);
8360
8571
  }
8572
+ function looseObject(shape, params) {
8573
+ return new ZodObject({
8574
+ type: "object",
8575
+ shape,
8576
+ catchall: unknown(),
8577
+ ...normalizeParams(params)
8578
+ });
8579
+ }
8361
8580
  const ZodUnion = /*@__PURE__*/ $constructor("ZodUnion", (inst, def)=>{
8362
8581
  $ZodUnion.init(inst, def);
8363
8582
  ZodType.init(inst, def);
@@ -9054,6 +9273,13 @@ const mockAction = async (task, params)=>{
9054
9273
  data: ""
9055
9274
  };
9056
9275
  const image = await (0, __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_f7afdc8c__.downloadImage)(url, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(tmpCachePath, fileName));
9276
+ const stats = __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].statSync(image);
9277
+ const maxSize = 5242880;
9278
+ if (stats.size > maxSize) throw {
9279
+ code: 414,
9280
+ message: "百家号平台:单张图片不得超过 5MB",
9281
+ data: ""
9282
+ };
9057
9283
  const formData = new __WEBPACK_EXTERNAL_MODULE_form_data_cf000082__["default"]();
9058
9284
  formData.append("org_file_name", fileName);
9059
9285
  formData.append("type", "image");
@@ -12334,7 +12560,7 @@ const douyinGetVerifyQrCode = async (task, params)=>{
12334
12560
  });
12335
12561
  const qrData = qrCodeResponse?.data;
12336
12562
  task.logger.info(`获取二维码响应: error_code=${qrData?.error_code}, message=${qrCodeResponse?.message}`);
12337
- if (qrData?.error_code !== 0) return (0, __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_f7afdc8c__.response)(414, `获取二维码失败: error_code=${qrData?.error_code}`, "");
12563
+ if (qrData?.error_code !== 0) return (0, __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_f7afdc8c__.response)(414, USER_MESSAGE.QRCODE_FETCH_FAILED, "");
12338
12564
  return (0, __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_f7afdc8c__.response)(0, "获取二维码成功", {
12339
12565
  qrcode: qrData.qrcode,
12340
12566
  token: qrData.token,
@@ -12349,7 +12575,7 @@ const douyinGetVerifyQrCode = async (task, params)=>{
12349
12575
  } catch (err) {
12350
12576
  const msg = err instanceof Error ? err.message : String(err);
12351
12577
  task.logger.warn(`[douyinGetVerifyQrCode] 获取二维码失败: ${msg}`);
12352
- return (0, __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_f7afdc8c__.response)(500, `获取二维码失败: ${msg}`, "");
12578
+ return (0, __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_f7afdc8c__.response)(500, USER_MESSAGE.QRCODE_FETCH_FAILED, "");
12353
12579
  }
12354
12580
  };
12355
12581
  const DouyinGetWorkListParamsSchema = ActionCommonParamsSchema.extend({
@@ -13184,6 +13410,11 @@ class DouyinImageUploader {
13184
13410
  }
13185
13411
  async getImageInfo(localPath) {
13186
13412
  const stats = __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].statSync(localPath);
13413
+ const maxSize = 52428800;
13414
+ if (stats.size > maxSize) {
13415
+ __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].basename(localPath);
13416
+ throw new Error("抖音平台:单张图片不得超过 50MB");
13417
+ }
13187
13418
  let width = 1080;
13188
13419
  let height = 1920;
13189
13420
  try {
@@ -13664,18 +13895,10 @@ const mock_mockAction = async (task, params)=>{
13664
13895
  });
13665
13896
  } catch (error) {
13666
13897
  const handledError = Http.handleApiError(error);
13667
- const isProxyOrNetworkError = [
13668
- 599,
13669
- 500,
13670
- 502,
13671
- 503,
13672
- 504
13673
- ].includes(handledError.code);
13674
- if (isProxyOrNetworkError) {
13675
- const isProxyRequest = handledError.extra?.isProxyRequest === true;
13676
- const errorType = 599 === handledError.code || isProxyRequest ? "代理错误" : "网络错误";
13677
- const message = `图文发布失败,${errorType}:${handledError.message}${task.debug ? ` ${http.proxyInfo}` : ""}`;
13678
- task.logger.error(`[douyinPublish] ${errorType},直接返回: ${message}`, stringifyError(handledError));
13898
+ const classified = classifyPublishError(handledError);
13899
+ if (classified) {
13900
+ const message = `${classified.userMessage}${task.debug ? ` ${http.proxyInfo}` : ""}`;
13901
+ task.logger.error(`[douyinPublish] ${classified.category},直接返回: ${handledError.message} (code=${handledError.code})`, stringifyError(handledError));
13679
13902
  await updateTaskState?.({
13680
13903
  state: __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_f7afdc8c__.TaskState.FAILED,
13681
13904
  error: message
@@ -15393,7 +15616,7 @@ async function getDouyinData(_task, params) {
15393
15616
  }
15394
15617
  const errMsg = error instanceof Error ? error.message : String(error);
15395
15618
  _task.logger.error(`抖音账号数据获取失败: ${errMsg}`);
15396
- return types_errorResponse(errMsg || "抖音账号数据获取失败");
15619
+ return types_errorResponse(USER_MESSAGE.DOUYIN_ACCOUNT_FETCH_FAILED);
15397
15620
  }
15398
15621
  }
15399
15622
  async function getShipinhaoData(_task, params) {
@@ -15524,7 +15747,7 @@ async function getShipinhaoData(_task, params) {
15524
15747
  }
15525
15748
  const errMsg = error instanceof Error ? error.message : String(error);
15526
15749
  _task.logger.error(`视频号账号数据获取失败: ${errMsg}`);
15527
- return types_errorResponse(errMsg || "视频号账号数据获取失败");
15750
+ return types_errorResponse(USER_MESSAGE.SHIPINHAO_ACCOUNT_FETCH_FAILED);
15528
15751
  }
15529
15752
  }
15530
15753
  async function getToutiaoData(_task, params) {
@@ -15963,7 +16186,9 @@ async function handleBaijiahaoData(_task, params) {
15963
16186
  } : null
15964
16187
  }, "百家号文章数据获取成功");
15965
16188
  } catch (error) {
15966
- return searchPublishInfo_types_errorResponse(error instanceof Error ? error.message : "百家号文章数据获取失败");
16189
+ const errMsg = error instanceof Error ? error.message : String(error);
16190
+ _task.logger.error(`百家号文章数据获取失败: ${errMsg}`);
16191
+ return searchPublishInfo_types_errorResponse(USER_MESSAGE.BJH_POST_FETCH_FAILED);
15967
16192
  }
15968
16193
  }
15969
16194
  async function handleDouyinData(_task, params) {
@@ -16058,7 +16283,9 @@ async function handleDouyinData(_task, params) {
16058
16283
  } : null
16059
16284
  }, "抖音数据获取成功");
16060
16285
  } catch (error) {
16061
- return searchPublishInfo_types_errorResponse(error instanceof Error ? error.message : "抖音数据获取失败");
16286
+ const errMsg = error instanceof Error ? error.message : String(error);
16287
+ _task.logger.error(`抖音作品数据获取失败: ${errMsg}`);
16288
+ return searchPublishInfo_types_errorResponse(USER_MESSAGE.DOUYIN_POST_FETCH_FAILED);
16062
16289
  }
16063
16290
  }
16064
16291
  async function handleShipinhaoData(_task, params) {
@@ -16223,8 +16450,9 @@ async function handleShipinhaoData(_task, params) {
16223
16450
  }, "视频号数据获取成功");
16224
16451
  } catch (error) {
16225
16452
  const errMsg = error instanceof Error ? error.message : String(error);
16453
+ _task.logger.error(`视频号作品数据获取失败: ${errMsg}`);
16226
16454
  if (errMsg.startsWith("AUTH_ERROR:")) return searchPublishInfo_types_errorResponse("视频号数据获取失败,请检查账号状态", 414);
16227
- return searchPublishInfo_types_errorResponse(errMsg || "视频号数据获取失败");
16455
+ return searchPublishInfo_types_errorResponse(USER_MESSAGE.SHIPINHAO_POST_FETCH_FAILED);
16228
16456
  }
16229
16457
  }
16230
16458
  async function handleToutiaoData(_task, params) {
@@ -16309,7 +16537,9 @@ async function handleToutiaoData(_task, params) {
16309
16537
  } : null
16310
16538
  }, "头条号文章文章获取成功");
16311
16539
  } catch (error) {
16312
- return searchPublishInfo_types_errorResponse(error instanceof Error ? error.message : "头条号文章数据获取失败");
16540
+ const errMsg = error instanceof Error ? error.message : String(error);
16541
+ _task.logger.error(`头条号文章数据获取失败: ${errMsg}`);
16542
+ return searchPublishInfo_types_errorResponse(USER_MESSAGE.TT_POST_FETCH_FAILED);
16313
16543
  }
16314
16544
  }
16315
16545
  async function handleWeixinData(_task, params) {
@@ -18684,18 +18914,10 @@ const shipinhaoPublish_mock_mockAction = async (task, params)=>{
18684
18914
  });
18685
18915
  } catch (error) {
18686
18916
  const handledError = Http.handleApiError(error);
18687
- const isProxyOrNetworkError = [
18688
- 599,
18689
- 500,
18690
- 502,
18691
- 503,
18692
- 504
18693
- ].includes(handledError.code);
18694
- if (isProxyOrNetworkError) {
18695
- const isProxyRequest = handledError.extra?.isProxyRequest === true;
18696
- const errorType = 599 === handledError.code || isProxyRequest ? "代理错误" : "网络错误";
18697
- const message = `图文发布失败,${errorType}:${handledError.message}${task.debug ? ` ${http.proxyInfo}` : ""}`;
18698
- task.logger.error(`[shipinhaoPublish] ${errorType},直接返回: ${message}`, stringifyError(handledError));
18917
+ const classified = classifyPublishError(handledError);
18918
+ if (classified) {
18919
+ const message = `${classified.userMessage}${task.debug ? ` ${http.proxyInfo}` : ""}`;
18920
+ task.logger.error(`[shipinhaoPublish] ${classified.category},直接返回: ${handledError.message} (code=${handledError.code})`, stringifyError(handledError));
18699
18921
  await updateTaskState?.({
18700
18922
  state: __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_f7afdc8c__.TaskState.FAILED,
18701
18923
  error: message
@@ -19435,107 +19657,1747 @@ const shipinhaoPublish = async (task, params)=>{
19435
19657
  if ("server" === params.actionType) return rpa_server_rpaAction_Server(task, params);
19436
19658
  return executeAction(shipinhaoPublish_mock_mockAction, rpa_server_rpaAction_Server)(task, params);
19437
19659
  };
19438
- const ShipinhaoSendMsgParamsSchema = ActionCommonParamsSchema.extend({
19439
- toUsername: schemas_string().min(1, "接收者用户名不能为空"),
19440
- sessionId: schemas_string().min(1, "会话ID不能为空"),
19441
- msgType: schemas_enum([
19442
- "TEXT",
19443
- "IMAGE"
19444
- ], {
19445
- message: "消息类型必须是 TEXT 或 IMAGE"
19446
- }),
19447
- content: schemas_string().optional(),
19448
- imageInfo: schemas_object({
19449
- pathOrUrl: schemas_string().min(1, "图片路径或URL不能为空")
19450
- }).optional()
19451
- });
19452
- const CHUNK_SIZE = 524288;
19453
- async function shipinhaoSendMsg_getUserInfo(cookieStr, http) {
19454
- const url = `https://channels.weixin.qq.com/cgi-bin/mmfinderassistant-bin/auth/auth_data?_rid=${rid()}`;
19455
- const headers = {
19456
- referer: "https://channels.weixin.qq.com/micro/interaction/private_msg",
19457
- cookie: cookieStr,
19458
- Origin: "https://channels.weixin.qq.com"
19459
- };
19460
- return await http.api({
19461
- method: "get",
19462
- url,
19463
- headers
19464
- }, {
19465
- retries: 3,
19466
- retryDelay: 1000,
19467
- timeout: 10000
19660
+ function auth_getTimeStamp(length) {
19661
+ return Date.now().toString().substring(0, length);
19662
+ }
19663
+ async function auth_getUserInfo(cookies, http) {
19664
+ return http.api({
19665
+ method: "post",
19666
+ url: "https://channels.weixin.qq.com/cgi-bin/mmfinderassistant-bin/auth/auth_data",
19667
+ data: {
19668
+ timestamp: auth_getTimeStamp(13),
19669
+ _log_finder_uin: "",
19670
+ _log_finder_id: "",
19671
+ rawKeyBuff: null,
19672
+ pluginSessionId: null,
19673
+ scene: 7,
19674
+ reqScene: 7
19675
+ },
19676
+ headers: {
19677
+ cookie: cookies,
19678
+ referer: "https://channels.weixin.qq.com",
19679
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
19680
+ },
19681
+ defaultErrorMsg: "获取用户信息失败"
19468
19682
  });
19469
19683
  }
19470
- const shipinhaoSendMsg = async (_task, params)=>{
19471
- if (!params.sessionId) return (0, __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_f7afdc8c__.response)(414, "sessionId 不能为空", void 0);
19472
- if (!params.toUsername) return (0, __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_f7afdc8c__.response)(414, "接收者用户名不能为空", void 0);
19473
- if (!params.msgType) return (0, __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_f7afdc8c__.response)(414, "消息类型不能为空", void 0);
19474
- if (![
19475
- "TEXT",
19476
- "IMAGE"
19477
- ].includes(params.msgType)) return (0, __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_f7afdc8c__.response)(414, "消息类型必须是 TEXT 或 IMAGE", void 0);
19478
- if ("TEXT" === params.msgType) {
19479
- if (!params.content || "" === params.content.trim()) return (0, __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_f7afdc8c__.response)(414, "消息内容不能为空", void 0);
19480
- }
19481
- if ("IMAGE" === params.msgType) {
19482
- if (!params.imageInfo?.pathOrUrl) return (0, __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_f7afdc8c__.response)(414, "图片路径或URL不能为空", void 0);
19684
+ async function auth_getUploadAuthKey(cookies, finderUsername, http) {
19685
+ return http.api({
19686
+ method: "post",
19687
+ url: "https://channels.weixin.qq.com/cgi-bin/mmfinderassistant-bin/helper/helper_upload_params",
19688
+ data: {
19689
+ timestamp: auth_getTimeStamp(13),
19690
+ _log_finder_id: finderUsername,
19691
+ rawKeyBuff: null
19692
+ },
19693
+ headers: {
19694
+ cookie: cookies,
19695
+ referer: "https://channels.weixin.qq.com",
19696
+ Accept: "application/json, text/plain, */*",
19697
+ "Content-Type": "application/json",
19698
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
19699
+ },
19700
+ defaultErrorMsg: "获取上传认证密钥失败"
19701
+ });
19702
+ }
19703
+ class ShipinhaoAuthError extends Error {
19704
+ constructor(message, errCode){
19705
+ super(message), this.errCode = errCode;
19706
+ this.name = "ShipinhaoAuthError";
19483
19707
  }
19484
- if (!params.extraParam) return (0, __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_f7afdc8c__.response)(414, "缺少 extraParam 参数", void 0);
19485
- if (!params.extraParam.fingerPrintDeviceId || !params.extraParam.aId || !params.extraParam.uin) return (0, __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_f7afdc8c__.response)(414, "fingerPrintDeviceId、aId 和 uin 不能为空", void 0);
19486
- const cookieStr = params.cookies.map((it)=>`${it.name}=${it.value}`).join(";");
19487
- const headers = {
19488
- cookie: cookieStr,
19489
- referer: "https://channels.weixin.qq.com/micro/interaction/private_msg",
19490
- origin: "https://channels.weixin.qq.com",
19491
- "content-type": "application/json",
19492
- "finger-print-device-id": params.extraParam.fingerPrintDeviceId,
19493
- "x-wechat-uin": params.extraParam.uin
19708
+ }
19709
+ async function getShipinhaoUploadAuth(cookies, http) {
19710
+ const userInfo = await auth_getUserInfo(cookies, http);
19711
+ if (0 !== userInfo.errCode || !userInfo.data?.finderUser) {
19712
+ const isLoginExpired = 300333 === userInfo.errCode || 300334 === userInfo.errCode;
19713
+ throw new ShipinhaoAuthError(isLoginExpired ? "登录失效" : userInfo.errMsg || "获取用户信息失败", userInfo.errCode || 500);
19714
+ }
19715
+ const finderUsername = userInfo.data.finderUser.finderUsername;
19716
+ const authKeyResponse = await auth_getUploadAuthKey(cookies, finderUsername, http);
19717
+ if (0 !== authKeyResponse.errCode || !authKeyResponse.data?.authKey) throw new ShipinhaoAuthError(`获取上传认证参数失败: ${authKeyResponse.errMsg}`, authKeyResponse.errCode || 500);
19718
+ const uin = authKeyResponse.data.uin;
19719
+ if (!uin) throw new ShipinhaoAuthError("获取用户 uin 失败", 500);
19720
+ const videoFileType = authKeyResponse.data.videoFileType || 20302;
19721
+ const pictureFileType = authKeyResponse.data.pictureFileType || 20304;
19722
+ return {
19723
+ uin,
19724
+ authKey: authKeyResponse.data.authKey,
19725
+ finderUsername,
19726
+ videoFileType,
19727
+ pictureFileType
19494
19728
  };
19495
- const http = new Http({
19496
- headers
19729
+ }
19730
+ const MENTION_TEXT_SUFFIX = "\u0020";
19731
+ const MENTION_XML_SUFFIX = "\u2005";
19732
+ function payload_buildDescription(params) {
19733
+ let description = params.description || "";
19734
+ for (const topic of params.topics || [])description += `#${topic}`;
19735
+ for (const user of params.mentionedUsers || [])description += `@${user.nickname}${MENTION_TEXT_SUFFIX}`;
19736
+ return description;
19737
+ }
19738
+ function buildMentionedUser(mentionedUsers) {
19739
+ return (mentionedUsers || []).map((user)=>({
19740
+ nickname: `${user.nickname}${MENTION_TEXT_SUFFIX}`
19741
+ }));
19742
+ }
19743
+ function payload_buildTopicXml(params) {
19744
+ const values = [];
19745
+ let atIndex = null;
19746
+ if (params.description) values.push(`<![CDATA[${params.description}]]>`);
19747
+ for (const topic of params.topics || [])values.push(`<topic><![CDATA[#${topic}#]]></topic>`);
19748
+ for (const user of params.mentionedUsers || []){
19749
+ if (null === atIndex) atIndex = values.length;
19750
+ values.push(`<![CDATA[@${user.nickname}${MENTION_XML_SUFFIX}]]>`);
19751
+ }
19752
+ let xml = "<finder>";
19753
+ xml += "<version>1</version>";
19754
+ xml += `<valuecount>${values.length}</valuecount>`;
19755
+ xml += `<style><at>${atIndex ?? ""}</at></style>`;
19756
+ values.forEach((value, index)=>{
19757
+ xml += `<value${index}>${value}</value${index}>`;
19497
19758
  });
19498
- const urlParams = new URLSearchParams({
19499
- _aid: params.extraParam.aId,
19500
- _rid: rid(),
19501
- _pageUrl: "https://channels.weixin.qq.com/micro/interaction/private_msg"
19502
- }).toString();
19503
- const generateCliMsgId = ()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (s)=>{
19504
- const t = 16 * Math.random() | 0;
19505
- return ("x" === s ? t : 3 & t | 8).toString(16);
19759
+ xml += "</finder>";
19760
+ return xml;
19761
+ }
19762
+ function payload_buildLocation(location) {
19763
+ if (!location) return {
19764
+ latitude: 0,
19765
+ longitude: 0,
19766
+ city: "",
19767
+ poiName: "",
19768
+ address: "",
19769
+ poiClassifyId: ""
19770
+ };
19771
+ return {
19772
+ latitude: location.latitude,
19773
+ longitude: location.longitude,
19774
+ city: location.city,
19775
+ poiName: location.poiName || "",
19776
+ address: location.address || "",
19777
+ poiClassifyId: location.poiClassifyId || ""
19778
+ };
19779
+ }
19780
+ function buildTopic(params) {
19781
+ const topic = {
19782
+ finderTopicInfo: payload_buildTopicXml(params)
19783
+ };
19784
+ if (params.collection) {
19785
+ topic.collectionId = params.collection.collectionId;
19786
+ topic.collectionName = params.collection.collectionName;
19787
+ }
19788
+ return topic;
19789
+ }
19790
+ function buildEvent(event) {
19791
+ if (!event) return {};
19792
+ return {
19793
+ eventTopicId: event.eventTopicId,
19794
+ eventName: event.eventName,
19795
+ eventCreatorNickname: event.eventCreatorNickname || ""
19796
+ };
19797
+ }
19798
+ function buildExtReading(link) {
19799
+ if (!link) return {
19800
+ link: "",
19801
+ title: "",
19802
+ urlType: 1
19803
+ };
19804
+ return {
19805
+ link: link.link.replace(/[\s\u200b]/g, ""),
19806
+ title: link.title,
19807
+ urlType: link.urlType ?? 1
19808
+ };
19809
+ }
19810
+ function buildTagInfo(tagInfo, tagKey) {
19811
+ return {
19812
+ ...tagInfo,
19813
+ tagKey
19814
+ };
19815
+ }
19816
+ const CHUNK_SIZE = 8388608;
19817
+ const UPLOAD_STAGE_TIMEOUT = 180000;
19818
+ const DEFAULT_TUNING = {
19819
+ metaTimeout: UPLOAD_STAGE_TIMEOUT,
19820
+ partTimeout: UPLOAD_STAGE_TIMEOUT,
19821
+ partRetries: 3,
19822
+ completeTimeout: UPLOAD_STAGE_TIMEOUT
19823
+ };
19824
+ async function uploader_uploadFile(opts) {
19825
+ const { filePath, fileType, uin, authKey, http, logger, tuning } = opts;
19826
+ const stat = __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].statSync(filePath);
19827
+ const fileSize = stat.size;
19828
+ const fileName = filePath.split(/[\\/]/).pop() || "file";
19829
+ const metaTimeout = tuning?.metaTimeout ?? DEFAULT_TUNING.metaTimeout;
19830
+ const partTimeout = tuning?.partTimeout ?? DEFAULT_TUNING.partTimeout;
19831
+ const partRetries = tuning?.partRetries ?? DEFAULT_TUNING.partRetries;
19832
+ const completeTimeout = tuning?.completeTimeout ?? DEFAULT_TUNING.completeTimeout;
19833
+ logger?.info(`开始上传: ${fileName} (${fileSize} B, filetype=${fileType})`);
19834
+ logger?.info(`上传超时策略: 单片 ${partTimeout / 1000}s(重试 ${partRetries} 次)、合并 ${completeTimeout / 1000}s`);
19835
+ const fileMd5 = await computeFileMd5(filePath);
19836
+ const taskId = generateTaskId(fileName, fileSize, fileMd5);
19837
+ const baseUrl = "https://finderassistancea.video.qq.com";
19838
+ const headers = {
19839
+ Authorization: authKey
19840
+ };
19841
+ const xArgs = `apptype=251&filetype=${fileType}&weixinnum=${uin}&filekey=${encodeURIComponent(fileName)}&filesize=${fileSize}&taskid=${taskId}&scene=2`;
19842
+ const chunkCount = Math.ceil(fileSize / CHUNK_SIZE);
19843
+ const blockPartLength = [];
19844
+ for(let i = 0; i < chunkCount; i++)blockPartLength.push(Math.min((i + 1) * CHUNK_SIZE, fileSize));
19845
+ logger?.info(`申请 UploadID: ${chunkCount} 片`);
19846
+ const applyRes = await http.api({
19847
+ method: "PUT",
19848
+ url: `${baseUrl}/applyuploaddfs`,
19849
+ headers: {
19850
+ ...headers,
19851
+ "X-Arguments": xArgs
19852
+ },
19853
+ data: {
19854
+ BlockSum: chunkCount,
19855
+ BlockPartLength: blockPartLength
19856
+ }
19857
+ }, {
19858
+ timeout: metaTimeout,
19859
+ retries: 2,
19860
+ retryDelay: 2000
19861
+ });
19862
+ if (!applyRes.UploadID && !applyRes.ListPartsResult) throw new Error("申请 UploadID 失败: " + JSON.stringify(applyRes));
19863
+ let uploadId = applyRes.UploadID;
19864
+ const uploadedParts = new Set();
19865
+ if (applyRes.ListPartsResult) {
19866
+ logger?.info("检测到已上传分片,执行续传");
19867
+ const parts = Array.isArray(applyRes.ListPartsResult.Part) ? applyRes.ListPartsResult.Part : applyRes.ListPartsResult.Part ? [
19868
+ applyRes.ListPartsResult.Part
19869
+ ] : [];
19870
+ for (const p of parts)uploadedParts.add(p.PartNumber);
19871
+ const retryRes = await http.api({
19872
+ method: "PUT",
19873
+ url: `${baseUrl}/applyuploaddfs`,
19874
+ headers: {
19875
+ ...headers,
19876
+ "X-Arguments": xArgs
19877
+ },
19878
+ data: {
19879
+ BlockSum: chunkCount,
19880
+ BlockPartLength: blockPartLength
19881
+ }
19882
+ }, {
19883
+ timeout: metaTimeout,
19884
+ retries: 2,
19885
+ retryDelay: 2000
19506
19886
  });
19507
- let fromUsername = params.extraParam.finderUserName;
19508
- if (!fromUsername) {
19509
- _task.logger.info("未提供 finderUserName,尝试获取用户信息");
19510
- const userInfoRes = await shipinhaoSendMsg_getUserInfo(cookieStr, http);
19511
- if (!userInfoRes.data?.finderUser?.finderUsername) return (0, __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_f7afdc8c__.response)(userInfoRes.errCode || -1, userInfoRes.errMsg || "获取用户信息失败", {});
19512
- fromUsername = userInfoRes.data.finderUser.finderUsername;
19513
- _task.logger.info(`获取到用户名: ${fromUsername}`);
19887
+ uploadId = retryRes.UploadID;
19888
+ if (!uploadId) throw new Error("续传获取 UploadID 失败");
19514
19889
  }
19515
- let imgMsg;
19516
- if ("IMAGE" === params.msgType) {
19517
- let imageBuffer;
19518
- const imagePath = params.imageInfo.pathOrUrl;
19519
- try {
19520
- if (imagePath.startsWith("http://") || imagePath.startsWith("https://")) {
19521
- const resp = await __WEBPACK_EXTERNAL_MODULE_axios__["default"].get(imagePath, {
19522
- responseType: "arraybuffer"
19523
- });
19524
- imageBuffer = Buffer.from(resp.data);
19525
- } else {
19526
- const filePath = imagePath.startsWith("file://") ? imagePath.slice(7) : imagePath;
19527
- imageBuffer = Buffer.from(await __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].promises.readFile(filePath));
19890
+ const partInfo = [];
19891
+ const fd = __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].openSync(filePath, "r");
19892
+ try {
19893
+ for(let i = 0; i < chunkCount; i++){
19894
+ const partNumber = i + 1;
19895
+ if (uploadedParts.has(partNumber)) {
19896
+ const existing = applyRes.ListPartsResult.Part.find((p)=>p.PartNumber === partNumber);
19897
+ if (existing) {
19898
+ partInfo.push({
19899
+ PartNumber: partNumber,
19900
+ ETag: existing.ETag
19901
+ });
19902
+ logger?.info(`分片 ${partNumber}/${chunkCount} 已存在,跳过`);
19903
+ continue;
19904
+ }
19528
19905
  }
19529
- } catch (err) {
19530
- return (0, __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_f7afdc8c__.response)(414, `读取图片失败: ${err instanceof Error ? err.message : String(err)}`, void 0);
19906
+ const start = i * CHUNK_SIZE;
19907
+ const end = Math.min(start + CHUNK_SIZE, fileSize);
19908
+ const chunkSize = end - start;
19909
+ const chunk = Buffer.alloc(chunkSize);
19910
+ __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].readSync(fd, chunk, 0, chunkSize, start);
19911
+ const chunkMd5 = __WEBPACK_EXTERNAL_MODULE_node_crypto_9ba42079__["default"].createHash("md5").update(chunk).digest("hex");
19912
+ const partStart = Date.now();
19913
+ await http.api({
19914
+ method: "PUT",
19915
+ url: `${baseUrl}/uploadpartdfs?PartNumber=${partNumber}&UploadID=${encodeURIComponent(uploadId)}`,
19916
+ headers: {
19917
+ ...headers,
19918
+ "X-Arguments": xArgs.replace(/scene=2/, "scene=0"),
19919
+ "Content-MD5": chunkMd5
19920
+ },
19921
+ data: chunk
19922
+ }, {
19923
+ timeout: partTimeout,
19924
+ retries: partRetries,
19925
+ retryDelay: 2000
19926
+ });
19927
+ const partElapsed = Date.now() - partStart;
19928
+ const throughput = Math.round(chunkSize / (partElapsed / 1000));
19929
+ partInfo.push({
19930
+ PartNumber: partNumber,
19931
+ ETag: `"${chunkMd5}"`
19932
+ });
19933
+ logger?.info(`分片 ${partNumber}/${chunkCount} 完成 (${chunkSize} B, ${partElapsed}ms, ${Math.round(throughput / 1024)}KB/s)`);
19531
19934
  }
19532
- const md5 = (0, __WEBPACK_EXTERNAL_MODULE_node_crypto_9ba42079__.createHash)("md5").update(imageBuffer).digest("hex");
19533
- const timestamp = Date.now().toString();
19534
- const totalChunks = Math.ceil(imageBuffer.length / CHUNK_SIZE);
19535
- console.log(`分片上传md5${md5}`);
19935
+ } finally{
19936
+ __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].closeSync(fd);
19937
+ }
19938
+ logger?.info("合并分片...");
19939
+ const completeRes = await http.api({
19940
+ method: "POST",
19941
+ url: `${baseUrl}/completepartuploaddfs?UploadID=${encodeURIComponent(uploadId)}`,
19942
+ headers: {
19943
+ ...headers,
19944
+ "X-Arguments": xArgs
19945
+ },
19946
+ data: {
19947
+ TransFlag: "0_0",
19948
+ PartInfo: partInfo
19949
+ }
19950
+ }, {
19951
+ timeout: completeTimeout,
19952
+ retries: 1,
19953
+ retryDelay: 3000
19954
+ });
19955
+ if (!completeRes.DownloadURL) throw new Error("合并分片失败: " + JSON.stringify(completeRes));
19956
+ logger?.info("上传成功");
19957
+ return {
19958
+ downloadUrl: completeRes.DownloadURL,
19959
+ md5: fileMd5,
19960
+ fileSize
19961
+ };
19962
+ }
19963
+ async function computeFileMd5(filePath) {
19964
+ return new Promise((resolve, reject)=>{
19965
+ const hash = __WEBPACK_EXTERNAL_MODULE_node_crypto_9ba42079__["default"].createHash("md5");
19966
+ const stream = __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].createReadStream(filePath);
19967
+ stream.on("data", (chunk)=>hash.update(chunk));
19968
+ stream.on("end", ()=>resolve(hash.digest("hex")));
19969
+ stream.on("error", reject);
19970
+ });
19971
+ }
19972
+ function generateTaskId(fileName, fileSize, fileMd5) {
19973
+ const input = `${fileName}-${fileSize}-${fileMd5}`;
19974
+ return __WEBPACK_EXTERNAL_MODULE_node_crypto_9ba42079__["default"].createHash("md5").update(input).digest("hex").slice(0, 32);
19975
+ }
19976
+ const MAX_METADATA_BOX_SIZE = 268435456;
19977
+ function readBoxHeader(fd, offset, limit) {
19978
+ if (offset + 8 > limit) return null;
19979
+ const head = Buffer.alloc(16);
19980
+ const read = __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].readSync(fd, head, 0, 16, offset);
19981
+ if (read < 8) return null;
19982
+ let size = head.readUInt32BE(0);
19983
+ const type = head.toString("latin1", 4, 8);
19984
+ let headerSize = 8;
19985
+ if (1 === size) {
19986
+ if (read < 16) return null;
19987
+ size = head.readUInt32BE(8) * 2 ** 32 + head.readUInt32BE(12);
19988
+ headerSize = 16;
19989
+ } else if (0 === size) size = limit - offset;
19990
+ if (size < headerSize || offset + size > limit) return null;
19991
+ return {
19992
+ type,
19993
+ size,
19994
+ headerSize
19995
+ };
19996
+ }
19997
+ function parseVideoMeta(filePath) {
19998
+ let fd;
19999
+ let fileSize;
20000
+ try {
20001
+ fd = __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].openSync(filePath, "r");
20002
+ } catch {
20003
+ return null;
20004
+ }
20005
+ try {
20006
+ fileSize = __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].fstatSync(fd).size;
20007
+ const state = {
20008
+ movie: null,
20009
+ tracks: [],
20010
+ trexDefaults: new Map(),
20011
+ fragmentDurations: new Map(),
20012
+ trafTrackId: 0,
20013
+ trafDefaultSampleDuration: 0
20014
+ };
20015
+ let offset = 0;
20016
+ while(offset + 8 <= fileSize){
20017
+ const header = readBoxHeader(fd, offset, fileSize);
20018
+ if (!header) break;
20019
+ if ("moov" === header.type || "moof" === header.type) {
20020
+ const bodyLength = header.size - header.headerSize;
20021
+ if (bodyLength > 0 && bodyLength <= MAX_METADATA_BOX_SIZE) {
20022
+ const body = Buffer.alloc(bodyLength);
20023
+ const read = __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].readSync(fd, body, 0, bodyLength, offset + header.headerSize);
20024
+ state.trafTrackId = 0;
20025
+ state.trafDefaultSampleDuration = 0;
20026
+ walkBoxes(body.subarray(0, read), 0, read, state);
20027
+ }
20028
+ }
20029
+ offset += header.size;
20030
+ }
20031
+ const { movie, tracks } = state;
20032
+ const video = tracks.find((t)=>"vide" === t.handler) || tracks.find((t)=>t.width > 0 && t.height > 0);
20033
+ if (!video) return null;
20034
+ let { width, height } = video;
20035
+ if (90 === video.rotation || 270 === video.rotation) [width, height] = [
20036
+ height,
20037
+ width
20038
+ ];
20039
+ return {
20040
+ width: Math.round(width),
20041
+ height: Math.round(height),
20042
+ duration: resolveDuration(movie, video, state.fragmentDurations),
20043
+ rotation: video.rotation,
20044
+ fileSize,
20045
+ codec: video.codec
20046
+ };
20047
+ } catch {
20048
+ return null;
20049
+ } finally{
20050
+ try {
20051
+ __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].closeSync(fd);
20052
+ } catch {}
20053
+ }
20054
+ }
20055
+ function walkBoxes(buf, start, end, state) {
20056
+ let off = start;
20057
+ while(off + 8 <= end){
20058
+ let size = buf.readUInt32BE(off);
20059
+ const type = buf.toString("latin1", off + 4, off + 8);
20060
+ let headerSize = 8;
20061
+ if (1 === size) {
20062
+ if (off + 16 > end) break;
20063
+ const hi = buf.readUInt32BE(off + 8);
20064
+ const lo = buf.readUInt32BE(off + 12);
20065
+ size = hi * 2 ** 32 + lo;
20066
+ headerSize = 16;
20067
+ } else if (0 === size) size = end - off;
20068
+ if (size < headerSize || off + size > end) break;
20069
+ const bodyStart = off + headerSize;
20070
+ const bodyEnd = off + size;
20071
+ switch(type){
20072
+ case "trak":
20073
+ case "mdia":
20074
+ case "minf":
20075
+ case "stbl":
20076
+ case "mvex":
20077
+ case "traf":
20078
+ walkBoxes(buf, bodyStart, bodyEnd, state);
20079
+ break;
20080
+ case "mvhd":
20081
+ state.movie = parseMvhd(buf, bodyStart, bodyEnd);
20082
+ break;
20083
+ case "tkhd":
20084
+ state.tracks.push({
20085
+ ...parseTkhd(buf, bodyStart, bodyEnd),
20086
+ handler: null,
20087
+ codec: null,
20088
+ timescale: 0,
20089
+ mdhdDuration: 0,
20090
+ sttsDuration: 0
20091
+ });
20092
+ break;
20093
+ case "mdhd":
20094
+ {
20095
+ const mdhd = parseMvhd(buf, bodyStart, bodyEnd);
20096
+ if (mdhd && state.tracks.length) {
20097
+ const track = state.tracks[state.tracks.length - 1];
20098
+ track.timescale = mdhd.timescale;
20099
+ track.mdhdDuration = mdhd.duration;
20100
+ }
20101
+ break;
20102
+ }
20103
+ case "hdlr":
20104
+ if (bodyEnd - bodyStart >= 12 && state.tracks.length) state.tracks[state.tracks.length - 1].handler = buf.toString("latin1", bodyStart + 8, bodyStart + 12);
20105
+ break;
20106
+ case "stsd":
20107
+ {
20108
+ const codec = parseStsdCodec(buf, bodyStart, bodyEnd);
20109
+ if (codec && state.tracks.length) state.tracks[state.tracks.length - 1].codec = codec;
20110
+ break;
20111
+ }
20112
+ case "stts":
20113
+ if (state.tracks.length) state.tracks[state.tracks.length - 1].sttsDuration = parseSttsDuration(buf, bodyStart, bodyEnd);
20114
+ break;
20115
+ case "trex":
20116
+ if (bodyStart + 20 > bodyEnd) break;
20117
+ state.trexDefaults.set(buf.readUInt32BE(bodyStart + 4), buf.readUInt32BE(bodyStart + 12));
20118
+ break;
20119
+ case "tfhd":
20120
+ {
20121
+ const tfhd = parseTfhd(buf, bodyStart, bodyEnd);
20122
+ state.trafTrackId = tfhd.trackId;
20123
+ state.trafDefaultSampleDuration = tfhd.defaultSampleDuration || state.trexDefaults.get(tfhd.trackId) || 0;
20124
+ break;
20125
+ }
20126
+ case "trun":
20127
+ {
20128
+ const duration = parseTrunDuration(buf, bodyStart, bodyEnd, state.trafDefaultSampleDuration);
20129
+ state.fragmentDurations.set(state.trafTrackId, (state.fragmentDurations.get(state.trafTrackId) || 0) + duration);
20130
+ break;
20131
+ }
20132
+ }
20133
+ off += size;
20134
+ }
20135
+ }
20136
+ const UNKNOWN_DURATION_32 = 0xffffffff;
20137
+ function isUsableDuration(duration) {
20138
+ return duration > 0 && duration !== UNKNOWN_DURATION_32;
20139
+ }
20140
+ function resolveDuration(movie, video, fragmentDurations) {
20141
+ if (movie && movie.timescale && isUsableDuration(movie.duration)) return movie.duration / movie.timescale;
20142
+ if (video.timescale) {
20143
+ if (isUsableDuration(video.mdhdDuration)) return video.mdhdDuration / video.timescale;
20144
+ if (video.sttsDuration > 0) return video.sttsDuration / video.timescale;
20145
+ const fragment = fragmentDurations.get(video.trackId) ?? (1 === fragmentDurations.size ? [
20146
+ ...fragmentDurations.values()
20147
+ ][0] : 0);
20148
+ if (fragment > 0) return fragment / video.timescale;
20149
+ }
20150
+ return 0;
20151
+ }
20152
+ function parseSttsDuration(buf, start, end) {
20153
+ if (start + 8 > end) return 0;
20154
+ const entryCount = buf.readUInt32BE(start + 4);
20155
+ let total = 0;
20156
+ for(let i = 0; i < entryCount; i++){
20157
+ const off = start + 8 + 8 * i;
20158
+ if (off + 8 > end) break;
20159
+ total += buf.readUInt32BE(off) * buf.readUInt32BE(off + 4);
20160
+ }
20161
+ return total;
20162
+ }
20163
+ function parseTfhd(buf, start, end) {
20164
+ if (start + 8 > end) return {
20165
+ trackId: 0,
20166
+ defaultSampleDuration: 0
20167
+ };
20168
+ const flags = buf.readUIntBE(start + 1, 3);
20169
+ const trackId = buf.readUInt32BE(start + 4);
20170
+ let off = start + 8;
20171
+ if (0x000001 & flags) off += 8;
20172
+ if (0x000002 & flags) off += 4;
20173
+ if (0x000008 & flags && off + 4 <= end) return {
20174
+ trackId,
20175
+ defaultSampleDuration: buf.readUInt32BE(off)
20176
+ };
20177
+ return {
20178
+ trackId,
20179
+ defaultSampleDuration: 0
20180
+ };
20181
+ }
20182
+ function parseTrunDuration(buf, start, end, defaultSampleDuration) {
20183
+ if (start + 8 > end) return 0;
20184
+ const flags = buf.readUIntBE(start + 1, 3);
20185
+ const sampleCount = buf.readUInt32BE(start + 4);
20186
+ let off = start + 8;
20187
+ if (0x000001 & flags) off += 4;
20188
+ if (0x000004 & flags) off += 4;
20189
+ const hasDuration = (0x000100 & flags) !== 0;
20190
+ if (!hasDuration) return sampleCount * defaultSampleDuration;
20191
+ const entrySize = 4 + ((0x000200 & flags) !== 0 ? 4 : 0) + ((0x000400 & flags) !== 0 ? 4 : 0) + ((0x000800 & flags) !== 0 ? 4 : 0);
20192
+ let total = 0;
20193
+ for(let i = 0; i < sampleCount; i++){
20194
+ const entryOff = off + i * entrySize;
20195
+ if (entryOff + 4 > end) break;
20196
+ total += buf.readUInt32BE(entryOff);
20197
+ }
20198
+ return total;
20199
+ }
20200
+ function parseStsdCodec(buf, start, end) {
20201
+ if (start + 16 > end) return null;
20202
+ if (0 === buf.readUInt32BE(start + 4)) return null;
20203
+ return buf.toString("latin1", start + 12, start + 16).toLowerCase();
20204
+ }
20205
+ function parseMvhd(buf, start, end) {
20206
+ const version = buf.readUInt8(start);
20207
+ if (1 === version) {
20208
+ if (start + 28 > end) return null;
20209
+ const timescale = buf.readUInt32BE(start + 20);
20210
+ const hi = buf.readUInt32BE(start + 24);
20211
+ const lo = buf.readUInt32BE(start + 28);
20212
+ return {
20213
+ timescale,
20214
+ duration: hi * 2 ** 32 + lo
20215
+ };
20216
+ }
20217
+ if (start + 20 > end) return null;
20218
+ return {
20219
+ timescale: buf.readUInt32BE(start + 12),
20220
+ duration: buf.readUInt32BE(start + 16)
20221
+ };
20222
+ }
20223
+ function parseTkhd(buf, start, end) {
20224
+ const version = buf.readUInt8(start);
20225
+ const afterDuration = 1 === version ? 36 : 24;
20226
+ const matrixOff = start + afterDuration + 16;
20227
+ const whOff = matrixOff + 36;
20228
+ const trackIdOff = start + (1 === version ? 20 : 12);
20229
+ const trackId = trackIdOff + 4 <= end ? buf.readUInt32BE(trackIdOff) : 0;
20230
+ if (whOff + 8 > end) return {
20231
+ trackId,
20232
+ width: 0,
20233
+ height: 0,
20234
+ rotation: 0
20235
+ };
20236
+ const width = buf.readUInt32BE(whOff) / 65536;
20237
+ const height = buf.readUInt32BE(whOff + 4) / 65536;
20238
+ const a = buf.readInt32BE(matrixOff) / 65536;
20239
+ const b = buf.readInt32BE(matrixOff + 4) / 65536;
20240
+ let rotation = 0;
20241
+ if (Math.abs(a) < 0.01 && Math.abs(b - 1) < 0.01) rotation = 90;
20242
+ else if (Math.abs(a + 1) < 0.01 && Math.abs(b) < 0.01) rotation = 180;
20243
+ else if (Math.abs(a) < 0.01 && Math.abs(b + 1) < 0.01) rotation = 270;
20244
+ return {
20245
+ trackId,
20246
+ width,
20247
+ height,
20248
+ rotation
20249
+ };
20250
+ }
20251
+ function parseVideoCodec(filePath) {
20252
+ return parseVideoMeta(filePath)?.codec ?? null;
20253
+ }
20254
+ function buildVideoMetaFromParams(filePath, metadata) {
20255
+ return {
20256
+ width: Math.round(metadata.width),
20257
+ height: Math.round(metadata.height),
20258
+ duration: metadata.duration,
20259
+ rotation: 0,
20260
+ fileSize: metadata.fileSize,
20261
+ codec: parseVideoCodec(filePath)
20262
+ };
20263
+ }
20264
+ const MAX_DURATION_SECONDS = 28800;
20265
+ const MAX_FILE_SIZE = 21474836480;
20266
+ const ALLOWED_EXTENSIONS = [
20267
+ ".mp4"
20268
+ ];
20269
+ const ALLOWED_CODECS = [
20270
+ "avc1",
20271
+ "avc3"
20272
+ ];
20273
+ const MIN_TITLE_LENGTH = 6;
20274
+ const MAX_TITLE_LENGTH = 16;
20275
+ function formatFileSize(bytes) {
20276
+ if (bytes < 1048576) return `${(bytes / 1024).toFixed(2)} KB`;
20277
+ if (bytes < 1073741824) return `${(bytes / 1024 / 1024).toFixed(2)} MB`;
20278
+ return `${(bytes / 1024 / 1024 / 1024).toFixed(2)} GB`;
20279
+ }
20280
+ function formatDuration(seconds) {
20281
+ const total = Math.round(seconds);
20282
+ const h = Math.floor(total / 3600);
20283
+ const m = Math.floor(total % 3600 / 60);
20284
+ const s = total % 60;
20285
+ if (h > 0) return `${h}小时${m}分${s}秒`;
20286
+ if (m > 0) return `${m}分${s}秒`;
20287
+ return `${s}秒`;
20288
+ }
20289
+ function validateShipinhaoVideo(filePath, meta) {
20290
+ const fileName = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].basename(filePath);
20291
+ const ext = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].extname(fileName).toLowerCase();
20292
+ if (!ALLOWED_EXTENSIONS.includes(ext)) return `视频格式不支持:${fileName}。视频号仅支持 MP4/H.264 格式,请转换后重试。`;
20293
+ if (meta.duration > MAX_DURATION_SECONDS) return `视频时长超过限制:${fileName}(${formatDuration(meta.duration)})。视频号视频时长不能超过 8 小时,请剪辑后重试。`;
20294
+ if (meta.fileSize > MAX_FILE_SIZE) return `视频大小超过限制:${fileName}(${formatFileSize(meta.fileSize)})。视频号视频不能超过 20GB,请压缩后重试。`;
20295
+ if (meta.codec && !ALLOWED_CODECS.includes(meta.codec)) return `视频编码不支持:${fileName}(${meta.codec})。视频号仅支持 H.264 编码,请转码后重试。`;
20296
+ return null;
20297
+ }
20298
+ function validateShipinhaoTitle(title) {
20299
+ if (void 0 === title) return null;
20300
+ const trimmed = title.trim();
20301
+ if ("" === trimmed) return null;
20302
+ const length = [
20303
+ ...trimmed
20304
+ ].length;
20305
+ if (length < MIN_TITLE_LENGTH || length > MAX_TITLE_LENGTH) return `视频号标题需要在 ${MIN_TITLE_LENGTH}-${MAX_TITLE_LENGTH} 个字符之间,当前 ${length} 个字符,请调整后重试。`;
20306
+ return null;
20307
+ }
20308
+ const POST_CREATE_PAGE_URL = "https://channels.weixin.qq.com/micro/content/post/create";
20309
+ const MICRO_CONTENT_BASE = "https://channels.weixin.qq.com/micro/content/cgi-bin/mmfinderassistant-bin";
20310
+ function resolveClientContext(params, fallbackUin) {
20311
+ const extra = params.extraParam || {};
20312
+ const deviceIdCookie = params.cookies.find((c)=>"device_id" === c.name || "finger_print_device_id" === c.name)?.value;
20313
+ return {
20314
+ aId: "string" == typeof extra.aId ? extra.aId : "",
20315
+ fingerPrintDeviceId: "string" == typeof extra.fingerPrintDeviceId ? extra.fingerPrintDeviceId : deviceIdCookie || "",
20316
+ uin: "string" == typeof extra.uin ? extra.uin : String(fallbackUin)
20317
+ };
20318
+ }
20319
+ function buildPublishHeaders(cookieString, client) {
20320
+ const headers = {
20321
+ cookie: cookieString,
20322
+ referer: POST_CREATE_PAGE_URL,
20323
+ origin: "https://channels.weixin.qq.com",
20324
+ "content-type": "application/json"
20325
+ };
20326
+ if (client.fingerPrintDeviceId) headers["finger-print-device-id"] = client.fingerPrintDeviceId;
20327
+ if (client.uin) headers["x-wechat-uin"] = client.uin;
20328
+ return headers;
20329
+ }
20330
+ function buildPublishQuery(client) {
20331
+ const query = {
20332
+ _rid: rid(),
20333
+ _pageUrl: POST_CREATE_PAGE_URL
20334
+ };
20335
+ if (client.aId) query._aid = client.aId;
20336
+ return query;
20337
+ }
20338
+ function buildCommonBody(finderUsername) {
20339
+ return {
20340
+ timestamp: String(Date.now()),
20341
+ _log_finder_uin: "",
20342
+ _log_finder_id: finderUsername,
20343
+ rawKeyBuff: "",
20344
+ pluginSessionId: null,
20345
+ scene: 7,
20346
+ reqScene: 7
20347
+ };
20348
+ }
20349
+ async function getTraceKey(auth, client, http, logger) {
20350
+ logger.info("[getTraceKey] 开始获取 traceKey...");
20351
+ const res = await http.api({
20352
+ method: "POST",
20353
+ url: `${MICRO_CONTENT_BASE}/post/get-finder-post-trace-key`,
20354
+ params: buildPublishQuery(client),
20355
+ data: {
20356
+ objectId: "",
20357
+ ...buildCommonBody(auth.finderUsername)
20358
+ },
20359
+ defaultErrorMsg: "获取 traceKey 失败"
20360
+ });
20361
+ if (0 !== res.errCode || !res.data?.traceKey) {
20362
+ logger.error("[getTraceKey] 获取失败:", JSON.stringify(res));
20363
+ throw new Error(`获取 traceKey 失败: ${JSON.stringify(res)}`);
20364
+ }
20365
+ logger.info(`[getTraceKey] 获取成功: ${res.data.traceKey}`);
20366
+ return res.data.traceKey;
20367
+ }
20368
+ async function getObjectTagKey(auth, client, http, logger) {
20369
+ logger.info("[getObjectTagKey] 获取内容声明 tagKey...");
20370
+ try {
20371
+ const res = await http.api({
20372
+ method: "POST",
20373
+ url: `${MICRO_CONTENT_BASE}/post/finder_get_object_tag_list`,
20374
+ params: buildPublishQuery(client),
20375
+ data: {
20376
+ source: 1,
20377
+ ...buildCommonBody(auth.finderUsername)
20378
+ },
20379
+ defaultErrorMsg: "获取内容声明标注失败"
20380
+ });
20381
+ if (0 !== res.errCode || !res.data?.tagKey) {
20382
+ logger.warn(`[getObjectTagKey] 未取到 tagKey: ${JSON.stringify(res)}`);
20383
+ return null;
20384
+ }
20385
+ logger.info(`[getObjectTagKey] tagKey: ${res.data.tagKey}`);
20386
+ return res.data.tagKey;
20387
+ } catch (error) {
20388
+ logger.warn(`[getObjectTagKey] 获取 tagKey 异常: ${stringifyError(error)}`);
20389
+ return null;
20390
+ }
20391
+ }
20392
+ async function submitAndPollTranscode(opts) {
20393
+ const { videoUrl, videoMeta, traceKey, uploadStartTime, uploadEndTime, finderUsername, client, http, logger } = opts;
20394
+ logger.info("[submitAndPollTranscode] 开始提交转码任务...");
20395
+ const finderUrl = videoUrl.includes("wxapp.tc.qq.com") ? `https://finder.video.qq.com${videoUrl.split("qq.com")[1]}` : videoUrl;
20396
+ logger.info(`[submitAndPollTranscode] 视频尺寸: ${videoMeta.width}x${videoMeta.height}, 时长: ${videoMeta.duration}s`);
20397
+ const submitRes = await http.api({
20398
+ method: "POST",
20399
+ url: `${MICRO_CONTENT_BASE}/post/post_clip_video`,
20400
+ params: buildPublishQuery(client),
20401
+ data: {
20402
+ url: finderUrl,
20403
+ timeStart: 0,
20404
+ cropDuration: 0,
20405
+ height: videoMeta.height,
20406
+ width: videoMeta.width,
20407
+ x: 0,
20408
+ y: 0,
20409
+ clipOriginVideoInfo: {
20410
+ width: videoMeta.width,
20411
+ height: videoMeta.height,
20412
+ duration: videoMeta.duration,
20413
+ fileSize: videoMeta.fileSize
20414
+ },
20415
+ traceInfo: {
20416
+ traceKey,
20417
+ uploadCdnStart: uploadStartTime,
20418
+ uploadCdnEnd: uploadEndTime
20419
+ },
20420
+ targetWidth: videoMeta.width,
20421
+ targetHeight: videoMeta.height,
20422
+ type: 4,
20423
+ useAstraThumbCover: 1,
20424
+ ...buildCommonBody(finderUsername)
20425
+ },
20426
+ defaultErrorMsg: "提交转码失败"
20427
+ });
20428
+ if (0 !== submitRes.errCode || !submitRes.data?.clipKey) {
20429
+ logger.error("[submitAndPollTranscode] 提交转码失败:", JSON.stringify(submitRes));
20430
+ throw new Error(`提交转码失败: ${JSON.stringify(submitRes)}`);
20431
+ }
20432
+ const { clipKey, draftId } = submitRes.data;
20433
+ logger.info(`[submitAndPollTranscode] 转码任务已提交,clipKey: ${clipKey}, draftId: ${draftId}`);
20434
+ const pollInterval = 5000;
20435
+ const pollBudget = Math.min(1800000, 300000 + 1000 * Math.ceil(1.5 * videoMeta.duration));
20436
+ const maxPolls = Math.ceil(pollBudget / pollInterval);
20437
+ let pollCount = 0;
20438
+ logger.info(`[submitAndPollTranscode] 开始轮询转码结果,最多 ${maxPolls} 次(${Math.round(pollBudget / 1000)}s),间隔 ${pollInterval / 1000}s`);
20439
+ while(pollCount < maxPolls){
20440
+ await sleep(pollInterval);
20441
+ pollCount++;
20442
+ const pollRes = await http.api({
20443
+ method: "POST",
20444
+ url: `${MICRO_CONTENT_BASE}/post/post_clip_video_result`,
20445
+ params: buildPublishQuery(client),
20446
+ data: {
20447
+ clipKey,
20448
+ draftId,
20449
+ ...buildCommonBody(finderUsername)
20450
+ },
20451
+ defaultErrorMsg: "转码轮询失败"
20452
+ }, {
20453
+ timeout: 60000,
20454
+ retries: 2,
20455
+ retryDelay: 3000
20456
+ });
20457
+ if (0 !== pollRes.errCode) {
20458
+ logger.error(`[submitAndPollTranscode] 转码轮询失败 (poll ${pollCount}):`, JSON.stringify(pollRes));
20459
+ throw new Error(`转码轮询失败 (poll ${pollCount}): ${JSON.stringify(pollRes)}`);
20460
+ }
20461
+ const { flag, url, width, height, duration, md5, fileSize } = pollRes.data || {};
20462
+ logger.info(`[submitAndPollTranscode] 轮询第 ${pollCount} 次,flag=${flag}`);
20463
+ if (1 === flag) {
20464
+ if (!url || !width || !height || !duration || !md5 || !fileSize) {
20465
+ logger.error("[submitAndPollTranscode] 转码完成但返回数据不完整:", JSON.stringify(pollRes.data));
20466
+ throw new Error(`转码完成但返回数据不完整: ${JSON.stringify(pollRes.data)}`);
20467
+ }
20468
+ logger.info(`[submitAndPollTranscode] 转码完成! 用时: ${pollCount * pollInterval / 1000}s`);
20469
+ logger.info(`[submitAndPollTranscode] 视频信息: ${width}x${height}, 时长: ${duration}s, 大小: ${fileSize}`);
20470
+ return {
20471
+ clipKey,
20472
+ url,
20473
+ width,
20474
+ height,
20475
+ duration,
20476
+ md5,
20477
+ fileSize
20478
+ };
20479
+ }
20480
+ if (2 === flag) logger.info(`[submitAndPollTranscode] 转码中... (${pollCount}/${maxPolls})`);
20481
+ else {
20482
+ logger.error(`[submitAndPollTranscode] 转码失败,未知 flag=${flag}:`, JSON.stringify(pollRes.data));
20483
+ throw new Error(`转码失败,未知 flag=${flag}: ${JSON.stringify(pollRes.data)}`);
20484
+ }
20485
+ }
20486
+ logger.error(`[submitAndPollTranscode] 转码超时,已轮询 ${maxPolls} 次,用时: ${maxPolls * pollInterval / 1000}s`);
20487
+ throw new Error(`转码超时 (${maxPolls * pollInterval / 1000}s)`);
20488
+ }
20489
+ async function publishVideo(opts) {
20490
+ const { params, auth, client, clipResult, videoUpload, coverUpload, verticalCoverUpload, videoMeta, traceKey, tagKey, uploadStartTime, uploadEndTime, proxyHttp, logger } = opts;
20491
+ logger.info("[publishVideo] 开始构建发布请求...");
20492
+ const toFinderUrl = (url)=>url.includes("wxapp.tc.qq.com") ? `https://finder.video.qq.com${url.split("qq.com")[1]}` : url;
20493
+ const thumbFinderUrl = toFinderUrl(coverUpload.downloadUrl);
20494
+ const coverFinderUrl = toFinderUrl(verticalCoverUpload.downloadUrl);
20495
+ const md5sumUuid = __WEBPACK_EXTERNAL_MODULE_node_crypto_9ba42079__["default"].randomUUID();
20496
+ const description = params.description;
20497
+ logger.info("[publishVideo] 发布参数:");
20498
+ logger.info(` - 短标题: ${params.title || "(无)"}`);
20499
+ logger.info(` - 描述: ${description.substring(0, 50)}${description.length > 50 ? "..." : ""}`);
20500
+ logger.info(` - 定时发布: ${params.scheduledTime ? new Date(1000 * params.scheduledTime).toLocaleString() : "立即发布"}`);
20501
+ const objectDesc = {
20502
+ mpTitle: "",
20503
+ description,
20504
+ extReading: buildExtReading(params.link),
20505
+ mediaType: 4,
20506
+ location: payload_buildLocation(params.location),
20507
+ topic: buildTopic({
20508
+ description: params.description,
20509
+ topics: params.topics,
20510
+ mentionedUsers: params.mentionedUsers,
20511
+ collection: params.collection
20512
+ }),
20513
+ event: buildEvent(params.event),
20514
+ mentionedUser: buildMentionedUser(params.mentionedUsers),
20515
+ media: [
20516
+ {
20517
+ url: clipResult.url,
20518
+ fileSize: clipResult.fileSize,
20519
+ thumbUrl: thumbFinderUrl,
20520
+ fullThumbUrl: thumbFinderUrl,
20521
+ coverUrl: coverFinderUrl,
20522
+ fullCoverUrl: coverFinderUrl,
20523
+ shareCoverUrl: coverFinderUrl,
20524
+ mediaType: 4,
20525
+ videoPlayLen: Math.round(clipResult.duration),
20526
+ width: clipResult.width,
20527
+ height: clipResult.height,
20528
+ md5sum: md5sumUuid,
20529
+ cardShowStyle: 2,
20530
+ urlCdnTaskId: clipResult.clipKey
20531
+ }
20532
+ ],
20533
+ shortTitle: params.title ? [
20534
+ {
20535
+ shortTitle: params.title
20536
+ }
20537
+ ] : [],
20538
+ member: {}
20539
+ };
20540
+ const publishData = {
20541
+ objectType: 0,
20542
+ longitude: 0,
20543
+ latitude: 0,
20544
+ feedLongitude: 0,
20545
+ feedLatitude: 0,
20546
+ originalFlag: params.originalFlag ?? 0,
20547
+ topics: params.topics || [],
20548
+ isFullPost: 1,
20549
+ handleFlag: 2,
20550
+ videoClipTaskId: clipResult.clipKey,
20551
+ traceInfo: {
20552
+ traceKey,
20553
+ uploadCdnStart: uploadStartTime,
20554
+ uploadCdnEnd: uploadEndTime
20555
+ },
20556
+ objectDesc,
20557
+ report: {
20558
+ clipKey: clipResult.clipKey,
20559
+ draftId: clipResult.clipKey,
20560
+ ...buildCommonBody(auth.finderUsername),
20561
+ height: videoMeta.height,
20562
+ width: videoMeta.width,
20563
+ duration: videoMeta.duration,
20564
+ fileSize: videoUpload.fileSize,
20565
+ uploadCost: (uploadEndTime - uploadStartTime) * 1000
20566
+ },
20567
+ postFlag: 0,
20568
+ mode: 1,
20569
+ clientid: __WEBPACK_EXTERNAL_MODULE_node_crypto_9ba42079__["default"].randomUUID(),
20570
+ ...buildCommonBody(auth.finderUsername)
20571
+ };
20572
+ if (params.scheduledTime) publishData.effectiveTime = params.scheduledTime;
20573
+ if (params.tagInfo && tagKey) publishData.tagInfo = buildTagInfo(params.tagInfo, tagKey);
20574
+ logger.info("[publishVideo] 开始发布视频,全部参数:" + JSON.stringify(publishData));
20575
+ const publishRes = await proxyHttp.api({
20576
+ method: "POST",
20577
+ url: `${MICRO_CONTENT_BASE}/post/post_create`,
20578
+ params: buildPublishQuery(client),
20579
+ data: publishData,
20580
+ defaultErrorMsg: "发布视频失败"
20581
+ });
20582
+ logger.info(`[publishVideo] 发布响应: errCode=${publishRes.errCode}, baseResp.errcode=${publishRes.data?.baseResp?.errcode}`);
20583
+ return publishRes;
20584
+ }
20585
+ function sleep(ms) {
20586
+ return new Promise((resolve)=>setTimeout(resolve, ms));
20587
+ }
20588
+ async function resolveLocalCoverPath(coverPath, label, tmpCachePath, logger) {
20589
+ if (!/^https?:\/\//i.test(coverPath)) return coverPath;
20590
+ const fileName = (0, __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_f7afdc8c__.getFilenameFromUrl)(coverPath);
20591
+ const savePath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(tmpCachePath, `${Date.now()}-${label}-${fileName}`);
20592
+ await (0, __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_f7afdc8c__.downloadImage)(coverPath, savePath);
20593
+ return savePath;
20594
+ }
20595
+ const shipinhaoPublishVideo_mock_mockAction = async (task, params)=>{
20596
+ task.logger.info("[shipinhaoPublishVideo] 开始执行视频号视频发布 - Mock API 方式");
20597
+ const updateTaskState = task.taskStageStore?.update?.bind(task.taskStageStore, task.taskId || "");
20598
+ let currentStep = "初始化";
20599
+ try {
20600
+ task.logger.info(`[shipinhaoPublishVideo] 发布方式: ${params.scheduledTime ? `定时 ${new Date(1000 * params.scheduledTime).toLocaleString()}` : "立即发布"}`);
20601
+ currentStep = "解析认证信息";
20602
+ const cookieString = params.cookies.map((c)=>`${c.name}=${c.value}`).join("; ");
20603
+ const http = new Http({
20604
+ headers: {
20605
+ cookie: cookieString
20606
+ }
20607
+ });
20608
+ currentStep = "验证发布参数";
20609
+ if (!params.videoPath) return (0, __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_f7afdc8c__.response)(414, "视频文件路径不能为空", "");
20610
+ if (!params.coverPath) return (0, __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_f7afdc8c__.response)(414, "横屏封面图片路径不能为空", "");
20611
+ currentStep = "获取上传认证";
20612
+ task.logger.info("[shipinhaoPublishVideo] 获取上传认证...");
20613
+ const auth = await getShipinhaoUploadAuth(cookieString, http);
20614
+ const client = resolveClientContext(params, auth.uin);
20615
+ if (!client.aId) task.logger.warn("[shipinhaoPublishVideo] extraParam.aId 缺失,query 将不带 _aid");
20616
+ if (!client.fingerPrintDeviceId) task.logger.warn("[shipinhaoPublishVideo] extraParam.fingerPrintDeviceId 缺失,请求将不带 finger-print-device-id");
20617
+ const publishHeaders = buildPublishHeaders(cookieString, client);
20618
+ const microHttp = new Http({
20619
+ headers: publishHeaders
20620
+ });
20621
+ const args = [
20622
+ {
20623
+ headers: publishHeaders
20624
+ },
20625
+ task.logger,
20626
+ params.proxyLoc,
20627
+ params.accountId,
20628
+ "shipinhao"
20629
+ ];
20630
+ const proxyHttp = new Http(...args);
20631
+ currentStep = "组装视频元数据";
20632
+ task.logger.info("[shipinhaoPublishVideo] 组装视频元数据...");
20633
+ const videoMeta = buildVideoMetaFromParams(params.videoPath, params.videoMetadata);
20634
+ task.logger.info(`[shipinhaoPublishVideo] 视频: ${videoMeta.width}×${videoMeta.height}, ${videoMeta.duration.toFixed(2)}s, ${(videoMeta.fileSize / 1024 / 1024).toFixed(2)}MB, codec=${videoMeta.codec || "unknown"}`);
20635
+ if (!videoMeta.codec) task.logger.warn("[shipinhaoPublishVideo] 未能读取视频编码格式,跳过 H.264 预检,交由服务端判断");
20636
+ currentStep = "校验视频限制";
20637
+ const validationError = validateShipinhaoVideo(params.videoPath, videoMeta);
20638
+ if (validationError) {
20639
+ task.logger.error(`[shipinhaoPublishVideo] 视频校验未通过: ${validationError}`);
20640
+ await updateTaskState?.({
20641
+ state: __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_f7afdc8c__.TaskState.FAILED,
20642
+ error: validationError
20643
+ });
20644
+ return (0, __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_f7afdc8c__.response)(414, validationError, "");
20645
+ }
20646
+ task.logger.info("[shipinhaoPublishVideo] 视频校验通过");
20647
+ currentStep = "校验标题";
20648
+ const titleError = validateShipinhaoTitle(params.title);
20649
+ if (titleError) {
20650
+ task.logger.error(`[shipinhaoPublishVideo] 标题校验未通过: ${titleError}`);
20651
+ await updateTaskState?.({
20652
+ state: __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_f7afdc8c__.TaskState.FAILED,
20653
+ error: titleError
20654
+ });
20655
+ return (0, __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_f7afdc8c__.response)(414, titleError, "");
20656
+ }
20657
+ currentStep = "获取 traceKey";
20658
+ task.logger.info("[shipinhaoPublishVideo] 获取 traceKey...");
20659
+ const traceKey = await getTraceKey(auth, client, microHttp, task.logger);
20660
+ let tagKey = null;
20661
+ if (params.tagInfo) {
20662
+ currentStep = "获取内容声明 tagKey";
20663
+ tagKey = await getObjectTagKey(auth, client, microHttp, task.logger);
20664
+ }
20665
+ const uploadStartTime = Math.floor(Date.now() / 1000);
20666
+ task.logger.info(`[shipinhaoPublishVideo] 上传开始时间: ${uploadStartTime}`);
20667
+ currentStep = "上传视频";
20668
+ task.logger.info("[shipinhaoPublishVideo] 上传视频...");
20669
+ task.logger.info(`[shipinhaoPublishVideo] 视频路径: ${params.videoPath}`);
20670
+ task.logger.info(`[shipinhaoPublishVideo] 视频文件类型: ${auth.videoFileType}`);
20671
+ const videoUpload = await uploader_uploadFile({
20672
+ filePath: params.videoPath,
20673
+ fileType: auth.videoFileType,
20674
+ uin: auth.uin,
20675
+ authKey: auth.authKey,
20676
+ http,
20677
+ logger: task.logger
20678
+ });
20679
+ task.logger.info("[shipinhaoPublishVideo] 视频上传完成");
20680
+ const uploadEndTime = Math.floor(Date.now() / 1000);
20681
+ task.logger.info(`[shipinhaoPublishVideo] 上传结束时间: ${uploadEndTime}, 耗时: ${uploadEndTime - uploadStartTime}s`);
20682
+ currentStep = "上传横屏封面";
20683
+ const localCoverPath = await resolveLocalCoverPath(params.coverPath, "横屏封面", task.getTmpPath(), task.logger);
20684
+ task.logger.info("[shipinhaoPublishVideo] 上传横屏封面...");
20685
+ const coverUpload = await uploader_uploadFile({
20686
+ filePath: localCoverPath,
20687
+ fileType: auth.pictureFileType,
20688
+ uin: auth.uin,
20689
+ authKey: auth.authKey,
20690
+ http,
20691
+ logger: task.logger
20692
+ });
20693
+ task.logger.info("[shipinhaoPublishVideo] 横屏封面上传完成");
20694
+ let verticalCoverUpload = coverUpload;
20695
+ if (params.verticalCoverPath) {
20696
+ currentStep = "上传竖屏封面";
20697
+ const localVerticalPath = await resolveLocalCoverPath(params.verticalCoverPath, "竖屏封面", task.getTmpPath(), task.logger);
20698
+ task.logger.info("[shipinhaoPublishVideo] 上传竖屏封面");
20699
+ verticalCoverUpload = await uploader_uploadFile({
20700
+ filePath: localVerticalPath,
20701
+ fileType: auth.pictureFileType,
20702
+ uin: auth.uin,
20703
+ authKey: auth.authKey,
20704
+ http,
20705
+ logger: task.logger
20706
+ });
20707
+ task.logger.info("[shipinhaoPublishVideo] 竖屏封面上传完成");
20708
+ } else task.logger.info("[shipinhaoPublishVideo] 未传竖屏封面,复用横屏封面");
20709
+ currentStep = "提交转码";
20710
+ task.logger.info("[shipinhaoPublishVideo] 提交转码...");
20711
+ const clipResult = await submitAndPollTranscode({
20712
+ videoUrl: videoUpload.downloadUrl,
20713
+ videoMeta,
20714
+ traceKey,
20715
+ uploadStartTime,
20716
+ uploadEndTime,
20717
+ finderUsername: auth.finderUsername,
20718
+ client,
20719
+ http: microHttp,
20720
+ logger: task.logger
20721
+ });
20722
+ currentStep = "发布视频";
20723
+ task.logger.info("[shipinhaoPublishVideo] 发布视频...");
20724
+ task.logger.info(`[shipinhaoPublishVideo] clipKey: ${clipResult.clipKey}`);
20725
+ let publishResult;
20726
+ try {
20727
+ publishResult = await publishVideo({
20728
+ params,
20729
+ auth,
20730
+ client,
20731
+ clipResult,
20732
+ videoUpload,
20733
+ coverUpload,
20734
+ verticalCoverUpload,
20735
+ videoMeta,
20736
+ traceKey,
20737
+ tagKey,
20738
+ uploadStartTime,
20739
+ uploadEndTime,
20740
+ proxyHttp,
20741
+ logger: task.logger
20742
+ });
20743
+ } catch (error) {
20744
+ const handledError = Http.handleApiError(error);
20745
+ task.logger.error(`[shipinhaoPublishVideo] 发布请求失败: ${handledError.message}`, stringifyError(handledError));
20746
+ const classified = classifyPublishError(handledError);
20747
+ if (classified) {
20748
+ const message = `${classified.userMessage}${task.debug ? ` ${http.proxyInfo}` : ""}`;
20749
+ task.logger.error(`[shipinhaoPublishVideo] ${classified.category},直接返回: ${handledError.message} (code=${handledError.code})`, stringifyError(handledError));
20750
+ await updateTaskState?.({
20751
+ state: __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_f7afdc8c__.TaskState.FAILED,
20752
+ error: message
20753
+ });
20754
+ return {
20755
+ code: 414,
20756
+ data: "",
20757
+ message
20758
+ };
20759
+ }
20760
+ throw error;
20761
+ }
20762
+ task.logger.info(`[shipinhaoPublishVideo] publishResult: ${JSON.stringify(publishResult)}`);
20763
+ const resultCode = publishResult.data?.baseResp?.errcode ?? publishResult.errCode;
20764
+ const resultMsg = publishResult.data?.baseResp?.errmsg ?? (0 === resultCode ? "发布成功" : `发布失败(errCode=${resultCode})`);
20765
+ if (0 === resultCode) {
20766
+ task.logger.info("[shipinhaoPublishVideo] 发布成功");
20767
+ task.logger.info(`[shipinhaoPublishVideo] 作品ID: ${clipResult.clipKey}`);
20768
+ task.logger.info(`[shipinhaoPublishVideo] 视频URL: ${clipResult.url}`);
20769
+ task.logger.info(`[shipinhaoPublishVideo] 横屏封面URL: ${coverUpload.downloadUrl}`);
20770
+ task.logger.info(`[shipinhaoPublishVideo] 竖屏封面URL: ${verticalCoverUpload.downloadUrl}`);
20771
+ await updateTaskState?.({
20772
+ state: __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_f7afdc8c__.TaskState.SUCCESS,
20773
+ result: {
20774
+ response: resultMsg
20775
+ }
20776
+ });
20777
+ reportLogger({
20778
+ token: params.huiwenToken || "",
20779
+ enverionment: task.enverionment || "development",
20780
+ postId: params.articleId,
20781
+ eip: proxyHttp.proxyInfo,
20782
+ accountId: params.accountId,
20783
+ uid: params.uid,
20784
+ publishParams: {
20785
+ videoPath: params.videoPath,
20786
+ coverPath: params.coverPath,
20787
+ verticalCoverPath: params.verticalCoverPath,
20788
+ title: params.title,
20789
+ topics: params.topics,
20790
+ mentionedUsers: params.mentionedUsers,
20791
+ collection: params.collection,
20792
+ event: params.event,
20793
+ link: params.link,
20794
+ tagInfo: params.tagInfo,
20795
+ originalFlag: params.originalFlag,
20796
+ scheduledTime: params.scheduledTime
20797
+ },
20798
+ platform: "shipinhao"
20799
+ });
20800
+ task.logger.info("[shipinhaoPublishVideo] 日志上报完成");
20801
+ return (0, __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_f7afdc8c__.response)(0, "发布成功", clipResult.clipKey);
20802
+ }
20803
+ let errorMessage = resultMsg;
20804
+ if (-11224 === resultCode) errorMessage = "视频号管理员完成实名且绑定手机号后才可以发表";
20805
+ else if (300333 === resultCode || 300334 === resultCode) errorMessage = "登录失效";
20806
+ else if (300330 === resultCode) errorMessage = "未登录";
20807
+ else if (300002 === resultCode) errorMessage = "官方平台在校验音乐/位置/定时信息时失败了,请重新编辑后发布";
20808
+ task.logger.error(`[shipinhaoPublishVideo] 发布失败: ${errorMessage} (errCode=${resultCode})`);
20809
+ await updateTaskState?.({
20810
+ state: __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_f7afdc8c__.TaskState.FAILED,
20811
+ error: errorMessage
20812
+ });
20813
+ return (0, __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_f7afdc8c__.response)(resultCode || 414, errorMessage, "");
20814
+ } catch (error) {
20815
+ const handledError = Http.handleApiError(error);
20816
+ const errorMsg = handledError.message || "发布失败,请稍后重试";
20817
+ const errorCode = handledError.code || 414;
20818
+ task.logger.error(`[shipinhaoPublishVideo] 发布流程异常 [${currentStep}]: ${errorMsg}`, stringifyError(error), handledError.extra);
20819
+ task.logger.error(`[shipinhaoPublishVideo] 错误码: ${errorCode}, 当前步骤: ${currentStep}`);
20820
+ await updateTaskState?.({
20821
+ state: __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_f7afdc8c__.TaskState.FAILED,
20822
+ error: errorMsg
20823
+ });
20824
+ return (0, __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_f7afdc8c__.response)(errorCode, errorMsg, "");
20825
+ }
20826
+ };
20827
+ const shipinhaoPublishVideo_rpa_rpaAction = async (task, params)=>{
20828
+ task.logger.info("开始微信视频号视频发布(RPA 模式)");
20829
+ const videoMeta = buildVideoMetaFromParams(params.videoPath, params.videoMetadata);
20830
+ task.logger.info(`视频: ${videoMeta.width}×${videoMeta.height}, ${videoMeta.duration.toFixed(2)}s, ${(videoMeta.fileSize / 1024 / 1024).toFixed(2)}MB, codec=${videoMeta.codec || "unknown"}`);
20831
+ if (!videoMeta.codec) task.logger.warn("未能读取视频编码格式,跳过 H.264 预检,交由服务端判断");
20832
+ const validationError = validateShipinhaoVideo(params.videoPath, videoMeta);
20833
+ if (validationError) {
20834
+ task.logger.error(`视频校验未通过: ${validationError}`);
20835
+ return (0, __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_f7afdc8c__.response)(414, validationError, "");
20836
+ }
20837
+ task.logger.info("视频校验通过");
20838
+ const titleError = validateShipinhaoTitle(params.title);
20839
+ if (titleError) {
20840
+ task.logger.error(`标题校验未通过: ${titleError}`);
20841
+ return (0, __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_f7afdc8c__.response)(414, titleError, "");
20842
+ }
20843
+ const unsupported = [
20844
+ params.verticalCoverPath && "verticalCoverPath",
20845
+ params.collection && "collection",
20846
+ params.originalFlag && "originalFlag",
20847
+ params.postWithMemberZoneLink && "postWithMemberZoneLink"
20848
+ ].filter(Boolean);
20849
+ if (unsupported.length) task.logger.warn(`RPA 模式不支持以下参数,将被忽略: ${unsupported.join("、")};如需生效请使用 mockApi 模式`);
20850
+ if (params.tagInfo && 5 === params.tagInfo.tagType) {
20851
+ const shootInfo = params.tagInfo.shootInfo;
20852
+ if (shootInfo && (shootInfo.provinceCode || shootInfo.cityCode)) task.logger.warn("tagInfo.tagType=5 在 RPA 模式下仅支持拍摄时间和国家选择,省市选择需要使用 mockApi 模式");
20853
+ }
20854
+ const tmpCachePath = task.getTmpPath();
20855
+ const page = await task.createPage({
20856
+ url: "https://channels.weixin.qq.com/platform/post/create",
20857
+ show: task.debug,
20858
+ cookies: params.cookies
20859
+ });
20860
+ try {
20861
+ const waitForElement = async (selector, timeout = 10000)=>{
20862
+ try {
20863
+ const element = page.locator(selector);
20864
+ await element.waitFor({
20865
+ state: "visible",
20866
+ timeout
20867
+ });
20868
+ return element;
20869
+ } catch {
20870
+ task.logger.warn(`元素未找到: ${selector}`);
20871
+ return null;
20872
+ }
20873
+ };
20874
+ const retryAction = async (action, maxRetries = 3, delay = 1000)=>{
20875
+ let lastError;
20876
+ for(let i = 0; i < maxRetries; i++)try {
20877
+ return await action();
20878
+ } catch (error) {
20879
+ lastError = error;
20880
+ task.logger.warn(`重试 ${i + 1}/${maxRetries}: ${lastError.message}`);
20881
+ if (i < maxRetries - 1) await page.waitForTimeout(delay);
20882
+ }
20883
+ throw lastError;
20884
+ };
20885
+ task.logger.info("等待页面加载...");
20886
+ task.logger.info("检查登录状态...");
20887
+ if (task.debug) {
20888
+ task.logger.info(`当前页面 URL: ${page.url()}`);
20889
+ const title = await page.title();
20890
+ task.logger.info(`页面标题: ${title}`);
20891
+ }
20892
+ try {
20893
+ await page.waitForSelector(".post-edit-wrap", {
20894
+ state: "visible",
20895
+ timeout: 30000
20896
+ });
20897
+ task.logger.info("✓ 登录状态正常,找到编辑器容器");
20898
+ } catch {
20899
+ task.logger.error("✗ 未找到编辑器,可能登录失效");
20900
+ return {
20901
+ code: 414,
20902
+ message: "登录失效或页面加载异常",
20903
+ data: page.url()
20904
+ };
20905
+ }
20906
+ task.logger.info("页面加载完成,开始填充内容");
20907
+ task.logger.info("开始上传视频");
20908
+ await retryAction(async ()=>{
20909
+ const videoUploadSelectors = [
20910
+ '.ant-upload-btn input[type="file"][accept*="video"]',
20911
+ '.upload input[type="file"][accept*="video"]',
20912
+ 'input[type="file"][accept*="video"]'
20913
+ ];
20914
+ let uploadInput = null;
20915
+ if (task.debug) {
20916
+ const allFileInputs = await page.locator('input[type="file"]').count();
20917
+ task.logger.info(`页面中共找到 ${allFileInputs} 个文件上传输入框`);
20918
+ }
20919
+ for (const selector of videoUploadSelectors){
20920
+ const input = page.locator(selector);
20921
+ const count = await input.count();
20922
+ if (count > 0) {
20923
+ uploadInput = input.first();
20924
+ task.logger.info(`找到视频上传输入框: ${selector}`);
20925
+ break;
20926
+ }
20927
+ }
20928
+ if (!uploadInput) {
20929
+ task.logger.warn("未找到视频上传输入框,等待 3 秒后重试...");
20930
+ await page.waitForTimeout(3000);
20931
+ const anyFileInput = page.locator('input[type="file"]');
20932
+ const inputCount = await anyFileInput.count();
20933
+ if (inputCount > 0) {
20934
+ uploadInput = anyFileInput.first();
20935
+ task.logger.info(`找到文件输入框(共 ${inputCount} 个)`);
20936
+ } else {
20937
+ if (task.debug) {
20938
+ const screenshotPath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(tmpCachePath, `upload-error-${Date.now()}.png`);
20939
+ await page.screenshot({
20940
+ path: screenshotPath,
20941
+ fullPage: true
20942
+ });
20943
+ task.logger.error(`未找到上传输入框,已截图保存至: ${screenshotPath}`);
20944
+ }
20945
+ throw new Error("未找到视频上传输入框");
20946
+ }
20947
+ }
20948
+ await uploadInput.setInputFiles(params.videoPath);
20949
+ task.logger.info("视频上传成功");
20950
+ await page.waitForTimeout(5000);
20951
+ });
20952
+ if (params.coverPath) {
20953
+ task.logger.info("开始上传封面");
20954
+ await retryAction(async ()=>{
20955
+ const coverUploadBtn = await waitForElement(".cover-upload-btn", 10000);
20956
+ if (coverUploadBtn) {
20957
+ const coverInput = page.locator('.cover-upload-btn input[type="file"]');
20958
+ await coverInput.setInputFiles(params.coverPath);
20959
+ task.logger.info("封面上传成功");
20960
+ await page.waitForTimeout(2000);
20961
+ }
20962
+ });
20963
+ }
20964
+ const descriptionText = payload_buildDescription({
20965
+ description: params.description,
20966
+ topics: params.topics,
20967
+ mentionedUsers: params.mentionedUsers
20968
+ });
20969
+ if (descriptionText) {
20970
+ task.logger.info("填写视频描述");
20971
+ await retryAction(async ()=>{
20972
+ const descEditor = await waitForElement(".input-editor", 10000);
20973
+ if (!descEditor) throw new Error("未找到描述编辑器");
20974
+ await descEditor.click();
20975
+ await page.waitForTimeout(500);
20976
+ await descEditor.evaluate((el)=>{
20977
+ el.textContent = "";
20978
+ });
20979
+ await page.waitForTimeout(300);
20980
+ task.logger.info("已清空编辑器内容");
20981
+ await descEditor.pressSequentially(descriptionText, {
20982
+ delay: 10
20983
+ });
20984
+ await page.waitForTimeout(500);
20985
+ task.logger.info("描述填写完成");
20986
+ });
20987
+ }
20988
+ if (params.title) {
20989
+ task.logger.info(`填写标题: ${params.title}`);
20990
+ const title = params.title;
20991
+ await retryAction(async ()=>{
20992
+ const titleInput = await waitForElement("#container-wrap div.form-item-body.short-title-wrap input", 10000);
20993
+ if (!titleInput) throw new Error("未找到标题输入框");
20994
+ await titleInput.click();
20995
+ await titleInput.clear({
20996
+ timeout: 3000
20997
+ });
20998
+ await titleInput.fill(title, {
20999
+ timeout: 5000
21000
+ });
21001
+ task.logger.info("标题填写完成");
21002
+ });
21003
+ }
21004
+ if (params.location) {
21005
+ task.logger.info(`选择地点: ${params.location.city}`);
21006
+ const instance = page.locator(".position-display-wrap");
21007
+ await instance.click();
21008
+ await page.waitForTimeout(1000);
21009
+ await page.locator(".location-filter-wrap input").fill(params.location.city);
21010
+ await page.waitForTimeout(2000);
21011
+ const poperInstance = page.locator(".location-filter-wrap .common-option-list-wrap .option-item");
21012
+ await poperInstance.nth(1).waitFor();
21013
+ await poperInstance.nth(1).click();
21014
+ task.logger.info("地点选择完成");
21015
+ }
21016
+ if (params.collection) {
21017
+ task.logger.info(`选择合集: ${params.collection.collectionName}`);
21018
+ const instanceCollection = page.locator(".post-album-display-wrap");
21019
+ await instanceCollection.click();
21020
+ await page.waitForTimeout(1000);
21021
+ page.locator(".post-album-wrap .option-item").filter({
21022
+ hasText: params.collection.collectionName
21023
+ }).first().click({
21024
+ force: true
21025
+ });
21026
+ }
21027
+ if (params.link) {
21028
+ task.logger.info(`设置扩展阅读链接: ${params.link.title}`);
21029
+ await page.locator(".post-link-wrap .link-display-wrap").click();
21030
+ await page.waitForTimeout(300);
21031
+ const linkTypeText = 2 === params.link.urlType ? "红包封面" : "公众号文章";
21032
+ await page.locator(".link-option-item .title-wrap span").filter({
21033
+ hasText: linkTypeText
21034
+ }).click();
21035
+ await page.waitForTimeout(300);
21036
+ const placeholder = 2 === params.link.urlType ? "粘贴红包封面链接" : "粘贴公众号文章链接";
21037
+ await page.locator(`.link-input-wrap input[placeholder="${placeholder}"]`).fill(params.link.link);
21038
+ await page.waitForTimeout(500);
21039
+ task.logger.info(`已设置${linkTypeText}: ${params.link.link}`);
21040
+ }
21041
+ if (params.event) {
21042
+ task.logger.info(`选择活动: ${params.event.eventName}`);
21043
+ await page.locator(".post-activity-wrap .activity-display").click();
21044
+ await page.waitForTimeout(500);
21045
+ await page.locator(".activity-filter-wrap .weui-desktop-form__input[placeholder='搜索活动']").fill(params.event.eventName);
21046
+ await page.waitForTimeout(500);
21047
+ const searchLoading = page.locator(".search-loading");
21048
+ await searchLoading.waitFor({
21049
+ state: "hidden",
21050
+ timeout: 5000
21051
+ }).catch(()=>{
21052
+ task.logger.warn("活动搜索加载超时,继续尝试选择");
21053
+ });
21054
+ const activityItem = page.locator(".option-item .activity-item .activity-item-info .name").filter({
21055
+ hasText: params.event.eventName
21056
+ });
21057
+ const count = await activityItem.count();
21058
+ if (count > 0) {
21059
+ await activityItem.first().click();
21060
+ await page.waitForTimeout(300);
21061
+ task.logger.info(`已选择活动: ${params.event.eventName}`);
21062
+ } else {
21063
+ task.logger.warn(`未找到活动: ${params.event.eventName},将不参与活动`);
21064
+ await page.locator(".post-activity-wrap .activity-display").click();
21065
+ await page.waitForTimeout(300);
21066
+ }
21067
+ }
21068
+ if (params.scheduledTime) {
21069
+ task.logger.info("设置定时发布");
21070
+ const timingRadio = page.locator(".weui-desktop-form__check-label").filter({
21071
+ hasNotText: "不定时"
21072
+ }).first();
21073
+ await timingRadio.click();
21074
+ await page.waitForTimeout(500);
21075
+ const instance = page.locator(".weui-desktop-picker__date");
21076
+ await instance.click();
21077
+ const dateD = utils_TimeFormatter.format(1000 * params.scheduledTime, "d");
21078
+ const nowMonth = utils_TimeFormatter.format(Date.now(), "MM月");
21079
+ const nowMonthText = utils_TimeFormatter.format(Date.now(), "M月");
21080
+ const month = utils_TimeFormatter.format(1000 * params.scheduledTime, "MM月");
21081
+ const monthLocator = await page.locator("weui-desktop-picker__panel__label").filter({
21082
+ hasText: month
21083
+ }).first();
21084
+ if (!monthLocator) {
21085
+ await page.locator(".weui-desktop-picker__panel__label").filter({
21086
+ hasText: nowMonth
21087
+ }).first().click();
21088
+ await page.waitForTimeout(500);
21089
+ await page.locator(".weui-desktop-picker__table-row td a").filter({
21090
+ hasText: nowMonthText
21091
+ }).first().click();
21092
+ }
21093
+ await page.waitForTimeout(500);
21094
+ await page.locator(".weui-desktop-picker__table-row td a").filter({
21095
+ hasText: dateD
21096
+ }).first().click();
21097
+ await page.locator(".weui-desktop-form__input-wrp input[placeholder*='请选择时间']").fill(utils_TimeFormatter.format(1000 * params.scheduledTime, "hh:mm"));
21098
+ await page.locator("i.weui-desktop-icon__time").click();
21099
+ await page.locator(".post-time-wrap .form-item .label").filter({
21100
+ hasText: "发表时间"
21101
+ }).click();
21102
+ }
21103
+ if (params.tagInfo) {
21104
+ task.logger.info(`设置视频标注: tagType=${params.tagInfo.tagType}`);
21105
+ await page.locator(".mark-tag-select").click();
21106
+ await page.waitForTimeout(300);
21107
+ const tagTypeTextMap = {
21108
+ 0: "无需标注",
21109
+ 1: "含AI生成内容",
21110
+ 2: "内容包含营销广告",
21111
+ 3: "内容为虚构剧情,仅供娱乐",
21112
+ 5: "内容为自行拍摄",
21113
+ 7: "内容为转载",
21114
+ 8: "个人观点,仅供参考"
21115
+ };
21116
+ const tagText = tagTypeTextMap[params.tagInfo.tagType];
21117
+ if (tagText) {
21118
+ await page.locator(".mark-tag-option .option-main").filter({
21119
+ hasText: tagText
21120
+ }).click();
21121
+ await page.waitForTimeout(300);
21122
+ if (5 === params.tagInfo.tagType) {
21123
+ const shootInfo = params.tagInfo.shootInfo;
21124
+ if (shootInfo) {
21125
+ task.logger.info("填写拍摄时间和地点...");
21126
+ await page.waitForTimeout(500);
21127
+ if (shootInfo.postTimestamp) {
21128
+ task.logger.info(`设置拍摄时间: ${shootInfo.postTimestamp}`);
21129
+ const timestamp = 1000 * parseInt(shootInfo.postTimestamp, 10);
21130
+ const date = new Date(timestamp);
21131
+ await page.locator(".original-dialog-content .weui-desktop-picker__date input[placeholder*='请选择拍摄时间']").click();
21132
+ await page.waitForTimeout(300);
21133
+ const dayNum = date.getDate();
21134
+ await page.locator(".weui-desktop-picker__table a").filter({
21135
+ hasText: new RegExp(`^\\s*${dayNum}\\s*$`)
21136
+ }).first().click();
21137
+ await page.waitForTimeout(300);
21138
+ }
21139
+ if (shootInfo.countryCode || shootInfo.provinceCode || shootInfo.cityCode) {
21140
+ task.logger.info("设置拍摄地点...");
21141
+ await page.locator(".original-dialog-content .weui-desktop-form__dropdowncascade .weui-desktop-form__dropdowncascade__dt").click();
21142
+ await page.waitForTimeout(300);
21143
+ if (1156 === shootInfo.countryCode) {
21144
+ await page.locator(".weui-desktop-dropdown__list-ele .weui-desktop-dropdown__list-ele__text").filter({
21145
+ hasText: "中国"
21146
+ }).click();
21147
+ await page.waitForTimeout(300);
21148
+ task.logger.warn("RPA 模式下暂不支持选择具体省份和城市,仅选择了国家");
21149
+ } else task.logger.warn(`不支持的国家代码: ${shootInfo.countryCode},跳过地点设置`);
21150
+ }
21151
+ const confirmBtn = await waitForElement(".weui-desktop-dialog .weui-desktop-btn_primary");
21152
+ if (confirmBtn) {
21153
+ await confirmBtn.click();
21154
+ await page.waitForTimeout(300);
21155
+ }
21156
+ } else task.logger.warn("tagType=5 需要提供 shootInfo 字段(拍摄时间和地点)");
21157
+ }
21158
+ if (7 === params.tagInfo.tagType) {
21159
+ const repostSource = params.tagInfo.repostSource;
21160
+ if (repostSource) {
21161
+ task.logger.info(`填写转载来源: ${repostSource}`);
21162
+ await page.waitForTimeout(500);
21163
+ await page.locator(".repost-dialog-content .repost-textarea").fill(repostSource);
21164
+ await page.waitForTimeout(300);
21165
+ const confirmBtn = await waitForElement(".weui-desktop-dialog .weui-desktop-btn_primary");
21166
+ if (confirmBtn) {
21167
+ await confirmBtn.click();
21168
+ await page.waitForTimeout(300);
21169
+ }
21170
+ } else task.logger.warn("tagType=7 需要提供 repostSource 字段(转载来源)");
21171
+ }
21172
+ } else task.logger.warn(`未知的 tagType: ${params.tagInfo.tagType},跳过标注设置`);
21173
+ }
21174
+ task.logger.info("准备发布...");
21175
+ await page.waitForTimeout(500);
21176
+ let videoId = "";
21177
+ const handleResponse = async (response)=>{
21178
+ const url = response.url();
21179
+ if (url.includes("/post/post_create")) {
21180
+ const jsonResponse = await response.json();
21181
+ page.off("response", handleResponse);
21182
+ videoId = jsonResponse.object?.id || jsonResponse.data?.objectId || "";
21183
+ }
21184
+ };
21185
+ page.on("response", handleResponse);
21186
+ task._timerRecord.PrePublish = Date.now();
21187
+ 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";
21188
+ task.logger.info("等待视频上传完成(预览区媒体操作栏出现)...");
21189
+ const uploadTimeout = 600000;
21190
+ const uploadWaitStart = Date.now();
21191
+ let lastProgressLog = 0;
21192
+ while(true){
21193
+ const ready = await page.evaluate((selector)=>{
21194
+ const host = document.querySelector("#container-wrap > div.container-center > div > wujie-app");
21195
+ const root = host?.shadowRoot;
21196
+ if (!root) return false;
21197
+ return !!root.querySelector(selector);
21198
+ }, MEDIA_OPR_SELECTOR);
21199
+ if (ready) break;
21200
+ const elapsed = Date.now() - uploadWaitStart;
21201
+ if (elapsed > uploadTimeout) throw new Error(`视频上传超时,预览区未就绪(已等待 ${Math.round(elapsed / 1000)}s)`);
21202
+ if (elapsed - lastProgressLog >= 15000) {
21203
+ lastProgressLog = elapsed;
21204
+ task.logger.info(`视频仍在上传中... 已等待 ${Math.round(elapsed / 1000)}s`);
21205
+ }
21206
+ await page.waitForTimeout(1000);
21207
+ }
21208
+ task.logger.info(`视频上传完成(等待 ${Math.round((Date.now() - uploadWaitStart) / 1000)}s)`);
21209
+ const clicked = await page.evaluate(()=>{
21210
+ const host = document.querySelector("#container-wrap > div.container-center > div > wujie-app");
21211
+ const root = host?.shadowRoot;
21212
+ if (!root) return "未找到 wujie-app shadowRoot";
21213
+ const btns = Array.from(root.querySelectorAll(".form-btns .weui-desktop-btn"));
21214
+ const target = btns.find((el)=>(el.textContent || "").includes("发表"));
21215
+ if (!target) return "未找到发表按钮";
21216
+ if (target.classList.contains("weui-desktop-btn_disabled")) return "发表按钮仍处于禁用状态";
21217
+ target.click();
21218
+ return null;
21219
+ });
21220
+ if (clicked) throw new Error(clicked);
21221
+ task.logger.info("已点击发布按钮,等待响应...");
21222
+ try {
21223
+ await page.waitForURL((url)=>url.href !== page.url(), {
21224
+ timeout: 30000
21225
+ });
21226
+ task.logger.info(`发布成功,页面已跳转: ${page.url()}`);
21227
+ } catch {
21228
+ task.logger.warn("等待页面跳转超时,可能发布失败或网络慢,继续关闭页面");
21229
+ }
21230
+ await page.close();
21231
+ return (0, __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_f7afdc8c__.success)(videoId, "发布成功");
21232
+ } catch (error) {
21233
+ let errorMsg = error instanceof Error ? error.message : String(error);
21234
+ if (errorMsg.includes("context or browser has been closed")) errorMsg = "浏览器上下文已被关闭";
21235
+ task.logger.error(`微信视频号视频发布失败: ${errorMsg}`);
21236
+ return (0, __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_f7afdc8c__.response)(414, `微信视频号视频发布失败: ${errorMsg}`, "");
21237
+ }
21238
+ };
21239
+ const ShipinhaoPublishVideoParamsSchema = ActionCommonParamsSchema.extend({
21240
+ videoPath: schemas_string().min(1),
21241
+ videoMetadata: schemas_object({
21242
+ duration: schemas_number().positive(),
21243
+ width: schemas_number().int().positive(),
21244
+ height: schemas_number().int().positive(),
21245
+ fileSize: schemas_number().int().positive(),
21246
+ path: schemas_string().min(1).optional(),
21247
+ fileName: schemas_string().min(1)
21248
+ }),
21249
+ coverPath: schemas_string().min(1),
21250
+ verticalCoverPath: schemas_string().min(1).optional(),
21251
+ description: schemas_string(),
21252
+ title: schemas_string().optional(),
21253
+ scheduledTime: schemas_number().int().positive().optional(),
21254
+ isImmediatelyPublish: schemas_boolean().optional(),
21255
+ topics: schemas_array(schemas_string()).optional(),
21256
+ mentionedUsers: schemas_array(schemas_object({
21257
+ nickname: schemas_string()
21258
+ })).optional(),
21259
+ collection: schemas_object({
21260
+ collectionId: schemas_string(),
21261
+ collectionName: schemas_string()
21262
+ }).optional(),
21263
+ event: schemas_object({
21264
+ eventTopicId: schemas_string(),
21265
+ eventName: schemas_string(),
21266
+ eventCreatorNickname: schemas_string().optional()
21267
+ }).optional(),
21268
+ link: schemas_object({
21269
+ link: schemas_string(),
21270
+ title: schemas_string(),
21271
+ urlType: schemas_number().int().default(1)
21272
+ }).optional(),
21273
+ tagInfo: looseObject({
21274
+ tagType: schemas_number().int()
21275
+ }).optional(),
21276
+ originalFlag: union([
21277
+ literal(0),
21278
+ literal(1)
21279
+ ]).optional(),
21280
+ postWithMemberZoneLink: union([
21281
+ literal(0),
21282
+ literal(1)
21283
+ ]).optional(),
21284
+ location: schemas_object({
21285
+ latitude: schemas_number(),
21286
+ longitude: schemas_number(),
21287
+ city: schemas_string(),
21288
+ poiName: schemas_string().optional(),
21289
+ address: schemas_string().optional(),
21290
+ poiClassifyId: schemas_string().optional()
21291
+ }).optional()
21292
+ });
21293
+ const shipinhaoPublishVideo = async (task, params)=>{
21294
+ task.logger.info(`[shipinhaoPublishVideo] actionType: ${params.actionType}`);
21295
+ if ("rpa" === params.actionType) return shipinhaoPublishVideo_rpa_rpaAction(task, params);
21296
+ if ("mockApi" === params.actionType) return shipinhaoPublishVideo_mock_mockAction(task, params);
21297
+ return executeAction(shipinhaoPublishVideo_mock_mockAction, shipinhaoPublishVideo_rpa_rpaAction)(task, params);
21298
+ };
21299
+ const ShipinhaoSendMsgParamsSchema = ActionCommonParamsSchema.extend({
21300
+ toUsername: schemas_string().min(1, "接收者用户名不能为空"),
21301
+ sessionId: schemas_string().min(1, "会话ID不能为空"),
21302
+ msgType: schemas_enum([
21303
+ "TEXT",
21304
+ "IMAGE"
21305
+ ], {
21306
+ message: "消息类型必须是 TEXT 或 IMAGE"
21307
+ }),
21308
+ content: schemas_string().optional(),
21309
+ imageInfo: schemas_object({
21310
+ pathOrUrl: schemas_string().min(1, "图片路径或URL不能为空")
21311
+ }).optional()
21312
+ });
21313
+ const shipinhaoSendMsg_CHUNK_SIZE = 524288;
21314
+ async function shipinhaoSendMsg_getUserInfo(cookieStr, http) {
21315
+ const url = `https://channels.weixin.qq.com/cgi-bin/mmfinderassistant-bin/auth/auth_data?_rid=${rid()}`;
21316
+ const headers = {
21317
+ referer: "https://channels.weixin.qq.com/micro/interaction/private_msg",
21318
+ cookie: cookieStr,
21319
+ Origin: "https://channels.weixin.qq.com"
21320
+ };
21321
+ return await http.api({
21322
+ method: "get",
21323
+ url,
21324
+ headers
21325
+ }, {
21326
+ retries: 3,
21327
+ retryDelay: 1000,
21328
+ timeout: 10000
21329
+ });
21330
+ }
21331
+ const shipinhaoSendMsg = async (_task, params)=>{
21332
+ if (!params.sessionId) return (0, __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_f7afdc8c__.response)(414, "sessionId 不能为空", void 0);
21333
+ if (!params.toUsername) return (0, __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_f7afdc8c__.response)(414, "接收者用户名不能为空", void 0);
21334
+ if (!params.msgType) return (0, __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_f7afdc8c__.response)(414, "消息类型不能为空", void 0);
21335
+ if (![
21336
+ "TEXT",
21337
+ "IMAGE"
21338
+ ].includes(params.msgType)) return (0, __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_f7afdc8c__.response)(414, "消息类型必须是 TEXT 或 IMAGE", void 0);
21339
+ if ("TEXT" === params.msgType) {
21340
+ if (!params.content || "" === params.content.trim()) return (0, __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_f7afdc8c__.response)(414, "消息内容不能为空", void 0);
21341
+ }
21342
+ if ("IMAGE" === params.msgType) {
21343
+ if (!params.imageInfo?.pathOrUrl) return (0, __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_f7afdc8c__.response)(414, "图片路径或URL不能为空", void 0);
21344
+ }
21345
+ if (!params.extraParam) return (0, __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_f7afdc8c__.response)(414, "缺少 extraParam 参数", void 0);
21346
+ if (!params.extraParam.fingerPrintDeviceId || !params.extraParam.aId || !params.extraParam.uin) return (0, __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_f7afdc8c__.response)(414, "fingerPrintDeviceId、aId 和 uin 不能为空", void 0);
21347
+ const cookieStr = params.cookies.map((it)=>`${it.name}=${it.value}`).join(";");
21348
+ const headers = {
21349
+ cookie: cookieStr,
21350
+ referer: "https://channels.weixin.qq.com/micro/interaction/private_msg",
21351
+ origin: "https://channels.weixin.qq.com",
21352
+ "content-type": "application/json",
21353
+ "finger-print-device-id": params.extraParam.fingerPrintDeviceId,
21354
+ "x-wechat-uin": params.extraParam.uin
21355
+ };
21356
+ const http = new Http({
21357
+ headers
21358
+ });
21359
+ const urlParams = new URLSearchParams({
21360
+ _aid: params.extraParam.aId,
21361
+ _rid: rid(),
21362
+ _pageUrl: "https://channels.weixin.qq.com/micro/interaction/private_msg"
21363
+ }).toString();
21364
+ const generateCliMsgId = ()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (s)=>{
21365
+ const t = 16 * Math.random() | 0;
21366
+ return ("x" === s ? t : 3 & t | 8).toString(16);
21367
+ });
21368
+ let fromUsername = params.extraParam.finderUserName;
21369
+ if (!fromUsername) {
21370
+ _task.logger.info("未提供 finderUserName,尝试获取用户信息");
21371
+ const userInfoRes = await shipinhaoSendMsg_getUserInfo(cookieStr, http);
21372
+ if (!userInfoRes.data?.finderUser?.finderUsername) return (0, __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_f7afdc8c__.response)(userInfoRes.errCode || -1, userInfoRes.errMsg || "获取用户信息失败", {});
21373
+ fromUsername = userInfoRes.data.finderUser.finderUsername;
21374
+ _task.logger.info(`获取到用户名: ${fromUsername}`);
21375
+ }
21376
+ let imgMsg;
21377
+ if ("IMAGE" === params.msgType) {
21378
+ let imageBuffer;
21379
+ const imagePath = params.imageInfo.pathOrUrl;
21380
+ try {
21381
+ if (imagePath.startsWith("http://") || imagePath.startsWith("https://")) {
21382
+ const resp = await __WEBPACK_EXTERNAL_MODULE_axios__["default"].get(imagePath, {
21383
+ responseType: "arraybuffer"
21384
+ });
21385
+ imageBuffer = Buffer.from(resp.data);
21386
+ } else {
21387
+ const filePath = imagePath.startsWith("file://") ? imagePath.slice(7) : imagePath;
21388
+ imageBuffer = Buffer.from(await __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].promises.readFile(filePath));
21389
+ }
21390
+ } catch (err) {
21391
+ _task.logger.error(`读取图片失败: ${err instanceof Error ? err.message : String(err)}`);
21392
+ return (0, __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_f7afdc8c__.response)(414, USER_MESSAGE.IMAGE_UPLOAD_FAILED, void 0);
21393
+ }
21394
+ const md5 = (0, __WEBPACK_EXTERNAL_MODULE_node_crypto_9ba42079__.createHash)("md5").update(imageBuffer).digest("hex");
21395
+ const timestamp = Date.now().toString();
21396
+ const totalChunks = Math.ceil(imageBuffer.length / shipinhaoSendMsg_CHUNK_SIZE);
21397
+ console.log(`分片上传md5${md5}`);
19536
21398
  let lastRes;
19537
21399
  for(let i = 0; i < totalChunks; i++){
19538
- const chunkBuffer = imageBuffer.slice(i * CHUNK_SIZE, (i + 1) * CHUNK_SIZE);
21400
+ const chunkBuffer = imageBuffer.slice(i * shipinhaoSendMsg_CHUNK_SIZE, (i + 1) * shipinhaoSendMsg_CHUNK_SIZE);
19539
21401
  const requestData = {
19540
21402
  content: `data:application/octet-stream;base64,${chunkBuffer.toString("base64")}`,
19541
21403
  chunk: i,
@@ -19988,6 +21850,13 @@ const toutiaoPublish_mock_mockAction = async (task, params)=>{
19988
21850
  const uploadImages = async (images)=>await Promise.all(images.map(async (url)=>{
19989
21851
  const fileName = (0, __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_f7afdc8c__.getFilenameFromUrl)(url);
19990
21852
  const image = await (0, __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_f7afdc8c__.downloadImage)(url, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(tmpCachePath, fileName));
21853
+ const stats = __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].statSync(image);
21854
+ const maxSize = 20971520;
21855
+ if (stats.size > maxSize) throw {
21856
+ code: 414,
21857
+ message: "头条号平台:单张图片不得超过 20MB",
21858
+ data: ""
21859
+ };
19991
21860
  const formData = new __WEBPACK_EXTERNAL_MODULE_form_data_cf000082__["default"]();
19992
21861
  formData.append("image", __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].createReadStream(image));
19993
21862
  const response = await http.api({
@@ -22038,18 +23907,10 @@ const weixinPublish_mock_mockAction = async (task, params)=>{
22038
23907
  });
22039
23908
  } catch (error) {
22040
23909
  const handledError = Http.handleApiError(error);
22041
- const isProxyOrNetworkError = [
22042
- 599,
22043
- 500,
22044
- 502,
22045
- 503,
22046
- 504
22047
- ].includes(handledError.code);
22048
- if (isProxyOrNetworkError) {
22049
- const isProxyRequest = handledError.extra?.isProxyRequest === true;
22050
- const errorType = 599 === handledError.code || isProxyRequest ? "代理错误" : "网络错误";
22051
- const message = `文章发布失败,${errorType}:${handledError.message}${task.debug ? ` ${http.proxyInfo}` : ""}`;
22052
- task.logger.error(`[weixinPublish] ${errorType},直接返回: ${message}`, stringifyError(handledError));
23910
+ const classified = classifyPublishError(handledError);
23911
+ if (classified) {
23912
+ const message = `${classified.userMessage}${task.debug ? ` ${http.proxyInfo}` : ""}`;
23913
+ task.logger.error(`[weixinPublish] ${classified.category},直接返回: ${handledError.message} (code=${handledError.code})`, stringifyError(handledError));
22053
23914
  await updateTaskState?.({
22054
23915
  state: __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_f7afdc8c__.TaskState.FAILED,
22055
23916
  error: message
@@ -23279,6 +25140,12 @@ const xiaohongshuPublish_mock_mockAction = async (task, params)=>{
23279
25140
  const fileName = (0, __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_f7afdc8c__.getFilenameFromUrl)(url);
23280
25141
  const localUrl = await (0, __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_f7afdc8c__.downloadImage)(url, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(tmpCachePath, fileName));
23281
25142
  const fileBuffer = __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].readFileSync(localUrl);
25143
+ const maxSize = 33554432;
25144
+ if (fileBuffer.byteLength > maxSize) throw {
25145
+ code: 414,
25146
+ message: "小红书平台:单张图片不得超过 32MB",
25147
+ data: ""
25148
+ };
23282
25149
  let width = 0;
23283
25150
  let height = 0;
23284
25151
  try {
@@ -23517,6 +25384,7 @@ const xiaohongshuPublish_mock_mockAction = async (task, params)=>{
23517
25384
  });
23518
25385
  return (0, __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_f7afdc8c__.success)(data, message);
23519
25386
  }
25387
+ task.logger.info(`[xiaohongshuPublish] publishData: ${JSON.stringify(publishData)} `);
23520
25388
  let publishResult;
23521
25389
  try {
23522
25390
  publishResult = await proxyHttp.api({
@@ -23527,23 +25395,15 @@ const xiaohongshuPublish_mock_mockAction = async (task, params)=>{
23527
25395
  defaultErrorMsg: "文章发布异常,请稍后重试。"
23528
25396
  }, {
23529
25397
  retries: 2,
23530
- retryDelay: 500,
23531
- timeout: 12000
25398
+ retryDelay: 3000,
25399
+ timeout: 30000
23532
25400
  });
23533
25401
  } catch (error) {
23534
25402
  const handledError = Http.handleApiError(error);
23535
- const isProxyOrNetworkError = [
23536
- 599,
23537
- 500,
23538
- 502,
23539
- 503,
23540
- 504
23541
- ].includes(handledError.code);
23542
- if (isProxyOrNetworkError) {
23543
- const isProxyRequest = handledError.extra?.isProxyRequest === true;
23544
- const errorType = 599 === handledError.code || isProxyRequest ? "代理错误" : "网络错误";
23545
- const message = `文章发布失败,${errorType}:${handledError.message}${task.debug ? ` ${http.proxyInfo}` : ""}`;
23546
- task.logger.error(`[xiaohongshuPublish] ${errorType},直接返回: ${message}`, stringifyError(handledError));
25403
+ const classified = classifyPublishError(handledError);
25404
+ if (classified) {
25405
+ const message = `${classified.userMessage}${task.debug ? ` ${http.proxyInfo}` : ""}`;
25406
+ task.logger.error(`[xiaohongshuPublish] ${classified.category},直接返回: ${handledError.message} (code=${handledError.code})`, stringifyError(handledError));
23547
25407
  await updateTaskState?.({
23548
25408
  state: __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_f7afdc8c__.TaskState.FAILED,
23549
25409
  error: message
@@ -25239,6 +27099,14 @@ class Action {
25239
27099
  this.task = task;
25240
27100
  this.task.logger.info(`当前包版本:Share=>${__WEBPACK_EXTERNAL_MODULE__iflyrpa_share_package_json_58ae5f06__["default"].version} Action=>${package_namespaceObject.i8}`);
25241
27101
  }
27102
+ getActionVersionMarker() {
27103
+ return {
27104
+ version: package_namespaceObject.i8,
27105
+ shareVersion: __WEBPACK_EXTERNAL_MODULE__iflyrpa_share_package_json_58ae5f06__["default"].version,
27106
+ marker: `Action_${package_namespaceObject.i8}_${__WEBPACK_EXTERNAL_MODULE__iflyrpa_share_package_json_58ae5f06__["default"].version}`,
27107
+ timestamp: new Date().toLocaleString()
27108
+ };
27109
+ }
25242
27110
  async bindTask(func, params) {
25243
27111
  let responseData;
25244
27112
  this.task.isBeta = this.task?.isFeatOn ? this.task?.isFeatOn(BetaFlag) : false;
@@ -25462,6 +27330,9 @@ class Action {
25462
27330
  shipinhaoPublish(params) {
25463
27331
  return this.bindTask(shipinhaoPublish, params);
25464
27332
  }
27333
+ shipinhaoPublishVideo(params) {
27334
+ return this.bindTask(shipinhaoPublishVideo, params);
27335
+ }
25465
27336
  douyinGetTopics(params) {
25466
27337
  return this.bindTask(douyinGetTopics, params);
25467
27338
  }
@@ -25515,7 +27386,7 @@ class Action {
25515
27386
  }
25516
27387
  }
25517
27388
  var __webpack_exports__version = package_namespaceObject.i8;
25518
- export { Action, ActionCommonParamsSchema, BaijiahaoPublishParamsSchema, BetaFlag, CollectionDetailSchema, ConfigDataSchema, DouyinCheckVerifyQrCodeParamsSchema, DouyinCreateCommentReplyParamsSchema, DouyinGetCollectionParamsSchema, DouyinGetCommentListParamsSchema, DouyinGetCommentReplyListParamsSchema, DouyinGetHotParamsSchema, DouyinGetLocationParamsSchema, DouyinGetMusicByCategoryParamsSchema, DouyinGetMusicCategoryParamsSchema, DouyinGetMusicParamsSchema, DouyinGetTopicsParamsSchema, DouyinGetVerifyQrCodeParamsSchema, DouyinGetWorkListParamsSchema, DouyinPublishParamsSchema, FetchArticlesDataSchema, FetchArticlesParamsSchema, Http, ProxyAgent, SearchAccountInfoParamsSchema, SessionCheckResultSchema, ShipinhaoCheckLinkValidateParamsSchema, ShipinhaoGetLocationParamsSchema, ShipinhaoGetMsgParamsSchema, ShipinhaoPublishParamsSchema, ShipinhaoSendMsgParamsSchema, ToutiaoPublishParamsSchema, UnreadCountSchema, WeixinPublishParamsSchema, WxBjhSessionParamsSchema, XhsWebSearchParamsSchema, XiaohongshuPublishParamsSchema, bjhConfigDataSchema, douyinConfigDataSchema, getFileState, reportLogger, rpaAction_Server_Mock, shipinhaoConfigDataSchema, ttConfigDataSchema, wxConfigDataSchema, xhsConfigDataSchema, __webpack_exports__version as version };
27389
+ export { Action, ActionCommonParamsSchema, BaijiahaoPublishParamsSchema, BetaFlag, CollectionDetailSchema, ConfigDataSchema, DouyinCheckVerifyQrCodeParamsSchema, DouyinCreateCommentReplyParamsSchema, DouyinGetCollectionParamsSchema, DouyinGetCommentListParamsSchema, DouyinGetCommentReplyListParamsSchema, DouyinGetHotParamsSchema, DouyinGetLocationParamsSchema, DouyinGetMusicByCategoryParamsSchema, DouyinGetMusicCategoryParamsSchema, DouyinGetMusicParamsSchema, DouyinGetTopicsParamsSchema, DouyinGetVerifyQrCodeParamsSchema, DouyinGetWorkListParamsSchema, DouyinPublishParamsSchema, FetchArticlesDataSchema, FetchArticlesParamsSchema, Http, ProxyAgent, SearchAccountInfoParamsSchema, SessionCheckResultSchema, ShipinhaoCheckLinkValidateParamsSchema, ShipinhaoGetLocationParamsSchema, ShipinhaoGetMsgParamsSchema, ShipinhaoPublishParamsSchema, ShipinhaoPublishVideoParamsSchema, ShipinhaoSendMsgParamsSchema, ToutiaoPublishParamsSchema, UnreadCountSchema, WeixinPublishParamsSchema, WxBjhSessionParamsSchema, XhsWebSearchParamsSchema, XiaohongshuPublishParamsSchema, bjhConfigDataSchema, douyinConfigDataSchema, getFileState, reportLogger, rpaAction_Server_Mock, shipinhaoConfigDataSchema, ttConfigDataSchema, wxConfigDataSchema, xhsConfigDataSchema, __webpack_exports__version as version };
25519
27390
 
25520
27391
  //# sourceMappingURL=index.mjs.map
25521
- //# debugId=b0f81db0-8823-5f32-bb7c-d4b4fe6dea37
27392
+ //# debugId=8d2e6460-75c8-5b65-9b60-d4269a0ff597