@iflyrpa/actions 4.0.9-beta.3 → 4.1.0-beta.5

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,3 +1,5 @@
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]="1de33b63-4038-5f51-813c-0899b138a5ca")}catch(e){}}();
1
3
  var __webpack_modules__ = {
2
4
  "./src/utils/XhsXsCommonEnc.js": function(module) {
3
5
  var encrypt_lookup = [
@@ -4364,6 +4366,7 @@ var __webpack_exports__ = {};
4364
4366
  SessionCheckResultSchema: ()=>SessionCheckResultSchema,
4365
4367
  DouyinGetCommentReplyListParamsSchema: ()=>DouyinGetCommentReplyListParamsSchema,
4366
4368
  DouyinCreateCommentReplyParamsSchema: ()=>DouyinCreateCommentReplyParamsSchema,
4369
+ ShipinhaoPublishVideoParamsSchema: ()=>ShipinhaoPublishVideoParamsSchema,
4367
4370
  DouyinGetHotParamsSchema: ()=>DouyinGetHotParamsSchema,
4368
4371
  DouyinGetMusicParamsSchema: ()=>DouyinGetMusicParamsSchema,
4369
4372
  FetchArticlesDataSchema: ()=>FetchArticlesDataSchema,
@@ -4400,7 +4403,7 @@ var __webpack_exports__ = {};
4400
4403
  });
4401
4404
  const package_json_namespaceObject = require("@iflyrpa/share/package.json");
4402
4405
  var package_json_default = /*#__PURE__*/ __webpack_require__.n(package_json_namespaceObject);
4403
- var package_namespaceObject = JSON.parse('{"i8":"4.0.9-beta.3"}');
4406
+ var package_namespaceObject = JSON.parse('{"i8":"4.1.0-beta.5"}');
4404
4407
  const share_namespaceObject = require("@iflyrpa/share");
4405
4408
  const external_node_fs_namespaceObject = require("node:fs");
4406
4409
  var external_node_fs_default = /*#__PURE__*/ __webpack_require__.n(external_node_fs_namespaceObject);
@@ -4869,22 +4872,32 @@ var __webpack_exports__ = {};
4869
4872
  const retries = options?.retries ?? 0;
4870
4873
  const retryDelay = options?.retryDelay ?? 500;
4871
4874
  const reqTimeout = options?.timeout ?? 30000;
4875
+ const externalSignal = options?.signal;
4872
4876
  let agent;
4873
4877
  const sessionRt = async (Rtimes)=>{
4874
4878
  try {
4875
4879
  this.proxyInfo = agent ? `${agent.ip}:${agent.port}` : void 0;
4876
4880
  const controller = new AbortController();
4877
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
+ }
4878
4889
  const response = await this.apiClient({
4879
4890
  ...config,
4880
4891
  timeout: reqTimeout,
4881
4892
  signal: controller.signal,
4893
+ onUploadProgress: options?.onUploadProgress,
4882
4894
  ...agent ? {
4883
4895
  httpAgent: agent.agent,
4884
4896
  httpsAgent: agent.agent
4885
4897
  } : {}
4886
4898
  }).finally(()=>{
4887
4899
  clearTimeout(timeoutId);
4900
+ externalSignal?.removeEventListener("abort", forwardAbort);
4888
4901
  });
4889
4902
  return response.data;
4890
4903
  } catch (error) {
@@ -6001,7 +6014,7 @@ var __webpack_exports__ = {};
6001
6014
  const xid = /^[0-9a-vA-V]{20}$/;
6002
6015
  const ksuid = /^[A-Za-z0-9]{27}$/;
6003
6016
  const nanoid = /^[a-zA-Z0-9_-]{21}$/;
6004
- 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)?)?)$/;
6005
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})$/;
6006
6019
  const regexes_uuid = (version)=>{
6007
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)$/;
@@ -6687,7 +6700,7 @@ var __webpack_exports__ = {};
6687
6700
  $ZodStringFormat.init(inst, def);
6688
6701
  });
6689
6702
  const $ZodISODuration = /*@__PURE__*/ $constructor("$ZodISODuration", (inst, def)=>{
6690
- def.pattern ?? (def.pattern = duration);
6703
+ def.pattern ?? (def.pattern = regexes_duration);
6691
6704
  $ZodStringFormat.init(inst, def);
6692
6705
  });
6693
6706
  const $ZodIPv4 = /*@__PURE__*/ $constructor("$ZodIPv4", (inst, def)=>{
@@ -9323,6 +9336,13 @@ var __webpack_exports__ = {};
9323
9336
  data: ""
9324
9337
  };
9325
9338
  const image = await (0, share_namespaceObject.downloadImage)(url, external_node_path_default().join(tmpCachePath, fileName));
9339
+ const stats = external_node_fs_default().statSync(image);
9340
+ const maxSize = 5242880;
9341
+ if (stats.size > maxSize) throw {
9342
+ code: 414,
9343
+ message: "百家号平台:单张图片不得超过 5MB",
9344
+ data: ""
9345
+ };
9326
9346
  const formData = new (external_form_data_default())();
9327
9347
  formData.append("org_file_name", fileName);
9328
9348
  formData.append("type", "image");
@@ -13460,6 +13480,11 @@ var __webpack_exports__ = {};
13460
13480
  }
13461
13481
  async getImageInfo(localPath) {
13462
13482
  const stats = external_node_fs_default().statSync(localPath);
13483
+ const maxSize = 52428800;
13484
+ if (stats.size > maxSize) {
13485
+ external_node_path_default().basename(localPath);
13486
+ throw new Error("抖音平台:单张图片不得超过 50MB");
13487
+ }
13463
13488
  let width = 1080;
13464
13489
  let height = 1920;
13465
13490
  try {
@@ -19706,6 +19731,1086 @@ var __webpack_exports__ = {};
19706
19731
  if ("server" === params.actionType) return rpa_server_rpaAction_Server(task, params);
19707
19732
  return executeAction(shipinhaoPublish_mock_mockAction, rpa_server_rpaAction_Server)(task, params);
19708
19733
  };
19734
+ function auth_getTimeStamp(length) {
19735
+ return Date.now().toString().substring(0, length);
19736
+ }
19737
+ async function auth_getUserInfo(cookies, http) {
19738
+ return http.api({
19739
+ method: "post",
19740
+ url: "https://channels.weixin.qq.com/cgi-bin/mmfinderassistant-bin/auth/auth_data",
19741
+ data: {
19742
+ timestamp: auth_getTimeStamp(13),
19743
+ _log_finder_uin: "",
19744
+ _log_finder_id: "",
19745
+ rawKeyBuff: null,
19746
+ pluginSessionId: null,
19747
+ scene: 7,
19748
+ reqScene: 7
19749
+ },
19750
+ headers: {
19751
+ cookie: cookies,
19752
+ referer: "https://channels.weixin.qq.com",
19753
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
19754
+ },
19755
+ defaultErrorMsg: "获取用户信息失败"
19756
+ });
19757
+ }
19758
+ async function auth_getUploadAuthKey(cookies, finderUsername, http) {
19759
+ return http.api({
19760
+ method: "post",
19761
+ url: "https://channels.weixin.qq.com/cgi-bin/mmfinderassistant-bin/helper/helper_upload_params",
19762
+ data: {
19763
+ timestamp: auth_getTimeStamp(13),
19764
+ _log_finder_id: finderUsername,
19765
+ rawKeyBuff: null
19766
+ },
19767
+ headers: {
19768
+ cookie: cookies,
19769
+ referer: "https://channels.weixin.qq.com",
19770
+ Accept: "application/json, text/plain, */*",
19771
+ "Content-Type": "application/json",
19772
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
19773
+ },
19774
+ defaultErrorMsg: "获取上传认证密钥失败"
19775
+ });
19776
+ }
19777
+ class ShipinhaoAuthError extends Error {
19778
+ constructor(message, errCode){
19779
+ super(message), this.errCode = errCode;
19780
+ this.name = "ShipinhaoAuthError";
19781
+ }
19782
+ }
19783
+ async function getShipinhaoUploadAuth(cookies, http) {
19784
+ const userInfo = await auth_getUserInfo(cookies, http);
19785
+ if (0 !== userInfo.errCode || !userInfo.data?.finderUser) {
19786
+ const isLoginExpired = 300333 === userInfo.errCode || 300334 === userInfo.errCode;
19787
+ throw new ShipinhaoAuthError(isLoginExpired ? "登录失效" : userInfo.errMsg || "获取用户信息失败", userInfo.errCode || 500);
19788
+ }
19789
+ const finderUsername = userInfo.data.finderUser.finderUsername;
19790
+ const authKeyResponse = await auth_getUploadAuthKey(cookies, finderUsername, http);
19791
+ if (0 !== authKeyResponse.errCode || !authKeyResponse.data?.authKey) throw new ShipinhaoAuthError(`获取上传认证参数失败: ${authKeyResponse.errMsg}`, authKeyResponse.errCode || 500);
19792
+ const uin = authKeyResponse.data.uin;
19793
+ if (!uin) throw new ShipinhaoAuthError("获取用户 uin 失败", 500);
19794
+ const videoFileType = authKeyResponse.data.videoFileType || 20302;
19795
+ const pictureFileType = authKeyResponse.data.pictureFileType || 20304;
19796
+ return {
19797
+ uin,
19798
+ authKey: authKeyResponse.data.authKey,
19799
+ finderUsername,
19800
+ videoFileType,
19801
+ pictureFileType
19802
+ };
19803
+ }
19804
+ const CHUNK_SIZE = 8388608;
19805
+ async function uploader_uploadFile(opts) {
19806
+ const { filePath, fileType, uin, authKey, http, logger } = opts;
19807
+ const stat = external_node_fs_default().statSync(filePath);
19808
+ const fileSize = stat.size;
19809
+ const fileName = filePath.split(/[\\/]/).pop() || "file";
19810
+ logger?.info(`开始上传: ${fileName} (${fileSize} B, filetype=${fileType})`);
19811
+ const fileMd5 = await computeFileMd5(filePath);
19812
+ const taskId = generateTaskId(fileName, fileSize, fileMd5);
19813
+ const baseUrl = "https://finderassistancea.video.qq.com";
19814
+ const headers = {
19815
+ Authorization: authKey
19816
+ };
19817
+ const xArgs = `apptype=251&filetype=${fileType}&weixinnum=${uin}&filekey=${encodeURIComponent(fileName)}&filesize=${fileSize}&taskid=${taskId}&scene=2`;
19818
+ const chunkCount = Math.ceil(fileSize / CHUNK_SIZE);
19819
+ const blockPartLength = [];
19820
+ for(let i = 0; i < chunkCount; i++)blockPartLength.push(Math.min((i + 1) * CHUNK_SIZE, fileSize));
19821
+ logger?.info(`申请 UploadID: ${chunkCount} 片`);
19822
+ const applyRes = await http.api({
19823
+ method: "PUT",
19824
+ url: `${baseUrl}/applyuploaddfs`,
19825
+ headers: {
19826
+ ...headers,
19827
+ "X-Arguments": xArgs
19828
+ },
19829
+ data: {
19830
+ BlockSum: chunkCount,
19831
+ BlockPartLength: blockPartLength
19832
+ }
19833
+ });
19834
+ if (!applyRes.UploadID && !applyRes.ListPartsResult) throw new Error("申请 UploadID 失败: " + JSON.stringify(applyRes));
19835
+ let uploadId = applyRes.UploadID;
19836
+ const uploadedParts = new Set();
19837
+ if (applyRes.ListPartsResult) {
19838
+ logger?.info("检测到已上传分片,执行续传");
19839
+ const parts = Array.isArray(applyRes.ListPartsResult.Part) ? applyRes.ListPartsResult.Part : applyRes.ListPartsResult.Part ? [
19840
+ applyRes.ListPartsResult.Part
19841
+ ] : [];
19842
+ for (const p of parts)uploadedParts.add(p.PartNumber);
19843
+ const retryRes = await http.api({
19844
+ method: "PUT",
19845
+ url: `${baseUrl}/applyuploaddfs`,
19846
+ headers: {
19847
+ ...headers,
19848
+ "X-Arguments": xArgs
19849
+ },
19850
+ data: {
19851
+ BlockSum: chunkCount,
19852
+ BlockPartLength: blockPartLength
19853
+ }
19854
+ });
19855
+ uploadId = retryRes.UploadID;
19856
+ if (!uploadId) throw new Error("续传获取 UploadID 失败");
19857
+ }
19858
+ const partInfo = [];
19859
+ const fd = external_node_fs_default().openSync(filePath, "r");
19860
+ try {
19861
+ for(let i = 0; i < chunkCount; i++){
19862
+ const partNumber = i + 1;
19863
+ if (uploadedParts.has(partNumber)) {
19864
+ const existing = applyRes.ListPartsResult.Part.find((p)=>p.PartNumber === partNumber);
19865
+ if (existing) {
19866
+ partInfo.push({
19867
+ PartNumber: partNumber,
19868
+ ETag: existing.ETag
19869
+ });
19870
+ logger?.info(`分片 ${partNumber}/${chunkCount} 已存在,跳过`);
19871
+ continue;
19872
+ }
19873
+ }
19874
+ const start = i * CHUNK_SIZE;
19875
+ const end = Math.min(start + CHUNK_SIZE, fileSize);
19876
+ const chunkSize = end - start;
19877
+ const chunk = Buffer.alloc(chunkSize);
19878
+ external_node_fs_default().readSync(fd, chunk, 0, chunkSize, start);
19879
+ const chunkMd5 = external_node_crypto_default().createHash("md5").update(chunk).digest("hex");
19880
+ await http.api({
19881
+ method: "PUT",
19882
+ url: `${baseUrl}/uploadpartdfs?PartNumber=${partNumber}&UploadID=${encodeURIComponent(uploadId)}`,
19883
+ headers: {
19884
+ ...headers,
19885
+ "X-Arguments": xArgs.replace(/scene=2/, "scene=0"),
19886
+ "Content-MD5": chunkMd5
19887
+ },
19888
+ data: chunk
19889
+ });
19890
+ partInfo.push({
19891
+ PartNumber: partNumber,
19892
+ ETag: `"${chunkMd5}"`
19893
+ });
19894
+ logger?.info(`分片 ${partNumber}/${chunkCount} 完成 (${chunkSize} B)`);
19895
+ }
19896
+ } finally{
19897
+ external_node_fs_default().closeSync(fd);
19898
+ }
19899
+ logger?.info("合并分片...");
19900
+ const completeRes = await http.api({
19901
+ method: "POST",
19902
+ url: `${baseUrl}/completepartuploaddfs?UploadID=${encodeURIComponent(uploadId)}`,
19903
+ headers: {
19904
+ ...headers,
19905
+ "X-Arguments": xArgs
19906
+ },
19907
+ data: {
19908
+ TransFlag: "0_0",
19909
+ PartInfo: partInfo
19910
+ }
19911
+ });
19912
+ if (!completeRes.DownloadURL) throw new Error("合并分片失败: " + JSON.stringify(completeRes));
19913
+ logger?.info(`上传成功: ${completeRes.DownloadURL.slice(0, 80)}...`);
19914
+ return {
19915
+ downloadUrl: completeRes.DownloadURL,
19916
+ md5: fileMd5,
19917
+ fileSize
19918
+ };
19919
+ }
19920
+ async function computeFileMd5(filePath) {
19921
+ return new Promise((resolve, reject)=>{
19922
+ const hash = external_node_crypto_default().createHash("md5");
19923
+ const stream = external_node_fs_default().createReadStream(filePath);
19924
+ stream.on("data", (chunk)=>hash.update(chunk));
19925
+ stream.on("end", ()=>resolve(hash.digest("hex")));
19926
+ stream.on("error", reject);
19927
+ });
19928
+ }
19929
+ function generateTaskId(fileName, fileSize, fileMd5) {
19930
+ const input = `${fileName}-${fileSize}-${fileMd5}`;
19931
+ return external_node_crypto_default().createHash("md5").update(input).digest("hex").slice(0, 32);
19932
+ }
19933
+ function parseVideoMeta(filePath) {
19934
+ let buf;
19935
+ try {
19936
+ buf = external_node_fs_default().readFileSync(filePath);
19937
+ } catch {
19938
+ return null;
19939
+ }
19940
+ let movie = null;
19941
+ const tracks = [];
19942
+ function walk(start, end) {
19943
+ let off = start;
19944
+ while(off + 8 <= end){
19945
+ let size = buf.readUInt32BE(off);
19946
+ const type = buf.toString("latin1", off + 4, off + 8);
19947
+ let headerSize = 8;
19948
+ if (1 === size) {
19949
+ if (off + 16 > end) break;
19950
+ const hi = buf.readUInt32BE(off + 8);
19951
+ const lo = buf.readUInt32BE(off + 12);
19952
+ size = hi * 2 ** 32 + lo;
19953
+ headerSize = 16;
19954
+ } else if (0 === size) size = end - off;
19955
+ if (size < headerSize || off + size > end) break;
19956
+ const bodyStart = off + headerSize;
19957
+ const bodyEnd = off + size;
19958
+ switch(type){
19959
+ case "moov":
19960
+ case "trak":
19961
+ case "mdia":
19962
+ case "minf":
19963
+ case "stbl":
19964
+ walk(bodyStart, bodyEnd);
19965
+ break;
19966
+ case "mvhd":
19967
+ movie = parseMvhd(buf, bodyStart, bodyEnd);
19968
+ break;
19969
+ case "tkhd":
19970
+ tracks.push({
19971
+ ...parseTkhd(buf, bodyStart, bodyEnd),
19972
+ handler: null,
19973
+ codec: null
19974
+ });
19975
+ break;
19976
+ case "hdlr":
19977
+ if (bodyEnd - bodyStart >= 12) {
19978
+ const handler = buf.toString("latin1", bodyStart + 8, bodyStart + 12);
19979
+ if (tracks.length) tracks[tracks.length - 1].handler = handler;
19980
+ }
19981
+ break;
19982
+ case "stsd":
19983
+ {
19984
+ const codec = parseStsdCodec(buf, bodyStart, bodyEnd);
19985
+ if (codec && tracks.length) tracks[tracks.length - 1].codec = codec;
19986
+ break;
19987
+ }
19988
+ }
19989
+ off += size;
19990
+ }
19991
+ }
19992
+ walk(0, buf.length);
19993
+ const video = tracks.find((t)=>"vide" === t.handler) || tracks.find((t)=>t.width > 0 && t.height > 0);
19994
+ if (!movie || !video) return null;
19995
+ const movieData = movie;
19996
+ let { width, height } = video;
19997
+ if (90 === video.rotation || 270 === video.rotation) [width, height] = [
19998
+ height,
19999
+ width
20000
+ ];
20001
+ return {
20002
+ width: Math.round(width),
20003
+ height: Math.round(height),
20004
+ duration: movieData.timescale ? movieData.duration / movieData.timescale : 0,
20005
+ rotation: video.rotation,
20006
+ fileSize: buf.length,
20007
+ codec: video.codec
20008
+ };
20009
+ }
20010
+ function parseStsdCodec(buf, start, end) {
20011
+ if (start + 16 > end) return null;
20012
+ return buf.toString("latin1", start + 12, start + 16).toLowerCase();
20013
+ }
20014
+ function parseMvhd(buf, start, end) {
20015
+ const version = buf.readUInt8(start);
20016
+ if (1 === version) {
20017
+ if (start + 28 > end) return null;
20018
+ const timescale = buf.readUInt32BE(start + 20);
20019
+ const hi = buf.readUInt32BE(start + 24);
20020
+ const lo = buf.readUInt32BE(start + 28);
20021
+ return {
20022
+ timescale,
20023
+ duration: hi * 2 ** 32 + lo
20024
+ };
20025
+ }
20026
+ if (start + 20 > end) return null;
20027
+ return {
20028
+ timescale: buf.readUInt32BE(start + 12),
20029
+ duration: buf.readUInt32BE(start + 16)
20030
+ };
20031
+ }
20032
+ function parseTkhd(buf, start, end) {
20033
+ const version = buf.readUInt8(start);
20034
+ const afterDuration = 1 === version ? 36 : 24;
20035
+ const matrixOff = start + afterDuration + 16;
20036
+ const whOff = matrixOff + 36;
20037
+ if (whOff + 8 > end) return {
20038
+ width: 0,
20039
+ height: 0,
20040
+ rotation: 0
20041
+ };
20042
+ const width = buf.readUInt32BE(whOff) / 65536;
20043
+ const height = buf.readUInt32BE(whOff + 4) / 65536;
20044
+ const a = buf.readInt32BE(matrixOff) / 65536;
20045
+ const b = buf.readInt32BE(matrixOff + 4) / 65536;
20046
+ let rotation = 0;
20047
+ if (Math.abs(a) < 0.01 && Math.abs(b - 1) < 0.01) rotation = 90;
20048
+ else if (Math.abs(a + 1) < 0.01 && Math.abs(b) < 0.01) rotation = 180;
20049
+ else if (Math.abs(a) < 0.01 && Math.abs(b + 1) < 0.01) rotation = 270;
20050
+ return {
20051
+ width,
20052
+ height,
20053
+ rotation
20054
+ };
20055
+ }
20056
+ const MAX_DURATION_SECONDS = 28800;
20057
+ const MAX_FILE_SIZE = 21474836480;
20058
+ const ALLOWED_EXTENSIONS = [
20059
+ ".mp4"
20060
+ ];
20061
+ const ALLOWED_CODECS = [
20062
+ "avc1",
20063
+ "avc3"
20064
+ ];
20065
+ const MIN_TITLE_LENGTH = 6;
20066
+ function formatFileSize(bytes) {
20067
+ if (bytes < 1048576) return `${(bytes / 1024).toFixed(2)} KB`;
20068
+ if (bytes < 1073741824) return `${(bytes / 1024 / 1024).toFixed(2)} MB`;
20069
+ return `${(bytes / 1024 / 1024 / 1024).toFixed(2)} GB`;
20070
+ }
20071
+ function formatDuration(seconds) {
20072
+ const total = Math.round(seconds);
20073
+ const h = Math.floor(total / 3600);
20074
+ const m = Math.floor(total % 3600 / 60);
20075
+ const s = total % 60;
20076
+ if (h > 0) return `${h}小时${m}分${s}秒`;
20077
+ if (m > 0) return `${m}分${s}秒`;
20078
+ return `${s}秒`;
20079
+ }
20080
+ function validateShipinhaoVideo(filePath, meta) {
20081
+ const fileName = external_node_path_default().basename(filePath);
20082
+ const ext = external_node_path_default().extname(fileName).toLowerCase();
20083
+ if (!ALLOWED_EXTENSIONS.includes(ext)) return `视频格式不支持:${fileName}。视频号仅支持 MP4/H.264 格式,请转换后重试。`;
20084
+ if (meta.duration > MAX_DURATION_SECONDS) return `视频时长超过限制:${fileName}(${formatDuration(meta.duration)})。视频号视频时长不能超过 8 小时,请剪辑后重试。`;
20085
+ if (meta.fileSize > MAX_FILE_SIZE) return `视频大小超过限制:${fileName}(${formatFileSize(meta.fileSize)})。视频号视频不能超过 20GB,请压缩后重试。`;
20086
+ if (meta.codec && !ALLOWED_CODECS.includes(meta.codec)) return `视频编码不支持:${fileName}(${meta.codec})。视频号仅支持 H.264 编码,请转码后重试。`;
20087
+ return null;
20088
+ }
20089
+ function validateShipinhaoTitle(title) {
20090
+ if (void 0 === title) return null;
20091
+ const trimmed = title.trim();
20092
+ const length = [
20093
+ ...trimmed
20094
+ ].length;
20095
+ if (length < MIN_TITLE_LENGTH) return `视频号标题至少需要 ${MIN_TITLE_LENGTH} 个字符,请补充后重试。`;
20096
+ return null;
20097
+ }
20098
+ async function getTraceKey(auth, http, logger) {
20099
+ logger.info("[getTraceKey] 开始获取 traceKey...");
20100
+ const res = await http.api({
20101
+ method: "POST",
20102
+ url: "https://channels.weixin.qq.com/micro/content/cgi-bin/mmfinderassistant-bin/post/get-finder-post-trace-key",
20103
+ data: {
20104
+ objectId: "",
20105
+ timestamp: String(Date.now()),
20106
+ _log_finder_uin: "",
20107
+ _log_finder_id: auth.finderUsername,
20108
+ rawKeyBuff: "",
20109
+ pluginSessionId: null,
20110
+ scene: 7,
20111
+ reqScene: 7
20112
+ },
20113
+ defaultErrorMsg: "获取 traceKey 失败"
20114
+ });
20115
+ if (0 !== res.errCode || !res.data?.traceKey) {
20116
+ logger.error("[getTraceKey] 获取失败:", JSON.stringify(res));
20117
+ throw new Error(`获取 traceKey 失败: ${JSON.stringify(res)}`);
20118
+ }
20119
+ logger.info(`[getTraceKey] 获取成功: ${res.data.traceKey}`);
20120
+ return res.data.traceKey;
20121
+ }
20122
+ async function submitAndPollTranscode(opts) {
20123
+ const { videoUrl, videoMeta, traceKey, uploadStartTime, uploadEndTime, finderUsername, http, logger } = opts;
20124
+ logger.info("[submitAndPollTranscode] 开始提交转码任务...");
20125
+ const finderUrl = videoUrl.includes("wxapp.tc.qq.com") ? `https://finder.video.qq.com${videoUrl.split("qq.com")[1]}` : videoUrl;
20126
+ logger.info(`[submitAndPollTranscode] 视频URL: ${finderUrl}`);
20127
+ logger.info(`[submitAndPollTranscode] 视频尺寸: ${videoMeta.width}x${videoMeta.height}, 时长: ${videoMeta.duration}s`);
20128
+ const submitRes = await http.api({
20129
+ method: "POST",
20130
+ url: "https://channels.weixin.qq.com/micro/content/cgi-bin/mmfinderassistant-bin/post/post_clip_video",
20131
+ data: {
20132
+ url: finderUrl,
20133
+ timeStart: 0,
20134
+ cropDuration: 0,
20135
+ height: videoMeta.height,
20136
+ width: videoMeta.width,
20137
+ x: 0,
20138
+ y: 0,
20139
+ clipOriginVideoInfo: {
20140
+ width: videoMeta.width,
20141
+ height: videoMeta.height,
20142
+ duration: videoMeta.duration,
20143
+ fileSize: videoMeta.fileSize
20144
+ },
20145
+ traceInfo: {
20146
+ traceKey,
20147
+ uploadCdnStart: uploadStartTime,
20148
+ uploadCdnEnd: uploadEndTime
20149
+ },
20150
+ targetWidth: videoMeta.width,
20151
+ targetHeight: videoMeta.height,
20152
+ type: 4,
20153
+ useAstraThumbCover: 1,
20154
+ timestamp: String(Date.now()),
20155
+ _log_finder_uin: "",
20156
+ _log_finder_id: finderUsername,
20157
+ rawKeyBuff: "",
20158
+ pluginSessionId: null,
20159
+ scene: 7,
20160
+ reqScene: 7
20161
+ },
20162
+ defaultErrorMsg: "提交转码失败"
20163
+ });
20164
+ if (0 !== submitRes.errCode || !submitRes.data?.clipKey) {
20165
+ logger.error("[submitAndPollTranscode] 提交转码失败:", JSON.stringify(submitRes));
20166
+ throw new Error(`提交转码失败: ${JSON.stringify(submitRes)}`);
20167
+ }
20168
+ const { clipKey, draftId } = submitRes.data;
20169
+ logger.info(`[submitAndPollTranscode] 转码任务已提交,clipKey: ${clipKey}, draftId: ${draftId}`);
20170
+ const maxPolls = 60;
20171
+ const pollInterval = 5000;
20172
+ let pollCount = 0;
20173
+ logger.info(`[submitAndPollTranscode] 开始轮询转码结果,最多 ${maxPolls} 次,间隔 ${pollInterval / 1000}s`);
20174
+ while(pollCount < maxPolls){
20175
+ await sleep(pollInterval);
20176
+ pollCount++;
20177
+ const pollRes = await http.api({
20178
+ method: "POST",
20179
+ url: "https://channels.weixin.qq.com/micro/content/cgi-bin/mmfinderassistant-bin/post/post_clip_video_result",
20180
+ data: {
20181
+ clipKey,
20182
+ draftId,
20183
+ timestamp: String(Date.now()),
20184
+ _log_finder_uin: "",
20185
+ _log_finder_id: finderUsername,
20186
+ rawKeyBuff: "",
20187
+ pluginSessionId: null,
20188
+ scene: 7,
20189
+ reqScene: 7
20190
+ },
20191
+ defaultErrorMsg: "转码轮询失败"
20192
+ });
20193
+ if (0 !== pollRes.errCode) {
20194
+ logger.error(`[submitAndPollTranscode] 转码轮询失败 (poll ${pollCount}):`, JSON.stringify(pollRes));
20195
+ throw new Error(`转码轮询失败 (poll ${pollCount}): ${JSON.stringify(pollRes)}`);
20196
+ }
20197
+ const { flag, url, width, height, duration, md5, fileSize } = pollRes.data || {};
20198
+ logger.info(`[submitAndPollTranscode] 轮询第 ${pollCount} 次,flag=${flag}`);
20199
+ if (1 === flag) {
20200
+ if (!url || !width || !height || !duration || !md5 || !fileSize) {
20201
+ logger.error("[submitAndPollTranscode] 转码完成但返回数据不完整:", JSON.stringify(pollRes.data));
20202
+ throw new Error(`转码完成但返回数据不完整: ${JSON.stringify(pollRes.data)}`);
20203
+ }
20204
+ logger.info(`[submitAndPollTranscode] 转码完成! 用时: ${pollCount * pollInterval / 1000}s`);
20205
+ logger.info(`[submitAndPollTranscode] 视频信息: ${width}x${height}, 时长: ${duration}s, 大小: ${fileSize}`);
20206
+ return {
20207
+ clipKey,
20208
+ url,
20209
+ width,
20210
+ height,
20211
+ duration,
20212
+ md5,
20213
+ fileSize
20214
+ };
20215
+ }
20216
+ if (2 === flag) logger.info(`[submitAndPollTranscode] 转码中... (${pollCount}/${maxPolls})`);
20217
+ else {
20218
+ logger.error(`[submitAndPollTranscode] 转码失败,未知 flag=${flag}:`, JSON.stringify(pollRes.data));
20219
+ throw new Error(`转码失败,未知 flag=${flag}: ${JSON.stringify(pollRes.data)}`);
20220
+ }
20221
+ }
20222
+ logger.error(`[submitAndPollTranscode] 转码超时,已轮询 ${maxPolls} 次,用时: ${maxPolls * pollInterval / 1000}s`);
20223
+ throw new Error(`转码超时 (${maxPolls * pollInterval / 1000}s)`);
20224
+ }
20225
+ async function publishVideo(opts) {
20226
+ const { params, auth, clipResult, videoUpload, coverUpload, traceKey, uploadStartTime, uploadEndTime, proxyHttp, logger } = opts;
20227
+ logger.info("[publishVideo] 开始构建发布请求...");
20228
+ const coverFinderUrl = coverUpload.downloadUrl.includes("wxapp.tc.qq.com") ? `https://finder.video.qq.com${coverUpload.downloadUrl.split("qq.com")[1]}` : coverUpload.downloadUrl;
20229
+ logger.info(`[publishVideo] 封面URL: ${coverFinderUrl}`);
20230
+ const md5sumUuid = external_node_crypto_default().randomUUID();
20231
+ logger.info("[publishVideo] 发布参数:");
20232
+ logger.info(` - 标题: ${params.title || "(无)"}`);
20233
+ logger.info(` - 描述: ${params.description?.substring(0, 50)}${params.description?.length > 50 ? "..." : ""}`);
20234
+ logger.info(` - 定时发布: ${params.scheduleTime ? new Date(1000 * params.scheduleTime).toLocaleString() : "立即发布"}`);
20235
+ logger.info(` - 地理位置: ${params.location ? `${params.location.city} (${params.location.latitude},${params.location.longitude})` : "(无)"}`);
20236
+ const publishRes = await proxyHttp.api({
20237
+ method: "POST",
20238
+ url: "https://channels.weixin.qq.com/micro/content/cgi-bin/mmfinderassistant-bin/post/post_create",
20239
+ data: {
20240
+ objectType: 0,
20241
+ longitude: params.location?.longitude || 0,
20242
+ latitude: params.location?.latitude || 0,
20243
+ feedLongitude: 0,
20244
+ feedLatitude: 0,
20245
+ originalFlag: 0,
20246
+ topics: [],
20247
+ isFullPost: 1,
20248
+ handleFlag: 2,
20249
+ videoClipTaskId: clipResult.clipKey,
20250
+ traceInfo: {
20251
+ traceKey,
20252
+ uploadCdnStart: uploadStartTime,
20253
+ uploadCdnEnd: uploadEndTime
20254
+ },
20255
+ objectDesc: {
20256
+ mpTitle: "",
20257
+ description: params.description,
20258
+ shortTitle: params.title || "",
20259
+ extReading: {},
20260
+ mediaType: 4,
20261
+ location: params.location ? {
20262
+ latitude: params.location.latitude,
20263
+ longitude: params.location.longitude,
20264
+ city: params.location.city,
20265
+ poiClassifyId: params.location.poiClassifyId || ""
20266
+ } : {
20267
+ latitude: 0,
20268
+ longitude: 0,
20269
+ city: "",
20270
+ poiClassifyId: ""
20271
+ },
20272
+ topic: {
20273
+ finderTopicInfo: `<finder><version>1</version><valuecount>1</valuecount><style><at></at></style><value0><![CDATA[${params.description}]]></value0></finder>`
20274
+ },
20275
+ event: {},
20276
+ mentionedUser: [],
20277
+ media: [
20278
+ {
20279
+ url: clipResult.url,
20280
+ fileSize: clipResult.fileSize,
20281
+ thumbUrl: coverFinderUrl,
20282
+ fullThumbUrl: coverFinderUrl,
20283
+ coverUrl: coverFinderUrl,
20284
+ fullCoverUrl: coverFinderUrl,
20285
+ shareCoverUrl: coverFinderUrl,
20286
+ mediaType: 4,
20287
+ videoPlayLen: Math.round(clipResult.duration),
20288
+ width: clipResult.width,
20289
+ height: clipResult.height,
20290
+ md5sum: md5sumUuid,
20291
+ cardShowStyle: 2,
20292
+ urlCdnTaskId: clipResult.clipKey
20293
+ }
20294
+ ],
20295
+ member: {}
20296
+ },
20297
+ effectiveTime: params.scheduleTime || 0,
20298
+ report: {
20299
+ clipKey: clipResult.clipKey,
20300
+ draftId: clipResult.clipKey,
20301
+ timestamp: String(Date.now()),
20302
+ _log_finder_uin: "",
20303
+ _log_finder_id: auth.finderUsername,
20304
+ rawKeyBuff: "",
20305
+ pluginSessionId: null,
20306
+ scene: 7,
20307
+ reqScene: 7,
20308
+ height: clipResult.height,
20309
+ width: clipResult.width,
20310
+ duration: clipResult.duration,
20311
+ fileSize: videoUpload.fileSize,
20312
+ uploadCost: (uploadEndTime - uploadStartTime) * 1000
20313
+ },
20314
+ postFlag: 0,
20315
+ mode: 1,
20316
+ clientid: external_node_crypto_default().randomUUID(),
20317
+ timestamp: String(Date.now()),
20318
+ _log_finder_uin: "",
20319
+ _log_finder_id: auth.finderUsername,
20320
+ rawKeyBuff: "",
20321
+ pluginSessionId: null,
20322
+ scene: 7,
20323
+ reqScene: 7
20324
+ },
20325
+ defaultErrorMsg: "发布视频失败"
20326
+ });
20327
+ logger.info(`[publishVideo] 发布响应: errCode=${publishRes.errCode}, baseResp.errcode=${publishRes.data?.baseResp?.errcode}`);
20328
+ return publishRes;
20329
+ }
20330
+ function sleep(ms) {
20331
+ return new Promise((resolve)=>setTimeout(resolve, ms));
20332
+ }
20333
+ const shipinhaoPublishVideo_mock_mockAction = async (task, params)=>{
20334
+ task.logger.info("[shipinhaoPublishVideo] 开始执行视频号视频发布 - Mock API 方式");
20335
+ const updateTaskState = task.taskStageStore?.update?.bind(task.taskStageStore, task.taskId || "");
20336
+ let currentStep = "初始化";
20337
+ try {
20338
+ currentStep = "解析认证信息";
20339
+ const cookieString = params.cookies.map((c)=>`${c.name}=${c.value}`).join("; ");
20340
+ const headers = {
20341
+ cookie: cookieString
20342
+ };
20343
+ const args = [
20344
+ {
20345
+ headers
20346
+ },
20347
+ task.logger,
20348
+ params.proxyLoc,
20349
+ params.accountId,
20350
+ "shipinhao"
20351
+ ];
20352
+ const http = new Http({
20353
+ headers
20354
+ });
20355
+ const proxyHttp = new Http(...args);
20356
+ currentStep = "验证发布参数";
20357
+ if (!params.videoPath) return (0, share_namespaceObject.response)(414, "视频文件路径不能为空", "");
20358
+ if (!params.coverPath) return (0, share_namespaceObject.response)(414, "封面图片路径不能为空", "");
20359
+ currentStep = "获取上传认证";
20360
+ task.logger.info("[shipinhaoPublishVideo] 获取上传认证...");
20361
+ const auth = await getShipinhaoUploadAuth(cookieString, http);
20362
+ currentStep = "解析视频元数据";
20363
+ task.logger.info("[shipinhaoPublishVideo] 解析视频元数据...");
20364
+ const videoMeta = parseVideoMeta(params.videoPath);
20365
+ if (!videoMeta) return (0, share_namespaceObject.response)(414, "视频文件解析失败,请检查文件格式(仅支持 MP4)", "");
20366
+ task.logger.info(`[shipinhaoPublishVideo] 视频: ${videoMeta.width}×${videoMeta.height}, ${videoMeta.duration.toFixed(2)}s, ${(videoMeta.fileSize / 1024 / 1024).toFixed(2)}MB, codec=${videoMeta.codec || "unknown"}`);
20367
+ currentStep = "校验视频限制";
20368
+ const validationError = validateShipinhaoVideo(params.videoPath, videoMeta);
20369
+ if (validationError) {
20370
+ task.logger.error(`[shipinhaoPublishVideo] 视频校验未通过: ${validationError}`);
20371
+ await updateTaskState?.({
20372
+ state: share_namespaceObject.TaskState.FAILED,
20373
+ error: validationError
20374
+ });
20375
+ return (0, share_namespaceObject.response)(414, validationError, "");
20376
+ }
20377
+ task.logger.info("[shipinhaoPublishVideo] 视频校验通过");
20378
+ currentStep = "校验标题";
20379
+ const titleError = validateShipinhaoTitle(params.title);
20380
+ if (titleError) {
20381
+ task.logger.error(`[shipinhaoPublishVideo] 标题校验未通过: ${titleError}`);
20382
+ await updateTaskState?.({
20383
+ state: share_namespaceObject.TaskState.FAILED,
20384
+ error: titleError
20385
+ });
20386
+ return (0, share_namespaceObject.response)(414, titleError, "");
20387
+ }
20388
+ currentStep = "获取 traceKey";
20389
+ task.logger.info("[shipinhaoPublishVideo] 获取 traceKey...");
20390
+ const traceKey = await getTraceKey(auth, http, task.logger);
20391
+ const uploadStartTime = Math.floor(Date.now() / 1000);
20392
+ task.logger.info(`[shipinhaoPublishVideo] 上传开始时间: ${uploadStartTime}`);
20393
+ currentStep = "上传视频";
20394
+ task.logger.info("[shipinhaoPublishVideo] 上传视频...");
20395
+ task.logger.info(`[shipinhaoPublishVideo] 视频路径: ${params.videoPath}`);
20396
+ task.logger.info(`[shipinhaoPublishVideo] 视频文件类型: ${auth.videoFileType}`);
20397
+ const videoUpload = await uploader_uploadFile({
20398
+ filePath: params.videoPath,
20399
+ fileType: auth.videoFileType,
20400
+ uin: auth.uin,
20401
+ authKey: auth.authKey,
20402
+ http,
20403
+ logger: task.logger
20404
+ });
20405
+ task.logger.info(`[shipinhaoPublishVideo] 视频上传完成,URL: ${videoUpload.downloadUrl}`);
20406
+ const uploadEndTime = Math.floor(Date.now() / 1000);
20407
+ task.logger.info(`[shipinhaoPublishVideo] 上传结束时间: ${uploadEndTime}, 耗时: ${uploadEndTime - uploadStartTime}s`);
20408
+ currentStep = "上传封面";
20409
+ task.logger.info("[shipinhaoPublishVideo] 上传封面...");
20410
+ task.logger.info(`[shipinhaoPublishVideo] 封面路径: ${params.coverPath}`);
20411
+ task.logger.info(`[shipinhaoPublishVideo] 封面文件类型: ${auth.pictureFileType}`);
20412
+ const coverUpload = await uploader_uploadFile({
20413
+ filePath: params.coverPath,
20414
+ fileType: auth.pictureFileType,
20415
+ uin: auth.uin,
20416
+ authKey: auth.authKey,
20417
+ http,
20418
+ logger: task.logger
20419
+ });
20420
+ task.logger.info(`[shipinhaoPublishVideo] 封面上传完成,URL: ${coverUpload.downloadUrl}`);
20421
+ currentStep = "提交转码";
20422
+ task.logger.info("[shipinhaoPublishVideo] 提交转码...");
20423
+ const clipResult = await submitAndPollTranscode({
20424
+ videoUrl: videoUpload.downloadUrl,
20425
+ videoMeta,
20426
+ traceKey,
20427
+ uploadStartTime,
20428
+ uploadEndTime,
20429
+ finderUsername: auth.finderUsername,
20430
+ http,
20431
+ logger: task.logger
20432
+ });
20433
+ currentStep = "发布视频";
20434
+ task.logger.info("[shipinhaoPublishVideo] 发布视频...");
20435
+ task.logger.info(`[shipinhaoPublishVideo] clipKey: ${clipResult.clipKey}`);
20436
+ let publishResult;
20437
+ try {
20438
+ publishResult = await publishVideo({
20439
+ params,
20440
+ auth,
20441
+ clipResult,
20442
+ videoUpload,
20443
+ coverUpload,
20444
+ traceKey,
20445
+ uploadStartTime,
20446
+ uploadEndTime,
20447
+ proxyHttp,
20448
+ logger: task.logger
20449
+ });
20450
+ } catch (error) {
20451
+ const handledError = Http.handleApiError(error);
20452
+ task.logger.error(`[shipinhaoPublishVideo] 发布请求失败: ${handledError.message}`, stringifyError(handledError));
20453
+ const classified = classifyPublishError(handledError);
20454
+ if (classified) {
20455
+ const message = `${classified.userMessage}${task.debug ? ` ${http.proxyInfo}` : ""}`;
20456
+ task.logger.error(`[shipinhaoPublishVideo] ${classified.category},直接返回: ${handledError.message} (code=${handledError.code})`, stringifyError(handledError));
20457
+ await updateTaskState?.({
20458
+ state: share_namespaceObject.TaskState.FAILED,
20459
+ error: message
20460
+ });
20461
+ return {
20462
+ code: 414,
20463
+ data: "",
20464
+ message
20465
+ };
20466
+ }
20467
+ throw error;
20468
+ }
20469
+ task.logger.info(`[shipinhaoPublishVideo] publishResult: ${JSON.stringify(publishResult)}`);
20470
+ const resultCode = publishResult.data?.baseResp?.errcode ?? publishResult.errCode;
20471
+ const resultMsg = publishResult.data?.baseResp?.errmsg ?? "发布成功";
20472
+ if (0 === resultCode) {
20473
+ task.logger.info("[shipinhaoPublishVideo] 发布成功");
20474
+ task.logger.info(`[shipinhaoPublishVideo] 作品ID: ${clipResult.clipKey}`);
20475
+ task.logger.info(`[shipinhaoPublishVideo] 视频URL: ${clipResult.url}`);
20476
+ task.logger.info(`[shipinhaoPublishVideo] 封面URL: ${coverUpload.downloadUrl}`);
20477
+ await updateTaskState?.({
20478
+ state: share_namespaceObject.TaskState.SUCCESS,
20479
+ result: {
20480
+ response: resultMsg
20481
+ }
20482
+ });
20483
+ reportLogger({
20484
+ token: params.huiwenToken || "",
20485
+ enverionment: task.enverionment || "development",
20486
+ postId: params.articleId,
20487
+ eip: proxyHttp.proxyInfo,
20488
+ accountId: params.accountId,
20489
+ uid: params.uid,
20490
+ publishParams: {
20491
+ videoPath: params.videoPath,
20492
+ coverPath: params.coverPath
20493
+ },
20494
+ platform: "shipinhao"
20495
+ });
20496
+ task.logger.info("[shipinhaoPublishVideo] 日志上报完成");
20497
+ return (0, share_namespaceObject.response)(0, "发布成功", clipResult.clipKey);
20498
+ }
20499
+ let errorMessage = resultMsg;
20500
+ if (-11224 === resultCode) errorMessage = "视频号管理员完成实名且绑定手机号后才可以发表";
20501
+ else if (300333 === resultCode || 300334 === resultCode) errorMessage = "登录失效";
20502
+ else if (300330 === resultCode) errorMessage = "未登录";
20503
+ task.logger.error(`[shipinhaoPublishVideo] 发布失败: ${errorMessage} (errCode=${resultCode})`);
20504
+ await updateTaskState?.({
20505
+ state: share_namespaceObject.TaskState.FAILED,
20506
+ error: errorMessage
20507
+ });
20508
+ return (0, share_namespaceObject.response)(resultCode || 414, errorMessage, "");
20509
+ } catch (error) {
20510
+ const handledError = Http.handleApiError(error);
20511
+ const errorMsg = handledError.message || "发布失败,请稍后重试";
20512
+ const errorCode = handledError.code || 414;
20513
+ task.logger.error(`[shipinhaoPublishVideo] 发布流程异常 [${currentStep}]: ${errorMsg}`, stringifyError(error), handledError.extra);
20514
+ task.logger.error(`[shipinhaoPublishVideo] 错误码: ${errorCode}, 当前步骤: ${currentStep}`);
20515
+ await updateTaskState?.({
20516
+ state: share_namespaceObject.TaskState.FAILED,
20517
+ error: errorMsg
20518
+ });
20519
+ return (0, share_namespaceObject.response)(errorCode, errorMsg, "");
20520
+ }
20521
+ };
20522
+ const shipinhaoPublishVideo_rpa_rpaAction = async (task, params)=>{
20523
+ task.logger.info("开始微信视频号视频发布(RPA 模式)");
20524
+ const videoMeta = parseVideoMeta(params.videoPath);
20525
+ if (!videoMeta) return (0, share_namespaceObject.response)(414, "视频文件解析失败,请检查文件格式(仅支持 MP4)", "");
20526
+ task.logger.info(`视频: ${videoMeta.width}×${videoMeta.height}, ${videoMeta.duration.toFixed(2)}s, ${(videoMeta.fileSize / 1024 / 1024).toFixed(2)}MB, codec=${videoMeta.codec || "unknown"}`);
20527
+ const validationError = validateShipinhaoVideo(params.videoPath, videoMeta);
20528
+ if (validationError) {
20529
+ task.logger.error(`视频校验未通过: ${validationError}`);
20530
+ return (0, share_namespaceObject.response)(414, validationError, "");
20531
+ }
20532
+ task.logger.info("视频校验通过");
20533
+ const titleError = validateShipinhaoTitle(params.title);
20534
+ if (titleError) {
20535
+ task.logger.error(`标题校验未通过: ${titleError}`);
20536
+ return (0, share_namespaceObject.response)(414, titleError, "");
20537
+ }
20538
+ const tmpCachePath = task.getTmpPath();
20539
+ const page = await task.createPage({
20540
+ url: "https://channels.weixin.qq.com/platform/post/create",
20541
+ show: task.debug,
20542
+ cookies: params.cookies
20543
+ });
20544
+ try {
20545
+ const waitForElement = async (selector, timeout = 10000)=>{
20546
+ try {
20547
+ const element = page.locator(selector);
20548
+ await element.waitFor({
20549
+ state: "visible",
20550
+ timeout
20551
+ });
20552
+ return element;
20553
+ } catch {
20554
+ task.logger.warn(`元素未找到: ${selector}`);
20555
+ return null;
20556
+ }
20557
+ };
20558
+ const retryAction = async (action, maxRetries = 3, delay = 1000)=>{
20559
+ let lastError;
20560
+ for(let i = 0; i < maxRetries; i++)try {
20561
+ return await action();
20562
+ } catch (error) {
20563
+ lastError = error;
20564
+ task.logger.warn(`重试 ${i + 1}/${maxRetries}: ${lastError.message}`);
20565
+ if (i < maxRetries - 1) await page.waitForTimeout(delay);
20566
+ }
20567
+ throw lastError;
20568
+ };
20569
+ task.logger.info("等待页面加载...");
20570
+ task.logger.info("检查登录状态...");
20571
+ if (task.debug) {
20572
+ task.logger.info(`当前页面 URL: ${page.url()}`);
20573
+ const title = await page.title();
20574
+ task.logger.info(`页面标题: ${title}`);
20575
+ }
20576
+ try {
20577
+ await page.waitForSelector(".post-edit-wrap", {
20578
+ state: "visible",
20579
+ timeout: 30000
20580
+ });
20581
+ task.logger.info("✓ 登录状态正常,找到编辑器容器");
20582
+ } catch {
20583
+ task.logger.error("✗ 未找到编辑器,可能登录失效");
20584
+ return {
20585
+ code: 414,
20586
+ message: "登录失效或页面加载异常",
20587
+ data: page.url()
20588
+ };
20589
+ }
20590
+ task.logger.info("页面加载完成,开始填充内容");
20591
+ task.logger.info("开始上传视频");
20592
+ await retryAction(async ()=>{
20593
+ const videoUploadSelectors = [
20594
+ '.ant-upload-btn input[type="file"][accept*="video"]',
20595
+ '.upload input[type="file"][accept*="video"]',
20596
+ 'input[type="file"][accept*="video"]'
20597
+ ];
20598
+ let uploadInput = null;
20599
+ if (task.debug) {
20600
+ const allFileInputs = await page.locator('input[type="file"]').count();
20601
+ task.logger.info(`页面中共找到 ${allFileInputs} 个文件上传输入框`);
20602
+ }
20603
+ for (const selector of videoUploadSelectors){
20604
+ const input = page.locator(selector);
20605
+ const count = await input.count();
20606
+ if (count > 0) {
20607
+ uploadInput = input.first();
20608
+ task.logger.info(`找到视频上传输入框: ${selector}`);
20609
+ break;
20610
+ }
20611
+ }
20612
+ if (!uploadInput) {
20613
+ task.logger.warn("未找到视频上传输入框,等待 3 秒后重试...");
20614
+ await page.waitForTimeout(3000);
20615
+ const anyFileInput = page.locator('input[type="file"]');
20616
+ const inputCount = await anyFileInput.count();
20617
+ if (inputCount > 0) {
20618
+ uploadInput = anyFileInput.first();
20619
+ task.logger.info(`找到文件输入框(共 ${inputCount} 个)`);
20620
+ } else {
20621
+ if (task.debug) {
20622
+ const screenshotPath = external_node_path_default().join(tmpCachePath, `upload-error-${Date.now()}.png`);
20623
+ await page.screenshot({
20624
+ path: screenshotPath,
20625
+ fullPage: true
20626
+ });
20627
+ task.logger.error(`未找到上传输入框,已截图保存至: ${screenshotPath}`);
20628
+ }
20629
+ throw new Error("未找到视频上传输入框");
20630
+ }
20631
+ }
20632
+ await uploadInput.setInputFiles(params.videoPath);
20633
+ task.logger.info("视频上传成功");
20634
+ await page.waitForTimeout(5000);
20635
+ });
20636
+ if (params.coverPath) {
20637
+ task.logger.info("开始上传封面");
20638
+ await retryAction(async ()=>{
20639
+ const coverUploadBtn = await waitForElement(".cover-upload-btn", 10000);
20640
+ if (coverUploadBtn) {
20641
+ const coverInput = page.locator('.cover-upload-btn input[type="file"]');
20642
+ await coverInput.setInputFiles(params.coverPath);
20643
+ task.logger.info("封面上传成功");
20644
+ await page.waitForTimeout(2000);
20645
+ }
20646
+ });
20647
+ }
20648
+ if (params.description) {
20649
+ task.logger.info("填写视频描述");
20650
+ await retryAction(async ()=>{
20651
+ const descEditor = await waitForElement(".input-editor", 10000);
20652
+ if (!descEditor) throw new Error("未找到描述编辑器");
20653
+ await descEditor.click();
20654
+ await page.waitForTimeout(500);
20655
+ await descEditor.evaluate((el)=>{
20656
+ el.textContent = "";
20657
+ });
20658
+ await page.waitForTimeout(300);
20659
+ task.logger.info("已清空编辑器内容");
20660
+ await descEditor.pressSequentially(params.description, {
20661
+ delay: 10
20662
+ });
20663
+ await page.waitForTimeout(500);
20664
+ task.logger.info("描述填写完成");
20665
+ });
20666
+ }
20667
+ if (params.title) {
20668
+ task.logger.info(`填写标题: ${params.title}`);
20669
+ const title = params.title;
20670
+ await retryAction(async ()=>{
20671
+ const titleInput = await waitForElement("#container-wrap div.form-item-body.short-title-wrap input", 10000);
20672
+ if (!titleInput) throw new Error("未找到标题输入框");
20673
+ await titleInput.click();
20674
+ await titleInput.clear({
20675
+ timeout: 3000
20676
+ });
20677
+ await titleInput.fill(title, {
20678
+ timeout: 5000
20679
+ });
20680
+ task.logger.info("标题填写完成");
20681
+ });
20682
+ }
20683
+ if (params.location) {
20684
+ task.logger.info(`选择地点: ${params.location.city}`);
20685
+ const instance = page.locator(".position-display-wrap");
20686
+ await instance.click();
20687
+ await page.waitForTimeout(1000);
20688
+ await page.locator(".location-filter-wrap input").fill(params.location.city);
20689
+ await page.waitForTimeout(2000);
20690
+ const poperInstance = page.locator(".location-filter-wrap .common-option-list-wrap .option-item");
20691
+ await poperInstance.nth(1).waitFor();
20692
+ await poperInstance.nth(1).click();
20693
+ task.logger.info("地点选择完成");
20694
+ }
20695
+ if (params.scheduleTime) {
20696
+ task.logger.info("设置定时发布");
20697
+ const timingRadio = page.locator(".weui-desktop-form__check-label").filter({
20698
+ hasNotText: "不定时"
20699
+ }).first();
20700
+ await timingRadio.click();
20701
+ await page.waitForTimeout(500);
20702
+ const instance = page.locator(".weui-desktop-picker__date");
20703
+ await instance.click();
20704
+ const dateD = utils_TimeFormatter.format(1000 * params.scheduleTime, "d");
20705
+ const nowMonth = utils_TimeFormatter.format(Date.now(), "MM月");
20706
+ const nowMonthText = utils_TimeFormatter.format(Date.now(), "M月");
20707
+ const month = utils_TimeFormatter.format(1000 * params.scheduleTime, "MM月");
20708
+ const monthLocator = await page.locator("weui-desktop-picker__panel__label").filter({
20709
+ hasText: month
20710
+ }).first();
20711
+ if (!monthLocator) {
20712
+ await page.locator(".weui-desktop-picker__panel__label").filter({
20713
+ hasText: nowMonth
20714
+ }).first().click();
20715
+ await page.waitForTimeout(500);
20716
+ await page.locator(".weui-desktop-picker__table-row td a").filter({
20717
+ hasText: nowMonthText
20718
+ }).first().click();
20719
+ }
20720
+ await page.waitForTimeout(500);
20721
+ await page.locator(".weui-desktop-picker__table-row td a").filter({
20722
+ hasText: dateD
20723
+ }).first().click();
20724
+ await page.locator(".weui-desktop-form__input-wrp input[placeholder*='请选择时间']").fill(utils_TimeFormatter.format(1000 * params.scheduleTime, "hh:mm"));
20725
+ await page.locator("i.weui-desktop-icon__time").click();
20726
+ await page.locator(".post-time-wrap .form-item .label").filter({
20727
+ hasText: "发表时间"
20728
+ }).click();
20729
+ }
20730
+ task.logger.info("准备发布...");
20731
+ await page.waitForTimeout(300);
20732
+ let videoId = "";
20733
+ const handleResponse = async (response)=>{
20734
+ const url = response.url();
20735
+ if (url.includes("/post/post_create")) {
20736
+ const jsonResponse = await response.json();
20737
+ page.off("response", handleResponse);
20738
+ videoId = jsonResponse.object?.id || jsonResponse.data?.objectId || "";
20739
+ }
20740
+ };
20741
+ page.on("response", handleResponse);
20742
+ task._timerRecord.PrePublish = Date.now();
20743
+ 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";
20744
+ task.logger.info("等待视频上传完成(预览区媒体操作栏出现)...");
20745
+ const uploadTimeout = 600000;
20746
+ const uploadWaitStart = Date.now();
20747
+ let lastProgressLog = 0;
20748
+ while(true){
20749
+ const ready = await page.evaluate((selector)=>{
20750
+ const host = document.querySelector("#container-wrap > div.container-center > div > wujie-app");
20751
+ const root = host?.shadowRoot;
20752
+ if (!root) return false;
20753
+ return !!root.querySelector(selector);
20754
+ }, MEDIA_OPR_SELECTOR);
20755
+ if (ready) break;
20756
+ const elapsed = Date.now() - uploadWaitStart;
20757
+ if (elapsed > uploadTimeout) throw new Error(`视频上传超时,预览区未就绪(已等待 ${Math.round(elapsed / 1000)}s)`);
20758
+ if (elapsed - lastProgressLog >= 15000) {
20759
+ lastProgressLog = elapsed;
20760
+ task.logger.info(`视频仍在上传中... 已等待 ${Math.round(elapsed / 1000)}s`);
20761
+ }
20762
+ await page.waitForTimeout(1000);
20763
+ }
20764
+ task.logger.info(`视频上传完成(等待 ${Math.round((Date.now() - uploadWaitStart) / 1000)}s)`);
20765
+ const clicked = await page.evaluate(()=>{
20766
+ const host = document.querySelector("#container-wrap > div.container-center > div > wujie-app");
20767
+ const root = host?.shadowRoot;
20768
+ if (!root) return "未找到 wujie-app shadowRoot";
20769
+ const btns = Array.from(root.querySelectorAll(".form-btns .weui-desktop-btn"));
20770
+ const target = btns.find((el)=>(el.textContent || "").includes("发表"));
20771
+ if (!target) return "未找到发表按钮";
20772
+ if (target.classList.contains("weui-desktop-btn_disabled")) return "发表按钮仍处于禁用状态";
20773
+ target.click();
20774
+ return null;
20775
+ });
20776
+ if (clicked) throw new Error(clicked);
20777
+ task.logger.info("已点击发布按钮,等待响应...");
20778
+ try {
20779
+ await page.waitForURL((url)=>url.href !== page.url(), {
20780
+ timeout: 30000
20781
+ });
20782
+ task.logger.info(`发布成功,页面已跳转: ${page.url()}`);
20783
+ } catch {
20784
+ task.logger.warn("等待页面跳转超时,可能发布失败或网络慢,继续关闭页面");
20785
+ }
20786
+ await page.close();
20787
+ return (0, share_namespaceObject.success)(videoId, "发布成功");
20788
+ } catch (error) {
20789
+ let errorMsg = error instanceof Error ? error.message : String(error);
20790
+ if (errorMsg.includes("context or browser has been closed")) errorMsg = "浏览器上下文已被关闭";
20791
+ task.logger.error(`微信视频号视频发布失败: ${errorMsg}`);
20792
+ return (0, share_namespaceObject.response)(414, `微信视频号视频发布失败: ${errorMsg}`, "");
20793
+ }
20794
+ };
20795
+ const ShipinhaoPublishVideoParamsSchema = ActionCommonParamsSchema.extend({
20796
+ videoPath: schemas_string().min(1),
20797
+ coverPath: schemas_string().min(1),
20798
+ description: schemas_string(),
20799
+ title: schemas_string().optional(),
20800
+ scheduleTime: schemas_number().int().positive().optional(),
20801
+ location: schemas_object({
20802
+ latitude: schemas_number(),
20803
+ longitude: schemas_number(),
20804
+ city: schemas_string(),
20805
+ poiClassifyId: schemas_string().optional()
20806
+ }).optional()
20807
+ });
20808
+ const shipinhaoPublishVideo = async (task, params)=>{
20809
+ task.logger.info(`shipinhaoPublishVideo actionType: ${params.actionType}`);
20810
+ if ("rpa" === params.actionType) return shipinhaoPublishVideo_rpa_rpaAction(task, params);
20811
+ if ("mockApi" === params.actionType) return shipinhaoPublishVideo_mock_mockAction(task, params);
20812
+ return executeAction(shipinhaoPublishVideo_mock_mockAction, shipinhaoPublishVideo_rpa_rpaAction)(task, params);
20813
+ };
19709
20814
  const ShipinhaoSendMsgParamsSchema = ActionCommonParamsSchema.extend({
19710
20815
  toUsername: schemas_string().min(1, "接收者用户名不能为空"),
19711
20816
  sessionId: schemas_string().min(1, "会话ID不能为空"),
@@ -19720,7 +20825,7 @@ var __webpack_exports__ = {};
19720
20825
  pathOrUrl: schemas_string().min(1, "图片路径或URL不能为空")
19721
20826
  }).optional()
19722
20827
  });
19723
- const CHUNK_SIZE = 524288;
20828
+ const shipinhaoSendMsg_CHUNK_SIZE = 524288;
19724
20829
  async function shipinhaoSendMsg_getUserInfo(cookieStr, http) {
19725
20830
  const url = `https://channels.weixin.qq.com/cgi-bin/mmfinderassistant-bin/auth/auth_data?_rid=${rid()}`;
19726
20831
  const headers = {
@@ -19803,11 +20908,11 @@ var __webpack_exports__ = {};
19803
20908
  }
19804
20909
  const md5 = (0, external_node_crypto_namespaceObject.createHash)("md5").update(imageBuffer).digest("hex");
19805
20910
  const timestamp = Date.now().toString();
19806
- const totalChunks = Math.ceil(imageBuffer.length / CHUNK_SIZE);
20911
+ const totalChunks = Math.ceil(imageBuffer.length / shipinhaoSendMsg_CHUNK_SIZE);
19807
20912
  console.log(`分片上传md5${md5}`);
19808
20913
  let lastRes;
19809
20914
  for(let i = 0; i < totalChunks; i++){
19810
- const chunkBuffer = imageBuffer.slice(i * CHUNK_SIZE, (i + 1) * CHUNK_SIZE);
20915
+ const chunkBuffer = imageBuffer.slice(i * shipinhaoSendMsg_CHUNK_SIZE, (i + 1) * shipinhaoSendMsg_CHUNK_SIZE);
19811
20916
  const requestData = {
19812
20917
  content: `data:application/octet-stream;base64,${chunkBuffer.toString("base64")}`,
19813
20918
  chunk: i,
@@ -20260,6 +21365,13 @@ var __webpack_exports__ = {};
20260
21365
  const uploadImages = async (images)=>await Promise.all(images.map(async (url)=>{
20261
21366
  const fileName = (0, share_namespaceObject.getFilenameFromUrl)(url);
20262
21367
  const image = await (0, share_namespaceObject.downloadImage)(url, external_node_path_default().join(tmpCachePath, fileName));
21368
+ const stats = external_node_fs_default().statSync(image);
21369
+ const maxSize = 20971520;
21370
+ if (stats.size > maxSize) throw {
21371
+ code: 414,
21372
+ message: "头条号平台:单张图片不得超过 20MB",
21373
+ data: ""
21374
+ };
20263
21375
  const formData = new (external_form_data_default())();
20264
21376
  formData.append("image", external_node_fs_default().createReadStream(image));
20265
21377
  const response = await http.api({
@@ -23543,6 +24655,12 @@ var __webpack_exports__ = {};
23543
24655
  const fileName = (0, share_namespaceObject.getFilenameFromUrl)(url);
23544
24656
  const localUrl = await (0, share_namespaceObject.downloadImage)(url, external_node_path_default().join(tmpCachePath, fileName));
23545
24657
  const fileBuffer = external_node_fs_default().readFileSync(localUrl);
24658
+ const maxSize = 33554432;
24659
+ if (fileBuffer.byteLength > maxSize) throw {
24660
+ code: 414,
24661
+ message: "小红书平台:单张图片不得超过 32MB",
24662
+ data: ""
24663
+ };
23546
24664
  let width = 0;
23547
24665
  let height = 0;
23548
24666
  try {
@@ -25727,6 +26845,9 @@ var __webpack_exports__ = {};
25727
26845
  shipinhaoPublish(params) {
25728
26846
  return this.bindTask(shipinhaoPublish, params);
25729
26847
  }
26848
+ shipinhaoPublishVideo(params) {
26849
+ return this.bindTask(shipinhaoPublishVideo, params);
26850
+ }
25730
26851
  douyinGetTopics(params) {
25731
26852
  return this.bindTask(douyinGetTopics, params);
25732
26853
  }
@@ -25786,4 +26907,5 @@ if (__webpack_exports__.__esModule) Object.defineProperty(__webpack_export_targe
25786
26907
  value: true
25787
26908
  });
25788
26909
 
25789
- //# sourceMappingURL=index.js.map
26910
+ //# sourceMappingURL=index.js.map
26911
+ //# debugId=1de33b63-4038-5f51-813c-0899b138a5ca