@iflyrpa/actions 4.0.9-beta.4 → 4.1.0-beta.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
 
2
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="3b831ac8-2f97-5984-b6b4-868d0748d2c6")}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]="959450cb-879c-5526-aedb-26ef8ba0e7a8")}catch(e){}}();
3
3
  var __webpack_modules__ = {
4
4
  "./src/utils/XhsXsCommonEnc.js": function(module) {
5
5
  var encrypt_lookup = [
@@ -4366,6 +4366,7 @@ var __webpack_exports__ = {};
4366
4366
  SessionCheckResultSchema: ()=>SessionCheckResultSchema,
4367
4367
  DouyinGetCommentReplyListParamsSchema: ()=>DouyinGetCommentReplyListParamsSchema,
4368
4368
  DouyinCreateCommentReplyParamsSchema: ()=>DouyinCreateCommentReplyParamsSchema,
4369
+ ShipinhaoPublishVideoParamsSchema: ()=>ShipinhaoPublishVideoParamsSchema,
4369
4370
  DouyinGetHotParamsSchema: ()=>DouyinGetHotParamsSchema,
4370
4371
  DouyinGetMusicParamsSchema: ()=>DouyinGetMusicParamsSchema,
4371
4372
  FetchArticlesDataSchema: ()=>FetchArticlesDataSchema,
@@ -4402,7 +4403,7 @@ var __webpack_exports__ = {};
4402
4403
  });
4403
4404
  const package_json_namespaceObject = require("@iflyrpa/share/package.json");
4404
4405
  var package_json_default = /*#__PURE__*/ __webpack_require__.n(package_json_namespaceObject);
4405
- var package_namespaceObject = JSON.parse('{"i8":"4.0.9-beta.4"}');
4406
+ var package_namespaceObject = JSON.parse('{"i8":"4.1.0-beta.6"}');
4406
4407
  const share_namespaceObject = require("@iflyrpa/share");
4407
4408
  const external_node_fs_namespaceObject = require("node:fs");
4408
4409
  var external_node_fs_default = /*#__PURE__*/ __webpack_require__.n(external_node_fs_namespaceObject);
@@ -4870,23 +4871,33 @@ var __webpack_exports__ = {};
4870
4871
  async api(config, options) {
4871
4872
  const retries = options?.retries ?? 0;
4872
4873
  const retryDelay = options?.retryDelay ?? 500;
4873
- const reqTimeout = options?.timeout ?? 30000;
4874
+ const reqTimeout = options?.timeout ?? 60000;
4875
+ const externalSignal = options?.signal;
4874
4876
  let agent;
4875
4877
  const sessionRt = async (Rtimes)=>{
4876
4878
  try {
4877
4879
  this.proxyInfo = agent ? `${agent.ip}:${agent.port}` : void 0;
4878
4880
  const controller = new AbortController();
4879
4881
  const timeoutId = setTimeout(()=>controller.abort(), reqTimeout + 500);
4882
+ const forwardAbort = ()=>controller.abort();
4883
+ if (externalSignal) {
4884
+ if (externalSignal.aborted) controller.abort();
4885
+ else externalSignal.addEventListener("abort", forwardAbort, {
4886
+ once: true
4887
+ });
4888
+ }
4880
4889
  const response = await this.apiClient({
4881
4890
  ...config,
4882
4891
  timeout: reqTimeout,
4883
4892
  signal: controller.signal,
4893
+ onUploadProgress: options?.onUploadProgress,
4884
4894
  ...agent ? {
4885
4895
  httpAgent: agent.agent,
4886
4896
  httpsAgent: agent.agent
4887
4897
  } : {}
4888
4898
  }).finally(()=>{
4889
4899
  clearTimeout(timeoutId);
4900
+ externalSignal?.removeEventListener("abort", forwardAbort);
4890
4901
  });
4891
4902
  return response.data;
4892
4903
  } catch (error) {
@@ -6003,7 +6014,7 @@ var __webpack_exports__ = {};
6003
6014
  const xid = /^[0-9a-vA-V]{20}$/;
6004
6015
  const ksuid = /^[A-Za-z0-9]{27}$/;
6005
6016
  const nanoid = /^[a-zA-Z0-9_-]{21}$/;
6006
- const duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
6017
+ const regexes_duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
6007
6018
  const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;
6008
6019
  const regexes_uuid = (version)=>{
6009
6020
  if (!version) return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;
@@ -6689,7 +6700,7 @@ var __webpack_exports__ = {};
6689
6700
  $ZodStringFormat.init(inst, def);
6690
6701
  });
6691
6702
  const $ZodISODuration = /*@__PURE__*/ $constructor("$ZodISODuration", (inst, def)=>{
6692
- def.pattern ?? (def.pattern = duration);
6703
+ def.pattern ?? (def.pattern = regexes_duration);
6693
6704
  $ZodStringFormat.init(inst, def);
6694
6705
  });
6695
6706
  const $ZodIPv4 = /*@__PURE__*/ $constructor("$ZodIPv4", (inst, def)=>{
@@ -8627,6 +8638,14 @@ var __webpack_exports__ = {};
8627
8638
  };
8628
8639
  return new ZodObject(def);
8629
8640
  }
8641
+ function looseObject(shape, params) {
8642
+ return new ZodObject({
8643
+ type: "object",
8644
+ shape,
8645
+ catchall: unknown(),
8646
+ ...normalizeParams(params)
8647
+ });
8648
+ }
8630
8649
  const ZodUnion = /*@__PURE__*/ $constructor("ZodUnion", (inst, def)=>{
8631
8650
  $ZodUnion.init(inst, def);
8632
8651
  ZodType.init(inst, def);
@@ -9325,6 +9344,13 @@ var __webpack_exports__ = {};
9325
9344
  data: ""
9326
9345
  };
9327
9346
  const image = await (0, share_namespaceObject.downloadImage)(url, external_node_path_default().join(tmpCachePath, fileName));
9347
+ const stats = external_node_fs_default().statSync(image);
9348
+ const maxSize = 5242880;
9349
+ if (stats.size > maxSize) throw {
9350
+ code: 414,
9351
+ message: "百家号平台:单张图片不得超过 5MB",
9352
+ data: ""
9353
+ };
9328
9354
  const formData = new (external_form_data_default())();
9329
9355
  formData.append("org_file_name", fileName);
9330
9356
  formData.append("type", "image");
@@ -13462,6 +13488,11 @@ var __webpack_exports__ = {};
13462
13488
  }
13463
13489
  async getImageInfo(localPath) {
13464
13490
  const stats = external_node_fs_default().statSync(localPath);
13491
+ const maxSize = 52428800;
13492
+ if (stats.size > maxSize) {
13493
+ external_node_path_default().basename(localPath);
13494
+ throw new Error("抖音平台:单张图片不得超过 50MB");
13495
+ }
13465
13496
  let width = 1080;
13466
13497
  let height = 1920;
13467
13498
  try {
@@ -19708,223 +19739,1860 @@ var __webpack_exports__ = {};
19708
19739
  if ("server" === params.actionType) return rpa_server_rpaAction_Server(task, params);
19709
19740
  return executeAction(shipinhaoPublish_mock_mockAction, rpa_server_rpaAction_Server)(task, params);
19710
19741
  };
19711
- const ShipinhaoSendMsgParamsSchema = ActionCommonParamsSchema.extend({
19712
- toUsername: schemas_string().min(1, "接收者用户名不能为空"),
19713
- sessionId: schemas_string().min(1, "会话ID不能为空"),
19714
- msgType: schemas_enum([
19715
- "TEXT",
19716
- "IMAGE"
19717
- ], {
19718
- message: "消息类型必须是 TEXT 或 IMAGE"
19719
- }),
19720
- content: schemas_string().optional(),
19721
- imageInfo: schemas_object({
19722
- pathOrUrl: schemas_string().min(1, "图片路径或URL不能为空")
19723
- }).optional()
19724
- });
19725
- const CHUNK_SIZE = 524288;
19726
- async function shipinhaoSendMsg_getUserInfo(cookieStr, http) {
19727
- const url = `https://channels.weixin.qq.com/cgi-bin/mmfinderassistant-bin/auth/auth_data?_rid=${rid()}`;
19728
- const headers = {
19729
- referer: "https://channels.weixin.qq.com/micro/interaction/private_msg",
19730
- cookie: cookieStr,
19731
- Origin: "https://channels.weixin.qq.com"
19732
- };
19733
- return await http.api({
19734
- method: "get",
19735
- url,
19736
- headers
19737
- }, {
19738
- retries: 3,
19739
- retryDelay: 1000,
19740
- timeout: 10000
19741
- });
19742
+ function auth_getTimeStamp(length) {
19743
+ return Date.now().toString().substring(0, length);
19742
19744
  }
19743
- const shipinhaoSendMsg = async (_task, params)=>{
19744
- if (!params.sessionId) return (0, share_namespaceObject.response)(414, "sessionId 不能为空", void 0);
19745
- if (!params.toUsername) return (0, share_namespaceObject.response)(414, "接收者用户名不能为空", void 0);
19746
- if (!params.msgType) return (0, share_namespaceObject.response)(414, "消息类型不能为空", void 0);
19747
- if (![
19748
- "TEXT",
19749
- "IMAGE"
19750
- ].includes(params.msgType)) return (0, share_namespaceObject.response)(414, "消息类型必须是 TEXT 或 IMAGE", void 0);
19751
- if ("TEXT" === params.msgType) {
19752
- if (!params.content || "" === params.content.trim()) return (0, share_namespaceObject.response)(414, "消息内容不能为空", void 0);
19753
- }
19754
- if ("IMAGE" === params.msgType) {
19755
- if (!params.imageInfo?.pathOrUrl) return (0, share_namespaceObject.response)(414, "图片路径或URL不能为空", void 0);
19756
- }
19757
- if (!params.extraParam) return (0, share_namespaceObject.response)(414, "缺少 extraParam 参数", void 0);
19758
- if (!params.extraParam.fingerPrintDeviceId || !params.extraParam.aId || !params.extraParam.uin) return (0, share_namespaceObject.response)(414, "fingerPrintDeviceId、aId 和 uin 不能为空", void 0);
19759
- const cookieStr = params.cookies.map((it)=>`${it.name}=${it.value}`).join(";");
19760
- const headers = {
19761
- cookie: cookieStr,
19762
- referer: "https://channels.weixin.qq.com/micro/interaction/private_msg",
19763
- origin: "https://channels.weixin.qq.com",
19764
- "content-type": "application/json",
19765
- "finger-print-device-id": params.extraParam.fingerPrintDeviceId,
19766
- "x-wechat-uin": params.extraParam.uin
19767
- };
19768
- const http = new Http({
19769
- headers
19770
- });
19771
- const urlParams = new URLSearchParams({
19772
- _aid: params.extraParam.aId,
19773
- _rid: rid(),
19774
- _pageUrl: "https://channels.weixin.qq.com/micro/interaction/private_msg"
19775
- }).toString();
19776
- const generateCliMsgId = ()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (s)=>{
19777
- const t = 16 * Math.random() | 0;
19778
- return ("x" === s ? t : 3 & t | 8).toString(16);
19779
- });
19780
- let fromUsername = params.extraParam.finderUserName;
19781
- if (!fromUsername) {
19782
- _task.logger.info("未提供 finderUserName,尝试获取用户信息");
19783
- const userInfoRes = await shipinhaoSendMsg_getUserInfo(cookieStr, http);
19784
- if (!userInfoRes.data?.finderUser?.finderUsername) return (0, share_namespaceObject.response)(userInfoRes.errCode || -1, userInfoRes.errMsg || "获取用户信息失败", {});
19785
- fromUsername = userInfoRes.data.finderUser.finderUsername;
19786
- _task.logger.info(`获取到用户名: ${fromUsername}`);
19787
- }
19788
- let imgMsg;
19789
- if ("IMAGE" === params.msgType) {
19790
- let imageBuffer;
19791
- const imagePath = params.imageInfo.pathOrUrl;
19792
- try {
19793
- if (imagePath.startsWith("http://") || imagePath.startsWith("https://")) {
19794
- const resp = await external_axios_default().get(imagePath, {
19795
- responseType: "arraybuffer"
19796
- });
19797
- imageBuffer = Buffer.from(resp.data);
19798
- } else {
19799
- const filePath = imagePath.startsWith("file://") ? imagePath.slice(7) : imagePath;
19800
- imageBuffer = Buffer.from(await external_node_fs_default().promises.readFile(filePath));
19801
- }
19802
- } catch (err) {
19803
- _task.logger.error(`读取图片失败: ${err instanceof Error ? err.message : String(err)}`);
19804
- return (0, share_namespaceObject.response)(414, USER_MESSAGE.IMAGE_UPLOAD_FAILED, void 0);
19805
- }
19806
- const md5 = (0, external_node_crypto_namespaceObject.createHash)("md5").update(imageBuffer).digest("hex");
19807
- const timestamp = Date.now().toString();
19808
- const totalChunks = Math.ceil(imageBuffer.length / CHUNK_SIZE);
19809
- console.log(`分片上传md5${md5}`);
19810
- let lastRes;
19811
- for(let i = 0; i < totalChunks; i++){
19812
- const chunkBuffer = imageBuffer.slice(i * CHUNK_SIZE, (i + 1) * CHUNK_SIZE);
19813
- const requestData = {
19814
- content: `data:application/octet-stream;base64,${chunkBuffer.toString("base64")}`,
19815
- chunk: i,
19816
- chunks: totalChunks,
19817
- fromUsername,
19818
- toUsername: params.toUsername,
19819
- aesKey: "U2FsdGVkX18cwrWR73LMGhBcmAX8xoNTgbmgkZBYkEs=",
19820
- mediaSize: imageBuffer.length,
19821
- mediaType: 3,
19822
- md5,
19823
- timestamp,
19824
- _log_finder_uin: "",
19825
- _log_finder_id: params.extraParam.finderUserName || "",
19826
- rawKeyBuff: null,
19827
- pluginSessionId: null,
19828
- scene: 7,
19829
- reqScene: 7
19830
- };
19831
- lastRes = await http.api({
19832
- method: "post",
19833
- url: `https://channels.weixin.qq.com/micro/interaction/cgi-bin/mmfinderassistant-bin/private-msg/upload-media-info?${urlParams}`,
19834
- data: requestData
19835
- });
19836
- console.log(`分片上传 ${i + 1}/${totalChunks} 响应:`, lastRes);
19837
- if (lastRes?.errCode !== 0 && i < totalChunks - 1) return (0, share_namespaceObject.response)(414, lastRes?.errMsg || `第 ${i + 1}/${totalChunks} 分片上传失败`, void 0);
19838
- }
19839
- if (lastRes?.errCode !== 0) return (0, share_namespaceObject.response)(414, lastRes?.errMsg || "上传图片失败", void 0);
19840
- const uploadedImgMsg = lastRes.data?.imgMsg;
19841
- imgMsg = {
19842
- aeskey: uploadedImgMsg.aesKey ?? uploadedImgMsg.aeskey,
19843
- url: uploadedImgMsg.cdnUrl ?? uploadedImgMsg.url,
19844
- hdSize: uploadedImgMsg.hdSize ?? uploadedImgMsg.size,
19845
- midSize: uploadedImgMsg.midSize ?? uploadedImgMsg.size,
19846
- thumbSize: uploadedImgMsg.thumbSize ?? uploadedImgMsg.size,
19847
- thumbHeight: uploadedImgMsg.thumbHeight ?? uploadedImgMsg.height,
19848
- thumbWidth: uploadedImgMsg.thumbWidth ?? uploadedImgMsg.width,
19849
- md5: uploadedImgMsg.md5
19850
- };
19851
- }
19852
- console.log("发送私信请求参数1111", {
19853
- sessionId: params.sessionId,
19854
- fromUsername
19855
- });
19856
- const sendRes = await http.api({
19745
+ async function auth_getUserInfo(cookies, http) {
19746
+ return http.api({
19857
19747
  method: "post",
19858
- url: `https://channels.weixin.qq.com/micro/interaction/cgi-bin/mmfinderassistant-bin/private-msg/send-private-msg?${urlParams}`,
19748
+ url: "https://channels.weixin.qq.com/cgi-bin/mmfinderassistant-bin/auth/auth_data",
19859
19749
  data: {
19860
- timestamp: Date.now().toString(),
19750
+ timestamp: auth_getTimeStamp(13),
19861
19751
  _log_finder_uin: "",
19862
- _log_finder_id: params.extraParam.finderUserName || "",
19752
+ _log_finder_id: "",
19863
19753
  rawKeyBuff: null,
19864
19754
  pluginSessionId: null,
19865
19755
  scene: 7,
19866
- reqScene: 7,
19867
- msgPack: {
19868
- sessionId: params.sessionId,
19869
- fromUsername,
19870
- toUsername: params.toUsername,
19871
- cliMsgId: generateCliMsgId(),
19872
- msgType: "TEXT" === params.msgType ? 1 : 3,
19873
- imgMsg: "IMAGE" === params.msgType ? imgMsg : void 0,
19874
- textMsg: "TEXT" === params.msgType ? {
19875
- content: params.content
19876
- } : void 0
19877
- }
19878
- }
19756
+ reqScene: 7
19757
+ },
19758
+ headers: {
19759
+ cookie: cookies,
19760
+ referer: "https://channels.weixin.qq.com",
19761
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
19762
+ },
19763
+ defaultErrorMsg: "获取用户信息失败"
19879
19764
  });
19880
- console.log("发送私信响应:", sendRes);
19881
- const isSuccess = sendRes?.errCode === 0;
19882
- return (0, share_namespaceObject.response)(isSuccess ? 0 : 414, sendRes?.errMsg || "发送图片私信失败", sendRes.data);
19883
- };
19884
- const toutiaoLogin_rpa_rpaAction = async (task, _params)=>{
19885
- const reporter = task.reportService?.reportLoginStatus ?? (()=>Promise.resolve());
19886
- let page;
19887
- let isSelfClosing = false;
19888
- let handleBrowserDisconnected;
19889
- const cleanup = async ()=>{
19890
- if (handleBrowserDisconnected) task._steelBrowser?.off("disconnected", handleBrowserDisconnected);
19891
- if (page && !page.isClosed()) await page.close().catch(()=>{});
19765
+ }
19766
+ async function auth_getUploadAuthKey(cookies, finderUsername, http) {
19767
+ return http.api({
19768
+ method: "post",
19769
+ url: "https://channels.weixin.qq.com/cgi-bin/mmfinderassistant-bin/helper/helper_upload_params",
19770
+ data: {
19771
+ timestamp: auth_getTimeStamp(13),
19772
+ _log_finder_id: finderUsername,
19773
+ rawKeyBuff: null
19774
+ },
19775
+ headers: {
19776
+ cookie: cookies,
19777
+ referer: "https://channels.weixin.qq.com",
19778
+ Accept: "application/json, text/plain, */*",
19779
+ "Content-Type": "application/json",
19780
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
19781
+ },
19782
+ defaultErrorMsg: "获取上传认证密钥失败"
19783
+ });
19784
+ }
19785
+ class ShipinhaoAuthError extends Error {
19786
+ constructor(message, errCode){
19787
+ super(message), this.errCode = errCode;
19788
+ this.name = "ShipinhaoAuthError";
19789
+ }
19790
+ }
19791
+ async function getShipinhaoUploadAuth(cookies, http) {
19792
+ const userInfo = await auth_getUserInfo(cookies, http);
19793
+ if (0 !== userInfo.errCode || !userInfo.data?.finderUser) {
19794
+ const isLoginExpired = 300333 === userInfo.errCode || 300334 === userInfo.errCode;
19795
+ throw new ShipinhaoAuthError(isLoginExpired ? "登录失效" : userInfo.errMsg || "获取用户信息失败", userInfo.errCode || 500);
19796
+ }
19797
+ const finderUsername = userInfo.data.finderUser.finderUsername;
19798
+ const authKeyResponse = await auth_getUploadAuthKey(cookies, finderUsername, http);
19799
+ if (0 !== authKeyResponse.errCode || !authKeyResponse.data?.authKey) throw new ShipinhaoAuthError(`获取上传认证参数失败: ${authKeyResponse.errMsg}`, authKeyResponse.errCode || 500);
19800
+ const uin = authKeyResponse.data.uin;
19801
+ if (!uin) throw new ShipinhaoAuthError("获取用户 uin 失败", 500);
19802
+ const videoFileType = authKeyResponse.data.videoFileType || 20302;
19803
+ const pictureFileType = authKeyResponse.data.pictureFileType || 20304;
19804
+ return {
19805
+ uin,
19806
+ authKey: authKeyResponse.data.authKey,
19807
+ finderUsername,
19808
+ videoFileType,
19809
+ pictureFileType
19892
19810
  };
19893
- try {
19894
- page = await task.createPage({
19895
- url: "https://mp.toutiao.com/auth/page/login"
19896
- });
19897
- if (!task._session?.id) throw new Error("Session ID 不存在");
19898
- handleBrowserDisconnected = ()=>{
19899
- if (task.debug && isSelfClosing) task.logger.info("执行结束,关闭浏览器!");
19900
- else task.logger.info("浏览器被手动释放或意外关闭!");
19901
- };
19902
- task._steelBrowser?.on("disconnected", handleBrowserDisconnected);
19903
- } catch (e) {
19904
- return {
19905
- code: 414,
19906
- message: `浏览器启动失败: ${e}`,
19907
- data: {}
19908
- };
19811
+ }
19812
+ const MENTION_TEXT_SUFFIX = "\u0020";
19813
+ const MENTION_XML_SUFFIX = "\u2005";
19814
+ function payload_buildDescription(params) {
19815
+ let description = params.description || "";
19816
+ for (const topic of params.topics || [])description += `#${topic}`;
19817
+ for (const user of params.mentionedUsers || [])description += `@${user.nickname}${MENTION_TEXT_SUFFIX}`;
19818
+ return description;
19819
+ }
19820
+ function buildMentionedUser(mentionedUsers) {
19821
+ return (mentionedUsers || []).map((user)=>({
19822
+ nickname: `${user.nickname}${MENTION_TEXT_SUFFIX}`
19823
+ }));
19824
+ }
19825
+ function payload_buildTopicXml(params) {
19826
+ const values = [];
19827
+ let atIndex = null;
19828
+ if (params.description) values.push(`<![CDATA[${params.description}]]>`);
19829
+ for (const topic of params.topics || [])values.push(`<topic><![CDATA[#${topic}#]]></topic>`);
19830
+ for (const user of params.mentionedUsers || []){
19831
+ if (null === atIndex) atIndex = values.length;
19832
+ values.push(`<![CDATA[@${user.nickname}${MENTION_XML_SUFFIX}]]>`);
19909
19833
  }
19910
- const pageInfo = await task._client?.sessions.liveDetails(task._session.id);
19911
- const pageId = pageInfo?.pages[0].id ?? "";
19912
- const baseHost = task._session.websocketUrl?.replace(/^wss?:\/\//, "") ?? "";
19913
- const connectAddress = new URLSearchParams({
19914
- baseHost,
19915
- pageId
19916
- }).toString();
19917
- task.reportService?.settingSessionID?.(task._session?.id || "");
19918
- await page.route(/\/welcome.*\.(png|mp4)$/i, (route)=>route.abort());
19919
- await reporter(0, "浏览器启动成功,请使用头条号App扫码登录……", {
19920
- connectAddress
19834
+ let xml = "<finder>";
19835
+ xml += "<version>1</version>";
19836
+ xml += `<valuecount>${values.length}</valuecount>`;
19837
+ xml += `<style><at>${atIndex ?? ""}</at></style>`;
19838
+ values.forEach((value, index)=>{
19839
+ xml += `<value${index}>${value}</value${index}>`;
19921
19840
  });
19922
- let userInfo = {
19923
- uniqueId: "",
19924
- avatar: "",
19925
- name: ""
19841
+ xml += "</finder>";
19842
+ return xml;
19843
+ }
19844
+ function payload_buildLocation(location) {
19845
+ if (!location) return {
19846
+ latitude: 0,
19847
+ longitude: 0,
19848
+ city: "",
19849
+ poiName: "",
19850
+ address: "",
19851
+ poiClassifyId: ""
19926
19852
  };
19927
- try {
19853
+ return {
19854
+ latitude: location.latitude,
19855
+ longitude: location.longitude,
19856
+ city: location.city,
19857
+ poiName: location.poiName || "",
19858
+ address: location.address || "",
19859
+ poiClassifyId: location.poiClassifyId || ""
19860
+ };
19861
+ }
19862
+ function buildTopic(params) {
19863
+ const topic = {
19864
+ finderTopicInfo: payload_buildTopicXml(params)
19865
+ };
19866
+ if (params.collection) {
19867
+ topic.collectionId = params.collection.collectionId;
19868
+ topic.collectionName = params.collection.collectionName;
19869
+ }
19870
+ return topic;
19871
+ }
19872
+ function buildEvent(event) {
19873
+ if (!event) return {};
19874
+ return {
19875
+ eventTopicId: event.eventTopicId,
19876
+ eventName: event.eventName,
19877
+ eventCreatorNickname: event.eventCreatorNickname || ""
19878
+ };
19879
+ }
19880
+ function buildExtReading(link) {
19881
+ if (!link) return {
19882
+ link: "",
19883
+ title: "",
19884
+ urlType: 1
19885
+ };
19886
+ return {
19887
+ link: link.link.replace(/[\s\u200b]/g, ""),
19888
+ title: link.title,
19889
+ urlType: link.urlType ?? 1
19890
+ };
19891
+ }
19892
+ function buildTagInfo(tagInfo, tagKey) {
19893
+ return {
19894
+ ...tagInfo,
19895
+ tagKey
19896
+ };
19897
+ }
19898
+ const CHUNK_SIZE = 8388608;
19899
+ const UPLOAD_STAGE_TIMEOUT = 180000;
19900
+ const DEFAULT_TUNING = {
19901
+ metaTimeout: UPLOAD_STAGE_TIMEOUT,
19902
+ partTimeout: UPLOAD_STAGE_TIMEOUT,
19903
+ partRetries: 3,
19904
+ completeTimeout: UPLOAD_STAGE_TIMEOUT
19905
+ };
19906
+ async function uploader_uploadFile(opts) {
19907
+ const { filePath, fileType, uin, authKey, http, logger, tuning } = opts;
19908
+ const stat = external_node_fs_default().statSync(filePath);
19909
+ const fileSize = stat.size;
19910
+ const fileName = filePath.split(/[\\/]/).pop() || "file";
19911
+ const metaTimeout = tuning?.metaTimeout ?? DEFAULT_TUNING.metaTimeout;
19912
+ const partTimeout = tuning?.partTimeout ?? DEFAULT_TUNING.partTimeout;
19913
+ const partRetries = tuning?.partRetries ?? DEFAULT_TUNING.partRetries;
19914
+ const completeTimeout = tuning?.completeTimeout ?? DEFAULT_TUNING.completeTimeout;
19915
+ logger?.info(`开始上传: ${fileName} (${fileSize} B, filetype=${fileType})`);
19916
+ logger?.info(`上传超时策略: 单片 ${partTimeout / 1000}s(重试 ${partRetries} 次)、合并 ${completeTimeout / 1000}s`);
19917
+ const fileMd5 = await computeFileMd5(filePath);
19918
+ const taskId = generateTaskId(fileName, fileSize, fileMd5);
19919
+ const baseUrl = "https://finderassistancea.video.qq.com";
19920
+ const headers = {
19921
+ Authorization: authKey
19922
+ };
19923
+ const xArgs = `apptype=251&filetype=${fileType}&weixinnum=${uin}&filekey=${encodeURIComponent(fileName)}&filesize=${fileSize}&taskid=${taskId}&scene=2`;
19924
+ const chunkCount = Math.ceil(fileSize / CHUNK_SIZE);
19925
+ const blockPartLength = [];
19926
+ for(let i = 0; i < chunkCount; i++)blockPartLength.push(Math.min((i + 1) * CHUNK_SIZE, fileSize));
19927
+ logger?.info(`申请 UploadID: ${chunkCount} 片`);
19928
+ const applyRes = await http.api({
19929
+ method: "PUT",
19930
+ url: `${baseUrl}/applyuploaddfs`,
19931
+ headers: {
19932
+ ...headers,
19933
+ "X-Arguments": xArgs
19934
+ },
19935
+ data: {
19936
+ BlockSum: chunkCount,
19937
+ BlockPartLength: blockPartLength
19938
+ }
19939
+ }, {
19940
+ timeout: metaTimeout,
19941
+ retries: 2,
19942
+ retryDelay: 2000
19943
+ });
19944
+ if (!applyRes.UploadID && !applyRes.ListPartsResult) throw new Error("申请 UploadID 失败: " + JSON.stringify(applyRes));
19945
+ let uploadId = applyRes.UploadID;
19946
+ const uploadedParts = new Set();
19947
+ if (applyRes.ListPartsResult) {
19948
+ logger?.info("检测到已上传分片,执行续传");
19949
+ const parts = Array.isArray(applyRes.ListPartsResult.Part) ? applyRes.ListPartsResult.Part : applyRes.ListPartsResult.Part ? [
19950
+ applyRes.ListPartsResult.Part
19951
+ ] : [];
19952
+ for (const p of parts)uploadedParts.add(p.PartNumber);
19953
+ const retryRes = await http.api({
19954
+ method: "PUT",
19955
+ url: `${baseUrl}/applyuploaddfs`,
19956
+ headers: {
19957
+ ...headers,
19958
+ "X-Arguments": xArgs
19959
+ },
19960
+ data: {
19961
+ BlockSum: chunkCount,
19962
+ BlockPartLength: blockPartLength
19963
+ }
19964
+ }, {
19965
+ timeout: metaTimeout,
19966
+ retries: 2,
19967
+ retryDelay: 2000
19968
+ });
19969
+ uploadId = retryRes.UploadID;
19970
+ if (!uploadId) throw new Error("续传获取 UploadID 失败");
19971
+ }
19972
+ const partInfo = [];
19973
+ const fd = external_node_fs_default().openSync(filePath, "r");
19974
+ try {
19975
+ for(let i = 0; i < chunkCount; i++){
19976
+ const partNumber = i + 1;
19977
+ if (uploadedParts.has(partNumber)) {
19978
+ const existing = applyRes.ListPartsResult.Part.find((p)=>p.PartNumber === partNumber);
19979
+ if (existing) {
19980
+ partInfo.push({
19981
+ PartNumber: partNumber,
19982
+ ETag: existing.ETag
19983
+ });
19984
+ logger?.info(`分片 ${partNumber}/${chunkCount} 已存在,跳过`);
19985
+ continue;
19986
+ }
19987
+ }
19988
+ const start = i * CHUNK_SIZE;
19989
+ const end = Math.min(start + CHUNK_SIZE, fileSize);
19990
+ const chunkSize = end - start;
19991
+ const chunk = Buffer.alloc(chunkSize);
19992
+ external_node_fs_default().readSync(fd, chunk, 0, chunkSize, start);
19993
+ const chunkMd5 = external_node_crypto_default().createHash("md5").update(chunk).digest("hex");
19994
+ const partStart = Date.now();
19995
+ await http.api({
19996
+ method: "PUT",
19997
+ url: `${baseUrl}/uploadpartdfs?PartNumber=${partNumber}&UploadID=${encodeURIComponent(uploadId)}`,
19998
+ headers: {
19999
+ ...headers,
20000
+ "X-Arguments": xArgs.replace(/scene=2/, "scene=0"),
20001
+ "Content-MD5": chunkMd5
20002
+ },
20003
+ data: chunk
20004
+ }, {
20005
+ timeout: partTimeout,
20006
+ retries: partRetries,
20007
+ retryDelay: 2000
20008
+ });
20009
+ const partElapsed = Date.now() - partStart;
20010
+ const throughput = Math.round(chunkSize / (partElapsed / 1000));
20011
+ partInfo.push({
20012
+ PartNumber: partNumber,
20013
+ ETag: `"${chunkMd5}"`
20014
+ });
20015
+ logger?.info(`分片 ${partNumber}/${chunkCount} 完成 (${chunkSize} B, ${partElapsed}ms, ${Math.round(throughput / 1024)}KB/s)`);
20016
+ }
20017
+ } finally{
20018
+ external_node_fs_default().closeSync(fd);
20019
+ }
20020
+ logger?.info("合并分片...");
20021
+ const completeRes = await http.api({
20022
+ method: "POST",
20023
+ url: `${baseUrl}/completepartuploaddfs?UploadID=${encodeURIComponent(uploadId)}`,
20024
+ headers: {
20025
+ ...headers,
20026
+ "X-Arguments": xArgs
20027
+ },
20028
+ data: {
20029
+ TransFlag: "0_0",
20030
+ PartInfo: partInfo
20031
+ }
20032
+ }, {
20033
+ timeout: completeTimeout,
20034
+ retries: 1,
20035
+ retryDelay: 3000
20036
+ });
20037
+ if (!completeRes.DownloadURL) throw new Error("合并分片失败: " + JSON.stringify(completeRes));
20038
+ logger?.info("上传成功");
20039
+ return {
20040
+ downloadUrl: completeRes.DownloadURL,
20041
+ md5: fileMd5,
20042
+ fileSize
20043
+ };
20044
+ }
20045
+ async function computeFileMd5(filePath) {
20046
+ return new Promise((resolve, reject)=>{
20047
+ const hash = external_node_crypto_default().createHash("md5");
20048
+ const stream = external_node_fs_default().createReadStream(filePath);
20049
+ stream.on("data", (chunk)=>hash.update(chunk));
20050
+ stream.on("end", ()=>resolve(hash.digest("hex")));
20051
+ stream.on("error", reject);
20052
+ });
20053
+ }
20054
+ function generateTaskId(fileName, fileSize, fileMd5) {
20055
+ const input = `${fileName}-${fileSize}-${fileMd5}`;
20056
+ return external_node_crypto_default().createHash("md5").update(input).digest("hex").slice(0, 32);
20057
+ }
20058
+ const MAX_METADATA_BOX_SIZE = 268435456;
20059
+ function readBoxHeader(fd, offset, limit) {
20060
+ if (offset + 8 > limit) return null;
20061
+ const head = Buffer.alloc(16);
20062
+ const read = external_node_fs_default().readSync(fd, head, 0, 16, offset);
20063
+ if (read < 8) return null;
20064
+ let size = head.readUInt32BE(0);
20065
+ const type = head.toString("latin1", 4, 8);
20066
+ let headerSize = 8;
20067
+ if (1 === size) {
20068
+ if (read < 16) return null;
20069
+ size = head.readUInt32BE(8) * 2 ** 32 + head.readUInt32BE(12);
20070
+ headerSize = 16;
20071
+ } else if (0 === size) size = limit - offset;
20072
+ if (size < headerSize || offset + size > limit) return null;
20073
+ return {
20074
+ type,
20075
+ size,
20076
+ headerSize
20077
+ };
20078
+ }
20079
+ function parseVideoMeta(filePath) {
20080
+ let fd;
20081
+ let fileSize;
20082
+ try {
20083
+ fd = external_node_fs_default().openSync(filePath, "r");
20084
+ } catch {
20085
+ return null;
20086
+ }
20087
+ try {
20088
+ fileSize = external_node_fs_default().fstatSync(fd).size;
20089
+ const state = {
20090
+ movie: null,
20091
+ tracks: [],
20092
+ trexDefaults: new Map(),
20093
+ fragmentDurations: new Map(),
20094
+ trafTrackId: 0,
20095
+ trafDefaultSampleDuration: 0
20096
+ };
20097
+ let offset = 0;
20098
+ while(offset + 8 <= fileSize){
20099
+ const header = readBoxHeader(fd, offset, fileSize);
20100
+ if (!header) break;
20101
+ if ("moov" === header.type || "moof" === header.type) {
20102
+ const bodyLength = header.size - header.headerSize;
20103
+ if (bodyLength > 0 && bodyLength <= MAX_METADATA_BOX_SIZE) {
20104
+ const body = Buffer.alloc(bodyLength);
20105
+ const read = external_node_fs_default().readSync(fd, body, 0, bodyLength, offset + header.headerSize);
20106
+ state.trafTrackId = 0;
20107
+ state.trafDefaultSampleDuration = 0;
20108
+ walkBoxes(body.subarray(0, read), 0, read, state);
20109
+ }
20110
+ }
20111
+ offset += header.size;
20112
+ }
20113
+ const { movie, tracks } = state;
20114
+ const video = tracks.find((t)=>"vide" === t.handler) || tracks.find((t)=>t.width > 0 && t.height > 0);
20115
+ if (!video) return null;
20116
+ let { width, height } = video;
20117
+ if (90 === video.rotation || 270 === video.rotation) [width, height] = [
20118
+ height,
20119
+ width
20120
+ ];
20121
+ return {
20122
+ width: Math.round(width),
20123
+ height: Math.round(height),
20124
+ duration: resolveDuration(movie, video, state.fragmentDurations),
20125
+ rotation: video.rotation,
20126
+ fileSize,
20127
+ codec: video.codec
20128
+ };
20129
+ } catch {
20130
+ return null;
20131
+ } finally{
20132
+ try {
20133
+ external_node_fs_default().closeSync(fd);
20134
+ } catch {}
20135
+ }
20136
+ }
20137
+ function walkBoxes(buf, start, end, state) {
20138
+ let off = start;
20139
+ while(off + 8 <= end){
20140
+ let size = buf.readUInt32BE(off);
20141
+ const type = buf.toString("latin1", off + 4, off + 8);
20142
+ let headerSize = 8;
20143
+ if (1 === size) {
20144
+ if (off + 16 > end) break;
20145
+ const hi = buf.readUInt32BE(off + 8);
20146
+ const lo = buf.readUInt32BE(off + 12);
20147
+ size = hi * 2 ** 32 + lo;
20148
+ headerSize = 16;
20149
+ } else if (0 === size) size = end - off;
20150
+ if (size < headerSize || off + size > end) break;
20151
+ const bodyStart = off + headerSize;
20152
+ const bodyEnd = off + size;
20153
+ switch(type){
20154
+ case "trak":
20155
+ case "mdia":
20156
+ case "minf":
20157
+ case "stbl":
20158
+ case "mvex":
20159
+ case "traf":
20160
+ walkBoxes(buf, bodyStart, bodyEnd, state);
20161
+ break;
20162
+ case "mvhd":
20163
+ state.movie = parseMvhd(buf, bodyStart, bodyEnd);
20164
+ break;
20165
+ case "tkhd":
20166
+ state.tracks.push({
20167
+ ...parseTkhd(buf, bodyStart, bodyEnd),
20168
+ handler: null,
20169
+ codec: null,
20170
+ timescale: 0,
20171
+ mdhdDuration: 0,
20172
+ sttsDuration: 0
20173
+ });
20174
+ break;
20175
+ case "mdhd":
20176
+ {
20177
+ const mdhd = parseMvhd(buf, bodyStart, bodyEnd);
20178
+ if (mdhd && state.tracks.length) {
20179
+ const track = state.tracks[state.tracks.length - 1];
20180
+ track.timescale = mdhd.timescale;
20181
+ track.mdhdDuration = mdhd.duration;
20182
+ }
20183
+ break;
20184
+ }
20185
+ case "hdlr":
20186
+ if (bodyEnd - bodyStart >= 12 && state.tracks.length) state.tracks[state.tracks.length - 1].handler = buf.toString("latin1", bodyStart + 8, bodyStart + 12);
20187
+ break;
20188
+ case "stsd":
20189
+ {
20190
+ const codec = parseStsdCodec(buf, bodyStart, bodyEnd);
20191
+ if (codec && state.tracks.length) state.tracks[state.tracks.length - 1].codec = codec;
20192
+ break;
20193
+ }
20194
+ case "stts":
20195
+ if (state.tracks.length) state.tracks[state.tracks.length - 1].sttsDuration = parseSttsDuration(buf, bodyStart, bodyEnd);
20196
+ break;
20197
+ case "trex":
20198
+ if (bodyStart + 20 > bodyEnd) break;
20199
+ state.trexDefaults.set(buf.readUInt32BE(bodyStart + 4), buf.readUInt32BE(bodyStart + 12));
20200
+ break;
20201
+ case "tfhd":
20202
+ {
20203
+ const tfhd = parseTfhd(buf, bodyStart, bodyEnd);
20204
+ state.trafTrackId = tfhd.trackId;
20205
+ state.trafDefaultSampleDuration = tfhd.defaultSampleDuration || state.trexDefaults.get(tfhd.trackId) || 0;
20206
+ break;
20207
+ }
20208
+ case "trun":
20209
+ {
20210
+ const duration = parseTrunDuration(buf, bodyStart, bodyEnd, state.trafDefaultSampleDuration);
20211
+ state.fragmentDurations.set(state.trafTrackId, (state.fragmentDurations.get(state.trafTrackId) || 0) + duration);
20212
+ break;
20213
+ }
20214
+ }
20215
+ off += size;
20216
+ }
20217
+ }
20218
+ const UNKNOWN_DURATION_32 = 0xffffffff;
20219
+ function isUsableDuration(duration) {
20220
+ return duration > 0 && duration !== UNKNOWN_DURATION_32;
20221
+ }
20222
+ function resolveDuration(movie, video, fragmentDurations) {
20223
+ if (movie && movie.timescale && isUsableDuration(movie.duration)) return movie.duration / movie.timescale;
20224
+ if (video.timescale) {
20225
+ if (isUsableDuration(video.mdhdDuration)) return video.mdhdDuration / video.timescale;
20226
+ if (video.sttsDuration > 0) return video.sttsDuration / video.timescale;
20227
+ const fragment = fragmentDurations.get(video.trackId) ?? (1 === fragmentDurations.size ? [
20228
+ ...fragmentDurations.values()
20229
+ ][0] : 0);
20230
+ if (fragment > 0) return fragment / video.timescale;
20231
+ }
20232
+ return 0;
20233
+ }
20234
+ function parseSttsDuration(buf, start, end) {
20235
+ if (start + 8 > end) return 0;
20236
+ const entryCount = buf.readUInt32BE(start + 4);
20237
+ let total = 0;
20238
+ for(let i = 0; i < entryCount; i++){
20239
+ const off = start + 8 + 8 * i;
20240
+ if (off + 8 > end) break;
20241
+ total += buf.readUInt32BE(off) * buf.readUInt32BE(off + 4);
20242
+ }
20243
+ return total;
20244
+ }
20245
+ function parseTfhd(buf, start, end) {
20246
+ if (start + 8 > end) return {
20247
+ trackId: 0,
20248
+ defaultSampleDuration: 0
20249
+ };
20250
+ const flags = buf.readUIntBE(start + 1, 3);
20251
+ const trackId = buf.readUInt32BE(start + 4);
20252
+ let off = start + 8;
20253
+ if (0x000001 & flags) off += 8;
20254
+ if (0x000002 & flags) off += 4;
20255
+ if (0x000008 & flags && off + 4 <= end) return {
20256
+ trackId,
20257
+ defaultSampleDuration: buf.readUInt32BE(off)
20258
+ };
20259
+ return {
20260
+ trackId,
20261
+ defaultSampleDuration: 0
20262
+ };
20263
+ }
20264
+ function parseTrunDuration(buf, start, end, defaultSampleDuration) {
20265
+ if (start + 8 > end) return 0;
20266
+ const flags = buf.readUIntBE(start + 1, 3);
20267
+ const sampleCount = buf.readUInt32BE(start + 4);
20268
+ let off = start + 8;
20269
+ if (0x000001 & flags) off += 4;
20270
+ if (0x000004 & flags) off += 4;
20271
+ const hasDuration = (0x000100 & flags) !== 0;
20272
+ if (!hasDuration) return sampleCount * defaultSampleDuration;
20273
+ const entrySize = 4 + ((0x000200 & flags) !== 0 ? 4 : 0) + ((0x000400 & flags) !== 0 ? 4 : 0) + ((0x000800 & flags) !== 0 ? 4 : 0);
20274
+ let total = 0;
20275
+ for(let i = 0; i < sampleCount; i++){
20276
+ const entryOff = off + i * entrySize;
20277
+ if (entryOff + 4 > end) break;
20278
+ total += buf.readUInt32BE(entryOff);
20279
+ }
20280
+ return total;
20281
+ }
20282
+ function parseStsdCodec(buf, start, end) {
20283
+ if (start + 16 > end) return null;
20284
+ if (0 === buf.readUInt32BE(start + 4)) return null;
20285
+ return buf.toString("latin1", start + 12, start + 16).toLowerCase();
20286
+ }
20287
+ function parseMvhd(buf, start, end) {
20288
+ const version = buf.readUInt8(start);
20289
+ if (1 === version) {
20290
+ if (start + 28 > end) return null;
20291
+ const timescale = buf.readUInt32BE(start + 20);
20292
+ const hi = buf.readUInt32BE(start + 24);
20293
+ const lo = buf.readUInt32BE(start + 28);
20294
+ return {
20295
+ timescale,
20296
+ duration: hi * 2 ** 32 + lo
20297
+ };
20298
+ }
20299
+ if (start + 20 > end) return null;
20300
+ return {
20301
+ timescale: buf.readUInt32BE(start + 12),
20302
+ duration: buf.readUInt32BE(start + 16)
20303
+ };
20304
+ }
20305
+ function parseTkhd(buf, start, end) {
20306
+ const version = buf.readUInt8(start);
20307
+ const afterDuration = 1 === version ? 36 : 24;
20308
+ const matrixOff = start + afterDuration + 16;
20309
+ const whOff = matrixOff + 36;
20310
+ const trackIdOff = start + (1 === version ? 20 : 12);
20311
+ const trackId = trackIdOff + 4 <= end ? buf.readUInt32BE(trackIdOff) : 0;
20312
+ if (whOff + 8 > end) return {
20313
+ trackId,
20314
+ width: 0,
20315
+ height: 0,
20316
+ rotation: 0
20317
+ };
20318
+ const width = buf.readUInt32BE(whOff) / 65536;
20319
+ const height = buf.readUInt32BE(whOff + 4) / 65536;
20320
+ const a = buf.readInt32BE(matrixOff) / 65536;
20321
+ const b = buf.readInt32BE(matrixOff + 4) / 65536;
20322
+ let rotation = 0;
20323
+ if (Math.abs(a) < 0.01 && Math.abs(b - 1) < 0.01) rotation = 90;
20324
+ else if (Math.abs(a + 1) < 0.01 && Math.abs(b) < 0.01) rotation = 180;
20325
+ else if (Math.abs(a) < 0.01 && Math.abs(b + 1) < 0.01) rotation = 270;
20326
+ return {
20327
+ trackId,
20328
+ width,
20329
+ height,
20330
+ rotation
20331
+ };
20332
+ }
20333
+ function parseVideoCodec(filePath) {
20334
+ return parseVideoMeta(filePath)?.codec ?? null;
20335
+ }
20336
+ function buildVideoMetaFromParams(filePath, metadata) {
20337
+ return {
20338
+ width: Math.round(metadata.width),
20339
+ height: Math.round(metadata.height),
20340
+ duration: metadata.duration,
20341
+ rotation: 0,
20342
+ fileSize: metadata.fileSize,
20343
+ codec: parseVideoCodec(filePath)
20344
+ };
20345
+ }
20346
+ const MAX_DURATION_SECONDS = 28800;
20347
+ const MAX_FILE_SIZE = 21474836480;
20348
+ const ALLOWED_EXTENSIONS = [
20349
+ ".mp4"
20350
+ ];
20351
+ const ALLOWED_CODECS = [
20352
+ "avc1",
20353
+ "avc3"
20354
+ ];
20355
+ const MIN_TITLE_LENGTH = 6;
20356
+ function formatFileSize(bytes) {
20357
+ if (bytes < 1048576) return `${(bytes / 1024).toFixed(2)} KB`;
20358
+ if (bytes < 1073741824) return `${(bytes / 1024 / 1024).toFixed(2)} MB`;
20359
+ return `${(bytes / 1024 / 1024 / 1024).toFixed(2)} GB`;
20360
+ }
20361
+ function formatDuration(seconds) {
20362
+ const total = Math.round(seconds);
20363
+ const h = Math.floor(total / 3600);
20364
+ const m = Math.floor(total % 3600 / 60);
20365
+ const s = total % 60;
20366
+ if (h > 0) return `${h}小时${m}分${s}秒`;
20367
+ if (m > 0) return `${m}分${s}秒`;
20368
+ return `${s}秒`;
20369
+ }
20370
+ function validateShipinhaoVideo(filePath, meta) {
20371
+ const fileName = external_node_path_default().basename(filePath);
20372
+ const ext = external_node_path_default().extname(fileName).toLowerCase();
20373
+ if (!ALLOWED_EXTENSIONS.includes(ext)) return `视频格式不支持:${fileName}。视频号仅支持 MP4/H.264 格式,请转换后重试。`;
20374
+ if (meta.duration > MAX_DURATION_SECONDS) return `视频时长超过限制:${fileName}(${formatDuration(meta.duration)})。视频号视频时长不能超过 8 小时,请剪辑后重试。`;
20375
+ if (meta.fileSize > MAX_FILE_SIZE) return `视频大小超过限制:${fileName}(${formatFileSize(meta.fileSize)})。视频号视频不能超过 20GB,请压缩后重试。`;
20376
+ if (meta.codec && !ALLOWED_CODECS.includes(meta.codec)) return `视频编码不支持:${fileName}(${meta.codec})。视频号仅支持 H.264 编码,请转码后重试。`;
20377
+ return null;
20378
+ }
20379
+ function validateShipinhaoTitle(title) {
20380
+ if (void 0 === title) return null;
20381
+ const trimmed = title.trim();
20382
+ const length = [
20383
+ ...trimmed
20384
+ ].length;
20385
+ if (length < MIN_TITLE_LENGTH) return `视频号标题至少需要 ${MIN_TITLE_LENGTH} 个字符,请补充后重试。`;
20386
+ return null;
20387
+ }
20388
+ const POST_CREATE_PAGE_URL = "https://channels.weixin.qq.com/micro/content/post/create";
20389
+ const MICRO_CONTENT_BASE = "https://channels.weixin.qq.com/micro/content/cgi-bin/mmfinderassistant-bin";
20390
+ function resolveClientContext(params, fallbackUin) {
20391
+ const extra = params.extraParam || {};
20392
+ const deviceIdCookie = params.cookies.find((c)=>"device_id" === c.name || "finger_print_device_id" === c.name)?.value;
20393
+ return {
20394
+ aId: "string" == typeof extra.aId ? extra.aId : "",
20395
+ fingerPrintDeviceId: "string" == typeof extra.fingerPrintDeviceId ? extra.fingerPrintDeviceId : deviceIdCookie || "",
20396
+ uin: "string" == typeof extra.uin ? extra.uin : String(fallbackUin)
20397
+ };
20398
+ }
20399
+ function buildPublishHeaders(cookieString, client) {
20400
+ const headers = {
20401
+ cookie: cookieString,
20402
+ referer: POST_CREATE_PAGE_URL,
20403
+ origin: "https://channels.weixin.qq.com",
20404
+ "content-type": "application/json"
20405
+ };
20406
+ if (client.fingerPrintDeviceId) headers["finger-print-device-id"] = client.fingerPrintDeviceId;
20407
+ if (client.uin) headers["x-wechat-uin"] = client.uin;
20408
+ return headers;
20409
+ }
20410
+ function buildPublishQuery(client) {
20411
+ const query = {
20412
+ _rid: rid(),
20413
+ _pageUrl: POST_CREATE_PAGE_URL
20414
+ };
20415
+ if (client.aId) query._aid = client.aId;
20416
+ return query;
20417
+ }
20418
+ function buildCommonBody(finderUsername) {
20419
+ return {
20420
+ timestamp: String(Date.now()),
20421
+ _log_finder_uin: "",
20422
+ _log_finder_id: finderUsername,
20423
+ rawKeyBuff: "",
20424
+ pluginSessionId: null,
20425
+ scene: 7,
20426
+ reqScene: 7
20427
+ };
20428
+ }
20429
+ async function getTraceKey(auth, client, http, logger) {
20430
+ logger.info("[getTraceKey] 开始获取 traceKey...");
20431
+ const res = await http.api({
20432
+ method: "POST",
20433
+ url: `${MICRO_CONTENT_BASE}/post/get-finder-post-trace-key`,
20434
+ params: buildPublishQuery(client),
20435
+ data: {
20436
+ objectId: "",
20437
+ ...buildCommonBody(auth.finderUsername)
20438
+ },
20439
+ defaultErrorMsg: "获取 traceKey 失败"
20440
+ });
20441
+ if (0 !== res.errCode || !res.data?.traceKey) {
20442
+ logger.error("[getTraceKey] 获取失败:", JSON.stringify(res));
20443
+ throw new Error(`获取 traceKey 失败: ${JSON.stringify(res)}`);
20444
+ }
20445
+ logger.info(`[getTraceKey] 获取成功: ${res.data.traceKey}`);
20446
+ return res.data.traceKey;
20447
+ }
20448
+ async function getObjectTagKey(auth, client, http, logger) {
20449
+ logger.info("[getObjectTagKey] 获取内容声明 tagKey...");
20450
+ try {
20451
+ const res = await http.api({
20452
+ method: "POST",
20453
+ url: `${MICRO_CONTENT_BASE}/post/finder_get_object_tag_list`,
20454
+ params: buildPublishQuery(client),
20455
+ data: {
20456
+ source: 1,
20457
+ ...buildCommonBody(auth.finderUsername)
20458
+ },
20459
+ defaultErrorMsg: "获取内容声明标注失败"
20460
+ });
20461
+ if (0 !== res.errCode || !res.data?.tagKey) {
20462
+ logger.warn(`[getObjectTagKey] 未取到 tagKey: ${JSON.stringify(res)}`);
20463
+ return null;
20464
+ }
20465
+ logger.info(`[getObjectTagKey] tagKey: ${res.data.tagKey}`);
20466
+ return res.data.tagKey;
20467
+ } catch (error) {
20468
+ logger.warn(`[getObjectTagKey] 获取 tagKey 异常: ${stringifyError(error)}`);
20469
+ return null;
20470
+ }
20471
+ }
20472
+ async function submitAndPollTranscode(opts) {
20473
+ const { videoUrl, videoMeta, traceKey, uploadStartTime, uploadEndTime, finderUsername, client, http, logger } = opts;
20474
+ logger.info("[submitAndPollTranscode] 开始提交转码任务...");
20475
+ const finderUrl = videoUrl.includes("wxapp.tc.qq.com") ? `https://finder.video.qq.com${videoUrl.split("qq.com")[1]}` : videoUrl;
20476
+ logger.info(`[submitAndPollTranscode] 视频尺寸: ${videoMeta.width}x${videoMeta.height}, 时长: ${videoMeta.duration}s`);
20477
+ const submitRes = await http.api({
20478
+ method: "POST",
20479
+ url: `${MICRO_CONTENT_BASE}/post/post_clip_video`,
20480
+ params: buildPublishQuery(client),
20481
+ data: {
20482
+ url: finderUrl,
20483
+ timeStart: 0,
20484
+ cropDuration: 0,
20485
+ height: videoMeta.height,
20486
+ width: videoMeta.width,
20487
+ x: 0,
20488
+ y: 0,
20489
+ clipOriginVideoInfo: {
20490
+ width: videoMeta.width,
20491
+ height: videoMeta.height,
20492
+ duration: videoMeta.duration,
20493
+ fileSize: videoMeta.fileSize
20494
+ },
20495
+ traceInfo: {
20496
+ traceKey,
20497
+ uploadCdnStart: uploadStartTime,
20498
+ uploadCdnEnd: uploadEndTime
20499
+ },
20500
+ targetWidth: videoMeta.width,
20501
+ targetHeight: videoMeta.height,
20502
+ type: 4,
20503
+ useAstraThumbCover: 1,
20504
+ ...buildCommonBody(finderUsername)
20505
+ },
20506
+ defaultErrorMsg: "提交转码失败"
20507
+ });
20508
+ if (0 !== submitRes.errCode || !submitRes.data?.clipKey) {
20509
+ logger.error("[submitAndPollTranscode] 提交转码失败:", JSON.stringify(submitRes));
20510
+ throw new Error(`提交转码失败: ${JSON.stringify(submitRes)}`);
20511
+ }
20512
+ const { clipKey, draftId } = submitRes.data;
20513
+ logger.info(`[submitAndPollTranscode] 转码任务已提交,clipKey: ${clipKey}, draftId: ${draftId}`);
20514
+ const pollInterval = 5000;
20515
+ const pollBudget = Math.min(1800000, 300000 + 1000 * Math.ceil(1.5 * videoMeta.duration));
20516
+ const maxPolls = Math.ceil(pollBudget / pollInterval);
20517
+ let pollCount = 0;
20518
+ logger.info(`[submitAndPollTranscode] 开始轮询转码结果,最多 ${maxPolls} 次(${Math.round(pollBudget / 1000)}s),间隔 ${pollInterval / 1000}s`);
20519
+ while(pollCount < maxPolls){
20520
+ await sleep(pollInterval);
20521
+ pollCount++;
20522
+ const pollRes = await http.api({
20523
+ method: "POST",
20524
+ url: `${MICRO_CONTENT_BASE}/post/post_clip_video_result`,
20525
+ params: buildPublishQuery(client),
20526
+ data: {
20527
+ clipKey,
20528
+ draftId,
20529
+ ...buildCommonBody(finderUsername)
20530
+ },
20531
+ defaultErrorMsg: "转码轮询失败"
20532
+ }, {
20533
+ timeout: 60000,
20534
+ retries: 2,
20535
+ retryDelay: 3000
20536
+ });
20537
+ if (0 !== pollRes.errCode) {
20538
+ logger.error(`[submitAndPollTranscode] 转码轮询失败 (poll ${pollCount}):`, JSON.stringify(pollRes));
20539
+ throw new Error(`转码轮询失败 (poll ${pollCount}): ${JSON.stringify(pollRes)}`);
20540
+ }
20541
+ const { flag, url, width, height, duration, md5, fileSize } = pollRes.data || {};
20542
+ logger.info(`[submitAndPollTranscode] 轮询第 ${pollCount} 次,flag=${flag}`);
20543
+ if (1 === flag) {
20544
+ if (!url || !width || !height || !duration || !md5 || !fileSize) {
20545
+ logger.error("[submitAndPollTranscode] 转码完成但返回数据不完整:", JSON.stringify(pollRes.data));
20546
+ throw new Error(`转码完成但返回数据不完整: ${JSON.stringify(pollRes.data)}`);
20547
+ }
20548
+ logger.info(`[submitAndPollTranscode] 转码完成! 用时: ${pollCount * pollInterval / 1000}s`);
20549
+ logger.info(`[submitAndPollTranscode] 视频信息: ${width}x${height}, 时长: ${duration}s, 大小: ${fileSize}`);
20550
+ return {
20551
+ clipKey,
20552
+ url,
20553
+ width,
20554
+ height,
20555
+ duration,
20556
+ md5,
20557
+ fileSize
20558
+ };
20559
+ }
20560
+ if (2 === flag) logger.info(`[submitAndPollTranscode] 转码中... (${pollCount}/${maxPolls})`);
20561
+ else {
20562
+ logger.error(`[submitAndPollTranscode] 转码失败,未知 flag=${flag}:`, JSON.stringify(pollRes.data));
20563
+ throw new Error(`转码失败,未知 flag=${flag}: ${JSON.stringify(pollRes.data)}`);
20564
+ }
20565
+ }
20566
+ logger.error(`[submitAndPollTranscode] 转码超时,已轮询 ${maxPolls} 次,用时: ${maxPolls * pollInterval / 1000}s`);
20567
+ throw new Error(`转码超时 (${maxPolls * pollInterval / 1000}s)`);
20568
+ }
20569
+ async function publishVideo(opts) {
20570
+ const { params, auth, client, clipResult, videoUpload, coverUpload, verticalCoverUpload, videoMeta, traceKey, tagKey, uploadStartTime, uploadEndTime, proxyHttp, logger } = opts;
20571
+ logger.info("[publishVideo] 开始构建发布请求...");
20572
+ const toFinderUrl = (url)=>url.includes("wxapp.tc.qq.com") ? `https://finder.video.qq.com${url.split("qq.com")[1]}` : url;
20573
+ const thumbFinderUrl = toFinderUrl(coverUpload.downloadUrl);
20574
+ const coverFinderUrl = toFinderUrl(verticalCoverUpload.downloadUrl);
20575
+ const md5sumUuid = external_node_crypto_default().randomUUID();
20576
+ const description = params.description;
20577
+ logger.info("[publishVideo] 发布参数:");
20578
+ logger.info(` - 短标题: ${params.title || "(无)"}`);
20579
+ logger.info(` - 描述: ${description.substring(0, 50)}${description.length > 50 ? "..." : ""}`);
20580
+ logger.info(` - 定时发布: ${params.scheduledTime ? new Date(1000 * params.scheduledTime).toLocaleString() : "立即发布"}`);
20581
+ const objectDesc = {
20582
+ mpTitle: "",
20583
+ description,
20584
+ extReading: buildExtReading(params.link),
20585
+ mediaType: 4,
20586
+ location: payload_buildLocation(params.location),
20587
+ topic: buildTopic({
20588
+ description: params.description,
20589
+ topics: params.topics,
20590
+ mentionedUsers: params.mentionedUsers,
20591
+ collection: params.collection
20592
+ }),
20593
+ event: buildEvent(params.event),
20594
+ mentionedUser: buildMentionedUser(params.mentionedUsers),
20595
+ media: [
20596
+ {
20597
+ url: clipResult.url,
20598
+ fileSize: clipResult.fileSize,
20599
+ thumbUrl: thumbFinderUrl,
20600
+ fullThumbUrl: thumbFinderUrl,
20601
+ coverUrl: coverFinderUrl,
20602
+ fullCoverUrl: coverFinderUrl,
20603
+ shareCoverUrl: coverFinderUrl,
20604
+ mediaType: 4,
20605
+ videoPlayLen: Math.round(clipResult.duration),
20606
+ width: clipResult.width,
20607
+ height: clipResult.height,
20608
+ md5sum: md5sumUuid,
20609
+ cardShowStyle: 2,
20610
+ urlCdnTaskId: clipResult.clipKey
20611
+ }
20612
+ ],
20613
+ shortTitle: params.title ? [
20614
+ {
20615
+ shortTitle: params.title
20616
+ }
20617
+ ] : [],
20618
+ member: {}
20619
+ };
20620
+ const publishData = {
20621
+ objectType: 0,
20622
+ longitude: 0,
20623
+ latitude: 0,
20624
+ feedLongitude: 0,
20625
+ feedLatitude: 0,
20626
+ originalFlag: params.originalFlag ?? 0,
20627
+ topics: params.topics || [],
20628
+ isFullPost: 1,
20629
+ handleFlag: 2,
20630
+ videoClipTaskId: clipResult.clipKey,
20631
+ traceInfo: {
20632
+ traceKey,
20633
+ uploadCdnStart: uploadStartTime,
20634
+ uploadCdnEnd: uploadEndTime
20635
+ },
20636
+ objectDesc,
20637
+ report: {
20638
+ clipKey: clipResult.clipKey,
20639
+ draftId: clipResult.clipKey,
20640
+ ...buildCommonBody(auth.finderUsername),
20641
+ height: videoMeta.height,
20642
+ width: videoMeta.width,
20643
+ duration: videoMeta.duration,
20644
+ fileSize: videoUpload.fileSize,
20645
+ uploadCost: (uploadEndTime - uploadStartTime) * 1000
20646
+ },
20647
+ postFlag: 0,
20648
+ mode: 1,
20649
+ clientid: external_node_crypto_default().randomUUID(),
20650
+ ...buildCommonBody(auth.finderUsername)
20651
+ };
20652
+ if (params.scheduledTime) publishData.effectiveTime = params.scheduledTime;
20653
+ if (params.tagInfo && tagKey) publishData.tagInfo = buildTagInfo(params.tagInfo, tagKey);
20654
+ logger.info("[publishVideo] 开始发布视频,全部参数:" + JSON.stringify(publishData));
20655
+ const publishRes = await proxyHttp.api({
20656
+ method: "POST",
20657
+ url: `${MICRO_CONTENT_BASE}/post/post_create`,
20658
+ params: buildPublishQuery(client),
20659
+ data: publishData,
20660
+ defaultErrorMsg: "发布视频失败"
20661
+ });
20662
+ logger.info(`[publishVideo] 发布响应: errCode=${publishRes.errCode}, baseResp.errcode=${publishRes.data?.baseResp?.errcode}`);
20663
+ return publishRes;
20664
+ }
20665
+ function sleep(ms) {
20666
+ return new Promise((resolve)=>setTimeout(resolve, ms));
20667
+ }
20668
+ async function resolveLocalCoverPath(coverPath, label, tmpCachePath, logger) {
20669
+ if (!/^https?:\/\//i.test(coverPath)) return coverPath;
20670
+ const fileName = (0, share_namespaceObject.getFilenameFromUrl)(coverPath);
20671
+ const savePath = external_node_path_default().join(tmpCachePath, `${Date.now()}-${label}-${fileName}`);
20672
+ await (0, share_namespaceObject.downloadImage)(coverPath, savePath);
20673
+ return savePath;
20674
+ }
20675
+ const shipinhaoPublishVideo_mock_mockAction = async (task, params)=>{
20676
+ task.logger.info("[shipinhaoPublishVideo] 开始执行视频号视频发布 - Mock API 方式");
20677
+ const updateTaskState = task.taskStageStore?.update?.bind(task.taskStageStore, task.taskId || "");
20678
+ let currentStep = "初始化";
20679
+ try {
20680
+ task.logger.info(`[shipinhaoPublishVideo] 发布方式: ${params.scheduledTime ? `定时 ${new Date(1000 * params.scheduledTime).toLocaleString()}` : "立即发布"}`);
20681
+ currentStep = "解析认证信息";
20682
+ const cookieString = params.cookies.map((c)=>`${c.name}=${c.value}`).join("; ");
20683
+ const http = new Http({
20684
+ headers: {
20685
+ cookie: cookieString
20686
+ }
20687
+ });
20688
+ currentStep = "验证发布参数";
20689
+ if (!params.videoPath) return (0, share_namespaceObject.response)(414, "视频文件路径不能为空", "");
20690
+ if (!params.coverPath) return (0, share_namespaceObject.response)(414, "横屏封面图片路径不能为空", "");
20691
+ currentStep = "获取上传认证";
20692
+ task.logger.info("[shipinhaoPublishVideo] 获取上传认证...");
20693
+ const auth = await getShipinhaoUploadAuth(cookieString, http);
20694
+ const client = resolveClientContext(params, auth.uin);
20695
+ if (!client.aId) task.logger.warn("[shipinhaoPublishVideo] extraParam.aId 缺失,query 将不带 _aid");
20696
+ if (!client.fingerPrintDeviceId) task.logger.warn("[shipinhaoPublishVideo] extraParam.fingerPrintDeviceId 缺失,请求将不带 finger-print-device-id");
20697
+ const publishHeaders = buildPublishHeaders(cookieString, client);
20698
+ const microHttp = new Http({
20699
+ headers: publishHeaders
20700
+ });
20701
+ const args = [
20702
+ {
20703
+ headers: publishHeaders
20704
+ },
20705
+ task.logger,
20706
+ params.proxyLoc,
20707
+ params.accountId,
20708
+ "shipinhao"
20709
+ ];
20710
+ const proxyHttp = new Http(...args);
20711
+ currentStep = "组装视频元数据";
20712
+ task.logger.info("[shipinhaoPublishVideo] 组装视频元数据...");
20713
+ const videoMeta = buildVideoMetaFromParams(params.videoPath, params.videoMetadata);
20714
+ task.logger.info(`[shipinhaoPublishVideo] 视频: ${videoMeta.width}×${videoMeta.height}, ${videoMeta.duration.toFixed(2)}s, ${(videoMeta.fileSize / 1024 / 1024).toFixed(2)}MB, codec=${videoMeta.codec || "unknown"}`);
20715
+ if (!videoMeta.codec) task.logger.warn("[shipinhaoPublishVideo] 未能读取视频编码格式,跳过 H.264 预检,交由服务端判断");
20716
+ currentStep = "校验视频限制";
20717
+ const validationError = validateShipinhaoVideo(params.videoPath, videoMeta);
20718
+ if (validationError) {
20719
+ task.logger.error(`[shipinhaoPublishVideo] 视频校验未通过: ${validationError}`);
20720
+ await updateTaskState?.({
20721
+ state: share_namespaceObject.TaskState.FAILED,
20722
+ error: validationError
20723
+ });
20724
+ return (0, share_namespaceObject.response)(414, validationError, "");
20725
+ }
20726
+ task.logger.info("[shipinhaoPublishVideo] 视频校验通过");
20727
+ currentStep = "校验标题";
20728
+ const titleError = validateShipinhaoTitle(params.title);
20729
+ if (titleError) {
20730
+ task.logger.error(`[shipinhaoPublishVideo] 标题校验未通过: ${titleError}`);
20731
+ await updateTaskState?.({
20732
+ state: share_namespaceObject.TaskState.FAILED,
20733
+ error: titleError
20734
+ });
20735
+ return (0, share_namespaceObject.response)(414, titleError, "");
20736
+ }
20737
+ currentStep = "获取 traceKey";
20738
+ task.logger.info("[shipinhaoPublishVideo] 获取 traceKey...");
20739
+ const traceKey = await getTraceKey(auth, client, microHttp, task.logger);
20740
+ let tagKey = null;
20741
+ if (params.tagInfo) {
20742
+ currentStep = "获取内容声明 tagKey";
20743
+ tagKey = await getObjectTagKey(auth, client, microHttp, task.logger);
20744
+ }
20745
+ const uploadStartTime = Math.floor(Date.now() / 1000);
20746
+ task.logger.info(`[shipinhaoPublishVideo] 上传开始时间: ${uploadStartTime}`);
20747
+ currentStep = "上传视频";
20748
+ task.logger.info("[shipinhaoPublishVideo] 上传视频...");
20749
+ task.logger.info(`[shipinhaoPublishVideo] 视频路径: ${params.videoPath}`);
20750
+ task.logger.info(`[shipinhaoPublishVideo] 视频文件类型: ${auth.videoFileType}`);
20751
+ const videoUpload = await uploader_uploadFile({
20752
+ filePath: params.videoPath,
20753
+ fileType: auth.videoFileType,
20754
+ uin: auth.uin,
20755
+ authKey: auth.authKey,
20756
+ http,
20757
+ logger: task.logger
20758
+ });
20759
+ task.logger.info("[shipinhaoPublishVideo] 视频上传完成");
20760
+ const uploadEndTime = Math.floor(Date.now() / 1000);
20761
+ task.logger.info(`[shipinhaoPublishVideo] 上传结束时间: ${uploadEndTime}, 耗时: ${uploadEndTime - uploadStartTime}s`);
20762
+ currentStep = "上传横屏封面";
20763
+ const localCoverPath = await resolveLocalCoverPath(params.coverPath, "横屏封面", task.getTmpPath(), task.logger);
20764
+ task.logger.info("[shipinhaoPublishVideo] 上传横屏封面...");
20765
+ const coverUpload = await uploader_uploadFile({
20766
+ filePath: localCoverPath,
20767
+ fileType: auth.pictureFileType,
20768
+ uin: auth.uin,
20769
+ authKey: auth.authKey,
20770
+ http,
20771
+ logger: task.logger
20772
+ });
20773
+ task.logger.info("[shipinhaoPublishVideo] 横屏封面上传完成");
20774
+ let verticalCoverUpload = coverUpload;
20775
+ if (params.verticalCoverPath) {
20776
+ currentStep = "上传竖屏封面";
20777
+ const localVerticalPath = await resolveLocalCoverPath(params.verticalCoverPath, "竖屏封面", task.getTmpPath(), task.logger);
20778
+ task.logger.info("[shipinhaoPublishVideo] 上传竖屏封面");
20779
+ verticalCoverUpload = await uploader_uploadFile({
20780
+ filePath: localVerticalPath,
20781
+ fileType: auth.pictureFileType,
20782
+ uin: auth.uin,
20783
+ authKey: auth.authKey,
20784
+ http,
20785
+ logger: task.logger
20786
+ });
20787
+ task.logger.info("[shipinhaoPublishVideo] 竖屏封面上传完成");
20788
+ } else task.logger.info("[shipinhaoPublishVideo] 未传竖屏封面,复用横屏封面");
20789
+ currentStep = "提交转码";
20790
+ task.logger.info("[shipinhaoPublishVideo] 提交转码...");
20791
+ const clipResult = await submitAndPollTranscode({
20792
+ videoUrl: videoUpload.downloadUrl,
20793
+ videoMeta,
20794
+ traceKey,
20795
+ uploadStartTime,
20796
+ uploadEndTime,
20797
+ finderUsername: auth.finderUsername,
20798
+ client,
20799
+ http: microHttp,
20800
+ logger: task.logger
20801
+ });
20802
+ currentStep = "发布视频";
20803
+ task.logger.info("[shipinhaoPublishVideo] 发布视频...");
20804
+ task.logger.info(`[shipinhaoPublishVideo] clipKey: ${clipResult.clipKey}`);
20805
+ let publishResult;
20806
+ try {
20807
+ publishResult = await publishVideo({
20808
+ params,
20809
+ auth,
20810
+ client,
20811
+ clipResult,
20812
+ videoUpload,
20813
+ coverUpload,
20814
+ verticalCoverUpload,
20815
+ videoMeta,
20816
+ traceKey,
20817
+ tagKey,
20818
+ uploadStartTime,
20819
+ uploadEndTime,
20820
+ proxyHttp,
20821
+ logger: task.logger
20822
+ });
20823
+ } catch (error) {
20824
+ const handledError = Http.handleApiError(error);
20825
+ task.logger.error(`[shipinhaoPublishVideo] 发布请求失败: ${handledError.message}`, stringifyError(handledError));
20826
+ const classified = classifyPublishError(handledError);
20827
+ if (classified) {
20828
+ const message = `${classified.userMessage}${task.debug ? ` ${http.proxyInfo}` : ""}`;
20829
+ task.logger.error(`[shipinhaoPublishVideo] ${classified.category},直接返回: ${handledError.message} (code=${handledError.code})`, stringifyError(handledError));
20830
+ await updateTaskState?.({
20831
+ state: share_namespaceObject.TaskState.FAILED,
20832
+ error: message
20833
+ });
20834
+ return {
20835
+ code: 414,
20836
+ data: "",
20837
+ message
20838
+ };
20839
+ }
20840
+ throw error;
20841
+ }
20842
+ task.logger.info(`[shipinhaoPublishVideo] publishResult: ${JSON.stringify(publishResult)}`);
20843
+ const resultCode = publishResult.data?.baseResp?.errcode ?? publishResult.errCode;
20844
+ const resultMsg = publishResult.data?.baseResp?.errmsg ?? (0 === resultCode ? "发布成功" : `发布失败(errCode=${resultCode})`);
20845
+ if (0 === resultCode) {
20846
+ task.logger.info("[shipinhaoPublishVideo] 发布成功");
20847
+ task.logger.info(`[shipinhaoPublishVideo] 作品ID: ${clipResult.clipKey}`);
20848
+ task.logger.info(`[shipinhaoPublishVideo] 视频URL: ${clipResult.url}`);
20849
+ task.logger.info(`[shipinhaoPublishVideo] 横屏封面URL: ${coverUpload.downloadUrl}`);
20850
+ task.logger.info(`[shipinhaoPublishVideo] 竖屏封面URL: ${verticalCoverUpload.downloadUrl}`);
20851
+ await updateTaskState?.({
20852
+ state: share_namespaceObject.TaskState.SUCCESS,
20853
+ result: {
20854
+ response: resultMsg
20855
+ }
20856
+ });
20857
+ reportLogger({
20858
+ token: params.huiwenToken || "",
20859
+ enverionment: task.enverionment || "development",
20860
+ postId: params.articleId,
20861
+ eip: proxyHttp.proxyInfo,
20862
+ accountId: params.accountId,
20863
+ uid: params.uid,
20864
+ publishParams: {
20865
+ videoPath: params.videoPath,
20866
+ coverPath: params.coverPath,
20867
+ verticalCoverPath: params.verticalCoverPath,
20868
+ title: params.title,
20869
+ topics: params.topics,
20870
+ mentionedUsers: params.mentionedUsers,
20871
+ collection: params.collection,
20872
+ event: params.event,
20873
+ link: params.link,
20874
+ tagInfo: params.tagInfo,
20875
+ originalFlag: params.originalFlag,
20876
+ scheduledTime: params.scheduledTime
20877
+ },
20878
+ platform: "shipinhao"
20879
+ });
20880
+ task.logger.info("[shipinhaoPublishVideo] 日志上报完成");
20881
+ return (0, share_namespaceObject.response)(0, "发布成功", clipResult.clipKey);
20882
+ }
20883
+ let errorMessage = resultMsg;
20884
+ if (-11224 === resultCode) errorMessage = "视频号管理员完成实名且绑定手机号后才可以发表";
20885
+ else if (300333 === resultCode || 300334 === resultCode) errorMessage = "登录失效";
20886
+ else if (300330 === resultCode) errorMessage = "未登录";
20887
+ else if (300002 === resultCode) errorMessage = "官方平台在校验音乐/位置/定时信息时失败了,请重新编辑后发布";
20888
+ task.logger.error(`[shipinhaoPublishVideo] 发布失败: ${errorMessage} (errCode=${resultCode})`);
20889
+ await updateTaskState?.({
20890
+ state: share_namespaceObject.TaskState.FAILED,
20891
+ error: errorMessage
20892
+ });
20893
+ return (0, share_namespaceObject.response)(resultCode || 414, errorMessage, "");
20894
+ } catch (error) {
20895
+ const handledError = Http.handleApiError(error);
20896
+ const errorMsg = handledError.message || "发布失败,请稍后重试";
20897
+ const errorCode = handledError.code || 414;
20898
+ task.logger.error(`[shipinhaoPublishVideo] 发布流程异常 [${currentStep}]: ${errorMsg}`, stringifyError(error), handledError.extra);
20899
+ task.logger.error(`[shipinhaoPublishVideo] 错误码: ${errorCode}, 当前步骤: ${currentStep}`);
20900
+ await updateTaskState?.({
20901
+ state: share_namespaceObject.TaskState.FAILED,
20902
+ error: errorMsg
20903
+ });
20904
+ return (0, share_namespaceObject.response)(errorCode, errorMsg, "");
20905
+ }
20906
+ };
20907
+ const shipinhaoPublishVideo_rpa_rpaAction = async (task, params)=>{
20908
+ task.logger.info("开始微信视频号视频发布(RPA 模式)");
20909
+ const videoMeta = buildVideoMetaFromParams(params.videoPath, params.videoMetadata);
20910
+ task.logger.info(`视频: ${videoMeta.width}×${videoMeta.height}, ${videoMeta.duration.toFixed(2)}s, ${(videoMeta.fileSize / 1024 / 1024).toFixed(2)}MB, codec=${videoMeta.codec || "unknown"}`);
20911
+ if (!videoMeta.codec) task.logger.warn("未能读取视频编码格式,跳过 H.264 预检,交由服务端判断");
20912
+ const validationError = validateShipinhaoVideo(params.videoPath, videoMeta);
20913
+ if (validationError) {
20914
+ task.logger.error(`视频校验未通过: ${validationError}`);
20915
+ return (0, share_namespaceObject.response)(414, validationError, "");
20916
+ }
20917
+ task.logger.info("视频校验通过");
20918
+ const titleError = validateShipinhaoTitle(params.title);
20919
+ if (titleError) {
20920
+ task.logger.error(`标题校验未通过: ${titleError}`);
20921
+ return (0, share_namespaceObject.response)(414, titleError, "");
20922
+ }
20923
+ const unsupported = [
20924
+ params.verticalCoverPath && "verticalCoverPath",
20925
+ params.collection && "collection",
20926
+ params.originalFlag && "originalFlag",
20927
+ params.postWithMemberZoneLink && "postWithMemberZoneLink"
20928
+ ].filter(Boolean);
20929
+ if (unsupported.length) task.logger.warn(`RPA 模式不支持以下参数,将被忽略: ${unsupported.join("、")};如需生效请使用 mockApi 模式`);
20930
+ if (params.tagInfo && 5 === params.tagInfo.tagType) {
20931
+ const shootInfo = params.tagInfo.shootInfo;
20932
+ if (shootInfo && (shootInfo.provinceCode || shootInfo.cityCode)) task.logger.warn("tagInfo.tagType=5 在 RPA 模式下仅支持拍摄时间和国家选择,省市选择需要使用 mockApi 模式");
20933
+ }
20934
+ const tmpCachePath = task.getTmpPath();
20935
+ const page = await task.createPage({
20936
+ url: "https://channels.weixin.qq.com/platform/post/create",
20937
+ show: task.debug,
20938
+ cookies: params.cookies
20939
+ });
20940
+ try {
20941
+ const waitForElement = async (selector, timeout = 10000)=>{
20942
+ try {
20943
+ const element = page.locator(selector);
20944
+ await element.waitFor({
20945
+ state: "visible",
20946
+ timeout
20947
+ });
20948
+ return element;
20949
+ } catch {
20950
+ task.logger.warn(`元素未找到: ${selector}`);
20951
+ return null;
20952
+ }
20953
+ };
20954
+ const retryAction = async (action, maxRetries = 3, delay = 1000)=>{
20955
+ let lastError;
20956
+ for(let i = 0; i < maxRetries; i++)try {
20957
+ return await action();
20958
+ } catch (error) {
20959
+ lastError = error;
20960
+ task.logger.warn(`重试 ${i + 1}/${maxRetries}: ${lastError.message}`);
20961
+ if (i < maxRetries - 1) await page.waitForTimeout(delay);
20962
+ }
20963
+ throw lastError;
20964
+ };
20965
+ task.logger.info("等待页面加载...");
20966
+ task.logger.info("检查登录状态...");
20967
+ if (task.debug) {
20968
+ task.logger.info(`当前页面 URL: ${page.url()}`);
20969
+ const title = await page.title();
20970
+ task.logger.info(`页面标题: ${title}`);
20971
+ }
20972
+ try {
20973
+ await page.waitForSelector(".post-edit-wrap", {
20974
+ state: "visible",
20975
+ timeout: 30000
20976
+ });
20977
+ task.logger.info("✓ 登录状态正常,找到编辑器容器");
20978
+ } catch {
20979
+ task.logger.error("✗ 未找到编辑器,可能登录失效");
20980
+ return {
20981
+ code: 414,
20982
+ message: "登录失效或页面加载异常",
20983
+ data: page.url()
20984
+ };
20985
+ }
20986
+ task.logger.info("页面加载完成,开始填充内容");
20987
+ task.logger.info("开始上传视频");
20988
+ await retryAction(async ()=>{
20989
+ const videoUploadSelectors = [
20990
+ '.ant-upload-btn input[type="file"][accept*="video"]',
20991
+ '.upload input[type="file"][accept*="video"]',
20992
+ 'input[type="file"][accept*="video"]'
20993
+ ];
20994
+ let uploadInput = null;
20995
+ if (task.debug) {
20996
+ const allFileInputs = await page.locator('input[type="file"]').count();
20997
+ task.logger.info(`页面中共找到 ${allFileInputs} 个文件上传输入框`);
20998
+ }
20999
+ for (const selector of videoUploadSelectors){
21000
+ const input = page.locator(selector);
21001
+ const count = await input.count();
21002
+ if (count > 0) {
21003
+ uploadInput = input.first();
21004
+ task.logger.info(`找到视频上传输入框: ${selector}`);
21005
+ break;
21006
+ }
21007
+ }
21008
+ if (!uploadInput) {
21009
+ task.logger.warn("未找到视频上传输入框,等待 3 秒后重试...");
21010
+ await page.waitForTimeout(3000);
21011
+ const anyFileInput = page.locator('input[type="file"]');
21012
+ const inputCount = await anyFileInput.count();
21013
+ if (inputCount > 0) {
21014
+ uploadInput = anyFileInput.first();
21015
+ task.logger.info(`找到文件输入框(共 ${inputCount} 个)`);
21016
+ } else {
21017
+ if (task.debug) {
21018
+ const screenshotPath = external_node_path_default().join(tmpCachePath, `upload-error-${Date.now()}.png`);
21019
+ await page.screenshot({
21020
+ path: screenshotPath,
21021
+ fullPage: true
21022
+ });
21023
+ task.logger.error(`未找到上传输入框,已截图保存至: ${screenshotPath}`);
21024
+ }
21025
+ throw new Error("未找到视频上传输入框");
21026
+ }
21027
+ }
21028
+ await uploadInput.setInputFiles(params.videoPath);
21029
+ task.logger.info("视频上传成功");
21030
+ await page.waitForTimeout(5000);
21031
+ });
21032
+ if (params.coverPath) {
21033
+ task.logger.info("开始上传封面");
21034
+ await retryAction(async ()=>{
21035
+ const coverUploadBtn = await waitForElement(".cover-upload-btn", 10000);
21036
+ if (coverUploadBtn) {
21037
+ const coverInput = page.locator('.cover-upload-btn input[type="file"]');
21038
+ await coverInput.setInputFiles(params.coverPath);
21039
+ task.logger.info("封面上传成功");
21040
+ await page.waitForTimeout(2000);
21041
+ }
21042
+ });
21043
+ }
21044
+ const descriptionText = payload_buildDescription({
21045
+ description: params.description,
21046
+ topics: params.topics,
21047
+ mentionedUsers: params.mentionedUsers
21048
+ });
21049
+ if (descriptionText) {
21050
+ task.logger.info("填写视频描述");
21051
+ await retryAction(async ()=>{
21052
+ const descEditor = await waitForElement(".input-editor", 10000);
21053
+ if (!descEditor) throw new Error("未找到描述编辑器");
21054
+ await descEditor.click();
21055
+ await page.waitForTimeout(500);
21056
+ await descEditor.evaluate((el)=>{
21057
+ el.textContent = "";
21058
+ });
21059
+ await page.waitForTimeout(300);
21060
+ task.logger.info("已清空编辑器内容");
21061
+ await descEditor.pressSequentially(descriptionText, {
21062
+ delay: 10
21063
+ });
21064
+ await page.waitForTimeout(500);
21065
+ task.logger.info("描述填写完成");
21066
+ });
21067
+ }
21068
+ if (params.title) {
21069
+ task.logger.info(`填写标题: ${params.title}`);
21070
+ const title = params.title;
21071
+ await retryAction(async ()=>{
21072
+ const titleInput = await waitForElement("#container-wrap div.form-item-body.short-title-wrap input", 10000);
21073
+ if (!titleInput) throw new Error("未找到标题输入框");
21074
+ await titleInput.click();
21075
+ await titleInput.clear({
21076
+ timeout: 3000
21077
+ });
21078
+ await titleInput.fill(title, {
21079
+ timeout: 5000
21080
+ });
21081
+ task.logger.info("标题填写完成");
21082
+ });
21083
+ }
21084
+ if (params.location) {
21085
+ task.logger.info(`选择地点: ${params.location.city}`);
21086
+ const instance = page.locator(".position-display-wrap");
21087
+ await instance.click();
21088
+ await page.waitForTimeout(1000);
21089
+ await page.locator(".location-filter-wrap input").fill(params.location.city);
21090
+ await page.waitForTimeout(2000);
21091
+ const poperInstance = page.locator(".location-filter-wrap .common-option-list-wrap .option-item");
21092
+ await poperInstance.nth(1).waitFor();
21093
+ await poperInstance.nth(1).click();
21094
+ task.logger.info("地点选择完成");
21095
+ }
21096
+ if (params.collection) {
21097
+ task.logger.info(`选择合集: ${params.collection.collectionName}`);
21098
+ const instanceCollection = page.locator(".post-album-display-wrap");
21099
+ await instanceCollection.click();
21100
+ await page.waitForTimeout(1000);
21101
+ page.locator(".post-album-wrap .option-item").filter({
21102
+ hasText: params.collection.collectionName
21103
+ }).first().click({
21104
+ force: true
21105
+ });
21106
+ }
21107
+ if (params.link) {
21108
+ task.logger.info(`设置扩展阅读链接: ${params.link.title}`);
21109
+ await page.locator(".post-link-wrap .link-display-wrap").click();
21110
+ await page.waitForTimeout(300);
21111
+ const linkTypeText = 2 === params.link.urlType ? "红包封面" : "公众号文章";
21112
+ await page.locator(".link-option-item .title-wrap span").filter({
21113
+ hasText: linkTypeText
21114
+ }).click();
21115
+ await page.waitForTimeout(300);
21116
+ const placeholder = 2 === params.link.urlType ? "粘贴红包封面链接" : "粘贴公众号文章链接";
21117
+ await page.locator(`.link-input-wrap input[placeholder="${placeholder}"]`).fill(params.link.link);
21118
+ await page.waitForTimeout(500);
21119
+ task.logger.info(`已设置${linkTypeText}: ${params.link.link}`);
21120
+ }
21121
+ if (params.event) {
21122
+ task.logger.info(`选择活动: ${params.event.eventName}`);
21123
+ await page.locator(".post-activity-wrap .activity-display").click();
21124
+ await page.waitForTimeout(500);
21125
+ await page.locator(".activity-filter-wrap .weui-desktop-form__input[placeholder='搜索活动']").fill(params.event.eventName);
21126
+ await page.waitForTimeout(500);
21127
+ const searchLoading = page.locator(".search-loading");
21128
+ await searchLoading.waitFor({
21129
+ state: "hidden",
21130
+ timeout: 5000
21131
+ }).catch(()=>{
21132
+ task.logger.warn("活动搜索加载超时,继续尝试选择");
21133
+ });
21134
+ const activityItem = page.locator(".option-item .activity-item .activity-item-info .name").filter({
21135
+ hasText: params.event.eventName
21136
+ });
21137
+ const count = await activityItem.count();
21138
+ if (count > 0) {
21139
+ await activityItem.first().click();
21140
+ await page.waitForTimeout(300);
21141
+ task.logger.info(`已选择活动: ${params.event.eventName}`);
21142
+ } else {
21143
+ task.logger.warn(`未找到活动: ${params.event.eventName},将不参与活动`);
21144
+ await page.locator(".post-activity-wrap .activity-display").click();
21145
+ await page.waitForTimeout(300);
21146
+ }
21147
+ }
21148
+ if (params.scheduledTime) {
21149
+ task.logger.info("设置定时发布");
21150
+ const timingRadio = page.locator(".weui-desktop-form__check-label").filter({
21151
+ hasNotText: "不定时"
21152
+ }).first();
21153
+ await timingRadio.click();
21154
+ await page.waitForTimeout(500);
21155
+ const instance = page.locator(".weui-desktop-picker__date");
21156
+ await instance.click();
21157
+ const dateD = utils_TimeFormatter.format(1000 * params.scheduledTime, "d");
21158
+ const nowMonth = utils_TimeFormatter.format(Date.now(), "MM月");
21159
+ const nowMonthText = utils_TimeFormatter.format(Date.now(), "M月");
21160
+ const month = utils_TimeFormatter.format(1000 * params.scheduledTime, "MM月");
21161
+ const monthLocator = await page.locator("weui-desktop-picker__panel__label").filter({
21162
+ hasText: month
21163
+ }).first();
21164
+ if (!monthLocator) {
21165
+ await page.locator(".weui-desktop-picker__panel__label").filter({
21166
+ hasText: nowMonth
21167
+ }).first().click();
21168
+ await page.waitForTimeout(500);
21169
+ await page.locator(".weui-desktop-picker__table-row td a").filter({
21170
+ hasText: nowMonthText
21171
+ }).first().click();
21172
+ }
21173
+ await page.waitForTimeout(500);
21174
+ await page.locator(".weui-desktop-picker__table-row td a").filter({
21175
+ hasText: dateD
21176
+ }).first().click();
21177
+ await page.locator(".weui-desktop-form__input-wrp input[placeholder*='请选择时间']").fill(utils_TimeFormatter.format(1000 * params.scheduledTime, "hh:mm"));
21178
+ await page.locator("i.weui-desktop-icon__time").click();
21179
+ await page.locator(".post-time-wrap .form-item .label").filter({
21180
+ hasText: "发表时间"
21181
+ }).click();
21182
+ }
21183
+ if (params.tagInfo) {
21184
+ task.logger.info(`设置视频标注: tagType=${params.tagInfo.tagType}`);
21185
+ await page.locator(".mark-tag-select").click();
21186
+ await page.waitForTimeout(300);
21187
+ const tagTypeTextMap = {
21188
+ 0: "无需标注",
21189
+ 1: "含AI生成内容",
21190
+ 2: "内容包含营销广告",
21191
+ 3: "内容为虚构剧情,仅供娱乐",
21192
+ 5: "内容为自行拍摄",
21193
+ 7: "内容为转载",
21194
+ 8: "个人观点,仅供参考"
21195
+ };
21196
+ const tagText = tagTypeTextMap[params.tagInfo.tagType];
21197
+ if (tagText) {
21198
+ await page.locator(".mark-tag-option .option-main").filter({
21199
+ hasText: tagText
21200
+ }).click();
21201
+ await page.waitForTimeout(300);
21202
+ if (5 === params.tagInfo.tagType) {
21203
+ const shootInfo = params.tagInfo.shootInfo;
21204
+ if (shootInfo) {
21205
+ task.logger.info("填写拍摄时间和地点...");
21206
+ await page.waitForTimeout(500);
21207
+ if (shootInfo.postTimestamp) {
21208
+ task.logger.info(`设置拍摄时间: ${shootInfo.postTimestamp}`);
21209
+ const timestamp = 1000 * parseInt(shootInfo.postTimestamp, 10);
21210
+ const date = new Date(timestamp);
21211
+ await page.locator(".original-dialog-content .weui-desktop-picker__date input[placeholder*='请选择拍摄时间']").click();
21212
+ await page.waitForTimeout(300);
21213
+ const dayNum = date.getDate();
21214
+ await page.locator(".weui-desktop-picker__table a").filter({
21215
+ hasText: new RegExp(`^\\s*${dayNum}\\s*$`)
21216
+ }).first().click();
21217
+ await page.waitForTimeout(300);
21218
+ }
21219
+ if (shootInfo.countryCode || shootInfo.provinceCode || shootInfo.cityCode) {
21220
+ task.logger.info("设置拍摄地点...");
21221
+ await page.locator(".original-dialog-content .weui-desktop-form__dropdowncascade .weui-desktop-form__dropdowncascade__dt").click();
21222
+ await page.waitForTimeout(300);
21223
+ if (1156 === shootInfo.countryCode) {
21224
+ await page.locator(".weui-desktop-dropdown__list-ele .weui-desktop-dropdown__list-ele__text").filter({
21225
+ hasText: "中国"
21226
+ }).click();
21227
+ await page.waitForTimeout(300);
21228
+ task.logger.warn("RPA 模式下暂不支持选择具体省份和城市,仅选择了国家");
21229
+ } else task.logger.warn(`不支持的国家代码: ${shootInfo.countryCode},跳过地点设置`);
21230
+ }
21231
+ const confirmBtn = await waitForElement(".weui-desktop-dialog .weui-desktop-btn_primary");
21232
+ if (confirmBtn) {
21233
+ await confirmBtn.click();
21234
+ await page.waitForTimeout(300);
21235
+ }
21236
+ } else task.logger.warn("tagType=5 需要提供 shootInfo 字段(拍摄时间和地点)");
21237
+ }
21238
+ if (7 === params.tagInfo.tagType) {
21239
+ const repostSource = params.tagInfo.repostSource;
21240
+ if (repostSource) {
21241
+ task.logger.info(`填写转载来源: ${repostSource}`);
21242
+ await page.waitForTimeout(500);
21243
+ await page.locator(".repost-dialog-content .repost-textarea").fill(repostSource);
21244
+ await page.waitForTimeout(300);
21245
+ const confirmBtn = await waitForElement(".weui-desktop-dialog .weui-desktop-btn_primary");
21246
+ if (confirmBtn) {
21247
+ await confirmBtn.click();
21248
+ await page.waitForTimeout(300);
21249
+ }
21250
+ } else task.logger.warn("tagType=7 需要提供 repostSource 字段(转载来源)");
21251
+ }
21252
+ } else task.logger.warn(`未知的 tagType: ${params.tagInfo.tagType},跳过标注设置`);
21253
+ }
21254
+ task.logger.info("准备发布...");
21255
+ await page.waitForTimeout(500);
21256
+ let videoId = "";
21257
+ const handleResponse = async (response)=>{
21258
+ const url = response.url();
21259
+ if (url.includes("/post/post_create")) {
21260
+ const jsonResponse = await response.json();
21261
+ page.off("response", handleResponse);
21262
+ videoId = jsonResponse.object?.id || jsonResponse.data?.objectId || "";
21263
+ }
21264
+ };
21265
+ page.on("response", handleResponse);
21266
+ task._timerRecord.PrePublish = Date.now();
21267
+ 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";
21268
+ task.logger.info("等待视频上传完成(预览区媒体操作栏出现)...");
21269
+ const uploadTimeout = 600000;
21270
+ const uploadWaitStart = Date.now();
21271
+ let lastProgressLog = 0;
21272
+ while(true){
21273
+ const ready = await page.evaluate((selector)=>{
21274
+ const host = document.querySelector("#container-wrap > div.container-center > div > wujie-app");
21275
+ const root = host?.shadowRoot;
21276
+ if (!root) return false;
21277
+ return !!root.querySelector(selector);
21278
+ }, MEDIA_OPR_SELECTOR);
21279
+ if (ready) break;
21280
+ const elapsed = Date.now() - uploadWaitStart;
21281
+ if (elapsed > uploadTimeout) throw new Error(`视频上传超时,预览区未就绪(已等待 ${Math.round(elapsed / 1000)}s)`);
21282
+ if (elapsed - lastProgressLog >= 15000) {
21283
+ lastProgressLog = elapsed;
21284
+ task.logger.info(`视频仍在上传中... 已等待 ${Math.round(elapsed / 1000)}s`);
21285
+ }
21286
+ await page.waitForTimeout(1000);
21287
+ }
21288
+ task.logger.info(`视频上传完成(等待 ${Math.round((Date.now() - uploadWaitStart) / 1000)}s)`);
21289
+ const clicked = await page.evaluate(()=>{
21290
+ const host = document.querySelector("#container-wrap > div.container-center > div > wujie-app");
21291
+ const root = host?.shadowRoot;
21292
+ if (!root) return "未找到 wujie-app shadowRoot";
21293
+ const btns = Array.from(root.querySelectorAll(".form-btns .weui-desktop-btn"));
21294
+ const target = btns.find((el)=>(el.textContent || "").includes("发表"));
21295
+ if (!target) return "未找到发表按钮";
21296
+ if (target.classList.contains("weui-desktop-btn_disabled")) return "发表按钮仍处于禁用状态";
21297
+ target.click();
21298
+ return null;
21299
+ });
21300
+ if (clicked) throw new Error(clicked);
21301
+ task.logger.info("已点击发布按钮,等待响应...");
21302
+ try {
21303
+ await page.waitForURL((url)=>url.href !== page.url(), {
21304
+ timeout: 30000
21305
+ });
21306
+ task.logger.info(`发布成功,页面已跳转: ${page.url()}`);
21307
+ } catch {
21308
+ task.logger.warn("等待页面跳转超时,可能发布失败或网络慢,继续关闭页面");
21309
+ }
21310
+ await page.close();
21311
+ return (0, share_namespaceObject.success)(videoId, "发布成功");
21312
+ } catch (error) {
21313
+ let errorMsg = error instanceof Error ? error.message : String(error);
21314
+ if (errorMsg.includes("context or browser has been closed")) errorMsg = "浏览器上下文已被关闭";
21315
+ task.logger.error(`微信视频号视频发布失败: ${errorMsg}`);
21316
+ return (0, share_namespaceObject.response)(414, `微信视频号视频发布失败: ${errorMsg}`, "");
21317
+ }
21318
+ };
21319
+ const ShipinhaoPublishVideoParamsSchema = ActionCommonParamsSchema.extend({
21320
+ videoPath: schemas_string().min(1),
21321
+ videoMetadata: schemas_object({
21322
+ duration: schemas_number().positive(),
21323
+ width: schemas_number().int().positive(),
21324
+ height: schemas_number().int().positive(),
21325
+ fileSize: schemas_number().int().positive(),
21326
+ path: schemas_string().min(1).optional(),
21327
+ fileName: schemas_string().min(1)
21328
+ }),
21329
+ coverPath: schemas_string().min(1),
21330
+ verticalCoverPath: schemas_string().min(1).optional(),
21331
+ description: schemas_string(),
21332
+ title: schemas_string().optional(),
21333
+ scheduledTime: schemas_number().int().positive().optional(),
21334
+ isImmediatelyPublish: schemas_boolean().optional(),
21335
+ topics: schemas_array(schemas_string()).optional(),
21336
+ mentionedUsers: schemas_array(schemas_object({
21337
+ nickname: schemas_string()
21338
+ })).optional(),
21339
+ collection: schemas_object({
21340
+ collectionId: schemas_string(),
21341
+ collectionName: schemas_string()
21342
+ }).optional(),
21343
+ event: schemas_object({
21344
+ eventTopicId: schemas_string(),
21345
+ eventName: schemas_string(),
21346
+ eventCreatorNickname: schemas_string().optional()
21347
+ }).optional(),
21348
+ link: schemas_object({
21349
+ link: schemas_string(),
21350
+ title: schemas_string(),
21351
+ urlType: schemas_number().int().default(1)
21352
+ }).optional(),
21353
+ tagInfo: looseObject({
21354
+ tagType: schemas_number().int()
21355
+ }).optional(),
21356
+ originalFlag: union([
21357
+ literal(0),
21358
+ literal(1)
21359
+ ]).optional(),
21360
+ postWithMemberZoneLink: union([
21361
+ literal(0),
21362
+ literal(1)
21363
+ ]).optional(),
21364
+ location: schemas_object({
21365
+ latitude: schemas_number(),
21366
+ longitude: schemas_number(),
21367
+ city: schemas_string(),
21368
+ poiName: schemas_string().optional(),
21369
+ address: schemas_string().optional(),
21370
+ poiClassifyId: schemas_string().optional()
21371
+ }).optional()
21372
+ });
21373
+ const shipinhaoPublishVideo = async (task, params)=>{
21374
+ task.logger.info(`[shipinhaoPublishVideo] actionType: ${params.actionType}`);
21375
+ if ("rpa" === params.actionType) return shipinhaoPublishVideo_rpa_rpaAction(task, params);
21376
+ if ("mockApi" === params.actionType) return shipinhaoPublishVideo_mock_mockAction(task, params);
21377
+ return executeAction(shipinhaoPublishVideo_mock_mockAction, shipinhaoPublishVideo_rpa_rpaAction)(task, params);
21378
+ };
21379
+ const ShipinhaoSendMsgParamsSchema = ActionCommonParamsSchema.extend({
21380
+ toUsername: schemas_string().min(1, "接收者用户名不能为空"),
21381
+ sessionId: schemas_string().min(1, "会话ID不能为空"),
21382
+ msgType: schemas_enum([
21383
+ "TEXT",
21384
+ "IMAGE"
21385
+ ], {
21386
+ message: "消息类型必须是 TEXT 或 IMAGE"
21387
+ }),
21388
+ content: schemas_string().optional(),
21389
+ imageInfo: schemas_object({
21390
+ pathOrUrl: schemas_string().min(1, "图片路径或URL不能为空")
21391
+ }).optional()
21392
+ });
21393
+ const shipinhaoSendMsg_CHUNK_SIZE = 524288;
21394
+ async function shipinhaoSendMsg_getUserInfo(cookieStr, http) {
21395
+ const url = `https://channels.weixin.qq.com/cgi-bin/mmfinderassistant-bin/auth/auth_data?_rid=${rid()}`;
21396
+ const headers = {
21397
+ referer: "https://channels.weixin.qq.com/micro/interaction/private_msg",
21398
+ cookie: cookieStr,
21399
+ Origin: "https://channels.weixin.qq.com"
21400
+ };
21401
+ return await http.api({
21402
+ method: "get",
21403
+ url,
21404
+ headers
21405
+ }, {
21406
+ retries: 3,
21407
+ retryDelay: 1000,
21408
+ timeout: 10000
21409
+ });
21410
+ }
21411
+ const shipinhaoSendMsg = async (_task, params)=>{
21412
+ if (!params.sessionId) return (0, share_namespaceObject.response)(414, "sessionId 不能为空", void 0);
21413
+ if (!params.toUsername) return (0, share_namespaceObject.response)(414, "接收者用户名不能为空", void 0);
21414
+ if (!params.msgType) return (0, share_namespaceObject.response)(414, "消息类型不能为空", void 0);
21415
+ if (![
21416
+ "TEXT",
21417
+ "IMAGE"
21418
+ ].includes(params.msgType)) return (0, share_namespaceObject.response)(414, "消息类型必须是 TEXT 或 IMAGE", void 0);
21419
+ if ("TEXT" === params.msgType) {
21420
+ if (!params.content || "" === params.content.trim()) return (0, share_namespaceObject.response)(414, "消息内容不能为空", void 0);
21421
+ }
21422
+ if ("IMAGE" === params.msgType) {
21423
+ if (!params.imageInfo?.pathOrUrl) return (0, share_namespaceObject.response)(414, "图片路径或URL不能为空", void 0);
21424
+ }
21425
+ if (!params.extraParam) return (0, share_namespaceObject.response)(414, "缺少 extraParam 参数", void 0);
21426
+ if (!params.extraParam.fingerPrintDeviceId || !params.extraParam.aId || !params.extraParam.uin) return (0, share_namespaceObject.response)(414, "fingerPrintDeviceId、aId 和 uin 不能为空", void 0);
21427
+ const cookieStr = params.cookies.map((it)=>`${it.name}=${it.value}`).join(";");
21428
+ const headers = {
21429
+ cookie: cookieStr,
21430
+ referer: "https://channels.weixin.qq.com/micro/interaction/private_msg",
21431
+ origin: "https://channels.weixin.qq.com",
21432
+ "content-type": "application/json",
21433
+ "finger-print-device-id": params.extraParam.fingerPrintDeviceId,
21434
+ "x-wechat-uin": params.extraParam.uin
21435
+ };
21436
+ const http = new Http({
21437
+ headers
21438
+ });
21439
+ const urlParams = new URLSearchParams({
21440
+ _aid: params.extraParam.aId,
21441
+ _rid: rid(),
21442
+ _pageUrl: "https://channels.weixin.qq.com/micro/interaction/private_msg"
21443
+ }).toString();
21444
+ const generateCliMsgId = ()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (s)=>{
21445
+ const t = 16 * Math.random() | 0;
21446
+ return ("x" === s ? t : 3 & t | 8).toString(16);
21447
+ });
21448
+ let fromUsername = params.extraParam.finderUserName;
21449
+ if (!fromUsername) {
21450
+ _task.logger.info("未提供 finderUserName,尝试获取用户信息");
21451
+ const userInfoRes = await shipinhaoSendMsg_getUserInfo(cookieStr, http);
21452
+ if (!userInfoRes.data?.finderUser?.finderUsername) return (0, share_namespaceObject.response)(userInfoRes.errCode || -1, userInfoRes.errMsg || "获取用户信息失败", {});
21453
+ fromUsername = userInfoRes.data.finderUser.finderUsername;
21454
+ _task.logger.info(`获取到用户名: ${fromUsername}`);
21455
+ }
21456
+ let imgMsg;
21457
+ if ("IMAGE" === params.msgType) {
21458
+ let imageBuffer;
21459
+ const imagePath = params.imageInfo.pathOrUrl;
21460
+ try {
21461
+ if (imagePath.startsWith("http://") || imagePath.startsWith("https://")) {
21462
+ const resp = await external_axios_default().get(imagePath, {
21463
+ responseType: "arraybuffer"
21464
+ });
21465
+ imageBuffer = Buffer.from(resp.data);
21466
+ } else {
21467
+ const filePath = imagePath.startsWith("file://") ? imagePath.slice(7) : imagePath;
21468
+ imageBuffer = Buffer.from(await external_node_fs_default().promises.readFile(filePath));
21469
+ }
21470
+ } catch (err) {
21471
+ _task.logger.error(`读取图片失败: ${err instanceof Error ? err.message : String(err)}`);
21472
+ return (0, share_namespaceObject.response)(414, USER_MESSAGE.IMAGE_UPLOAD_FAILED, void 0);
21473
+ }
21474
+ const md5 = (0, external_node_crypto_namespaceObject.createHash)("md5").update(imageBuffer).digest("hex");
21475
+ const timestamp = Date.now().toString();
21476
+ const totalChunks = Math.ceil(imageBuffer.length / shipinhaoSendMsg_CHUNK_SIZE);
21477
+ console.log(`分片上传md5${md5}`);
21478
+ let lastRes;
21479
+ for(let i = 0; i < totalChunks; i++){
21480
+ const chunkBuffer = imageBuffer.slice(i * shipinhaoSendMsg_CHUNK_SIZE, (i + 1) * shipinhaoSendMsg_CHUNK_SIZE);
21481
+ const requestData = {
21482
+ content: `data:application/octet-stream;base64,${chunkBuffer.toString("base64")}`,
21483
+ chunk: i,
21484
+ chunks: totalChunks,
21485
+ fromUsername,
21486
+ toUsername: params.toUsername,
21487
+ aesKey: "U2FsdGVkX18cwrWR73LMGhBcmAX8xoNTgbmgkZBYkEs=",
21488
+ mediaSize: imageBuffer.length,
21489
+ mediaType: 3,
21490
+ md5,
21491
+ timestamp,
21492
+ _log_finder_uin: "",
21493
+ _log_finder_id: params.extraParam.finderUserName || "",
21494
+ rawKeyBuff: null,
21495
+ pluginSessionId: null,
21496
+ scene: 7,
21497
+ reqScene: 7
21498
+ };
21499
+ lastRes = await http.api({
21500
+ method: "post",
21501
+ url: `https://channels.weixin.qq.com/micro/interaction/cgi-bin/mmfinderassistant-bin/private-msg/upload-media-info?${urlParams}`,
21502
+ data: requestData
21503
+ });
21504
+ console.log(`分片上传 ${i + 1}/${totalChunks} 响应:`, lastRes);
21505
+ if (lastRes?.errCode !== 0 && i < totalChunks - 1) return (0, share_namespaceObject.response)(414, lastRes?.errMsg || `第 ${i + 1}/${totalChunks} 分片上传失败`, void 0);
21506
+ }
21507
+ if (lastRes?.errCode !== 0) return (0, share_namespaceObject.response)(414, lastRes?.errMsg || "上传图片失败", void 0);
21508
+ const uploadedImgMsg = lastRes.data?.imgMsg;
21509
+ imgMsg = {
21510
+ aeskey: uploadedImgMsg.aesKey ?? uploadedImgMsg.aeskey,
21511
+ url: uploadedImgMsg.cdnUrl ?? uploadedImgMsg.url,
21512
+ hdSize: uploadedImgMsg.hdSize ?? uploadedImgMsg.size,
21513
+ midSize: uploadedImgMsg.midSize ?? uploadedImgMsg.size,
21514
+ thumbSize: uploadedImgMsg.thumbSize ?? uploadedImgMsg.size,
21515
+ thumbHeight: uploadedImgMsg.thumbHeight ?? uploadedImgMsg.height,
21516
+ thumbWidth: uploadedImgMsg.thumbWidth ?? uploadedImgMsg.width,
21517
+ md5: uploadedImgMsg.md5
21518
+ };
21519
+ }
21520
+ console.log("发送私信请求参数1111", {
21521
+ sessionId: params.sessionId,
21522
+ fromUsername
21523
+ });
21524
+ const sendRes = await http.api({
21525
+ method: "post",
21526
+ url: `https://channels.weixin.qq.com/micro/interaction/cgi-bin/mmfinderassistant-bin/private-msg/send-private-msg?${urlParams}`,
21527
+ data: {
21528
+ timestamp: Date.now().toString(),
21529
+ _log_finder_uin: "",
21530
+ _log_finder_id: params.extraParam.finderUserName || "",
21531
+ rawKeyBuff: null,
21532
+ pluginSessionId: null,
21533
+ scene: 7,
21534
+ reqScene: 7,
21535
+ msgPack: {
21536
+ sessionId: params.sessionId,
21537
+ fromUsername,
21538
+ toUsername: params.toUsername,
21539
+ cliMsgId: generateCliMsgId(),
21540
+ msgType: "TEXT" === params.msgType ? 1 : 3,
21541
+ imgMsg: "IMAGE" === params.msgType ? imgMsg : void 0,
21542
+ textMsg: "TEXT" === params.msgType ? {
21543
+ content: params.content
21544
+ } : void 0
21545
+ }
21546
+ }
21547
+ });
21548
+ console.log("发送私信响应:", sendRes);
21549
+ const isSuccess = sendRes?.errCode === 0;
21550
+ return (0, share_namespaceObject.response)(isSuccess ? 0 : 414, sendRes?.errMsg || "发送图片私信失败", sendRes.data);
21551
+ };
21552
+ const toutiaoLogin_rpa_rpaAction = async (task, _params)=>{
21553
+ const reporter = task.reportService?.reportLoginStatus ?? (()=>Promise.resolve());
21554
+ let page;
21555
+ let isSelfClosing = false;
21556
+ let handleBrowserDisconnected;
21557
+ const cleanup = async ()=>{
21558
+ if (handleBrowserDisconnected) task._steelBrowser?.off("disconnected", handleBrowserDisconnected);
21559
+ if (page && !page.isClosed()) await page.close().catch(()=>{});
21560
+ };
21561
+ try {
21562
+ page = await task.createPage({
21563
+ url: "https://mp.toutiao.com/auth/page/login"
21564
+ });
21565
+ if (!task._session?.id) throw new Error("Session ID 不存在");
21566
+ handleBrowserDisconnected = ()=>{
21567
+ if (task.debug && isSelfClosing) task.logger.info("执行结束,关闭浏览器!");
21568
+ else task.logger.info("浏览器被手动释放或意外关闭!");
21569
+ };
21570
+ task._steelBrowser?.on("disconnected", handleBrowserDisconnected);
21571
+ } catch (e) {
21572
+ return {
21573
+ code: 414,
21574
+ message: `浏览器启动失败: ${e}`,
21575
+ data: {}
21576
+ };
21577
+ }
21578
+ const pageInfo = await task._client?.sessions.liveDetails(task._session.id);
21579
+ const pageId = pageInfo?.pages[0].id ?? "";
21580
+ const baseHost = task._session.websocketUrl?.replace(/^wss?:\/\//, "") ?? "";
21581
+ const connectAddress = new URLSearchParams({
21582
+ baseHost,
21583
+ pageId
21584
+ }).toString();
21585
+ task.reportService?.settingSessionID?.(task._session?.id || "");
21586
+ await page.route(/\/welcome.*\.(png|mp4)$/i, (route)=>route.abort());
21587
+ await reporter(0, "浏览器启动成功,请使用头条号App扫码登录……", {
21588
+ connectAddress
21589
+ });
21590
+ let userInfo = {
21591
+ uniqueId: "",
21592
+ avatar: "",
21593
+ name: ""
21594
+ };
21595
+ try {
19928
21596
  const handleUserInfo = async (resp)=>{
19929
21597
  if (resp.url().includes("/mp/agw/creator_center/user_info")) try {
19930
21598
  const jsonUserInfo = await resp.json();
@@ -20262,6 +21930,13 @@ var __webpack_exports__ = {};
20262
21930
  const uploadImages = async (images)=>await Promise.all(images.map(async (url)=>{
20263
21931
  const fileName = (0, share_namespaceObject.getFilenameFromUrl)(url);
20264
21932
  const image = await (0, share_namespaceObject.downloadImage)(url, external_node_path_default().join(tmpCachePath, fileName));
21933
+ const stats = external_node_fs_default().statSync(image);
21934
+ const maxSize = 20971520;
21935
+ if (stats.size > maxSize) throw {
21936
+ code: 414,
21937
+ message: "头条号平台:单张图片不得超过 20MB",
21938
+ data: ""
21939
+ };
20265
21940
  const formData = new (external_form_data_default())();
20266
21941
  formData.append("image", external_node_fs_default().createReadStream(image));
20267
21942
  const response = await http.api({
@@ -23545,6 +25220,12 @@ var __webpack_exports__ = {};
23545
25220
  const fileName = (0, share_namespaceObject.getFilenameFromUrl)(url);
23546
25221
  const localUrl = await (0, share_namespaceObject.downloadImage)(url, external_node_path_default().join(tmpCachePath, fileName));
23547
25222
  const fileBuffer = external_node_fs_default().readFileSync(localUrl);
25223
+ const maxSize = 33554432;
25224
+ if (fileBuffer.byteLength > maxSize) throw {
25225
+ code: 414,
25226
+ message: "小红书平台:单张图片不得超过 32MB",
25227
+ data: ""
25228
+ };
23548
25229
  let width = 0;
23549
25230
  let height = 0;
23550
25231
  try {
@@ -25729,6 +27410,9 @@ var __webpack_exports__ = {};
25729
27410
  shipinhaoPublish(params) {
25730
27411
  return this.bindTask(shipinhaoPublish, params);
25731
27412
  }
27413
+ shipinhaoPublishVideo(params) {
27414
+ return this.bindTask(shipinhaoPublishVideo, params);
27415
+ }
25732
27416
  douyinGetTopics(params) {
25733
27417
  return this.bindTask(douyinGetTopics, params);
25734
27418
  }
@@ -25789,4 +27473,4 @@ if (__webpack_exports__.__esModule) Object.defineProperty(__webpack_export_targe
25789
27473
  });
25790
27474
 
25791
27475
  //# sourceMappingURL=index.js.map
25792
- //# debugId=3b831ac8-2f97-5984-b6b4-868d0748d2c6
27476
+ //# debugId=959450cb-879c-5526-aedb-26ef8ba0e7a8