publishport-opencli 1.0.65 → 1.0.67

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/cli-manifest.json CHANGED
@@ -14611,7 +14611,7 @@
14611
14611
  {
14612
14612
  "site": "douyin",
14613
14613
  "name": "draft",
14614
- "description": "上传视频并保存为草稿",
14614
+ "description": "上传视频并保存为草稿(草稿不保存定时发布时间,定时请用 publish --schedule)",
14615
14615
  "access": "write",
14616
14616
  "domain": "creator.douyin.com",
14617
14617
  "strategy": "cookie",
@@ -14700,12 +14700,6 @@
14700
14700
  "required": false,
14701
14701
  "help": "站内转载来源作品ID(UI命令须在当前观看历史中)"
14702
14702
  },
14703
- {
14704
- "name": "schedule",
14705
- "type": "str",
14706
- "required": false,
14707
- "help": "定时发布,北京时间 YYYY-MM-DD HH:mm / ISO8601 / Unix秒;2小时至14天后"
14708
- },
14709
14703
  {
14710
14704
  "name": "allow-download",
14711
14705
  "type": "boolean",
@@ -1,11 +1,11 @@
1
- import{DOUYIN_VIDEO_ARGS as w,validateDouyinSettings as v,setDouyinPublishSettings as h}from"./_shared/publish-settings.js";import*as m from"node:fs";import*as s from"node:path";import{cli as A,Strategy as x}from"@jackwener/opencli/registry";import{ArgumentError as c,CommandExecutionError as a}from"@jackwener/opencli/errors";import{setInputFiles as p}from"../_shared/file-inject.js";const b={public:"公开",friends:"好友可见",private:"仅自己可见"},T="https://creator.douyin.com/creator-micro/content/upload",k=120,S=20,g=20,C=60,E=200;async function y(t){await t.evaluate(`() => {
1
+ import{DOUYIN_VIDEO_ARGS as v,validateDouyinSettings as h,setDouyinPublishSettings as A}from"./_shared/publish-settings.js";import*as m from"node:fs";import*as s from"node:path";import{cli as T,Strategy as x}from"@jackwener/opencli/registry";import{ArgumentError as c,CommandExecutionError as a}from"@jackwener/opencli/errors";import{setInputFiles as p}from"../_shared/file-inject.js";const b={public:"公开",friends:"好友可见",private:"仅自己可见"},g="https://creator.douyin.com/creator-micro/content/upload",S=120,k=20,E=20,C=60,I=200;async function y(t){await t.evaluate(`() => {
2
2
  const targets = ['我知道了', '知道了', '关闭'];
3
3
  for (const text of targets) {
4
4
  const btn = Array.from(document.querySelectorAll('button,[role="button"]'))
5
5
  .find((el) => (el.textContent || '').trim() === text);
6
6
  if (btn instanceof HTMLElement) btn.click();
7
7
  }
8
- }`)}async function I(t){let e={href:"",ready:!1,bodyText:""};for(let n=0;n<k;n+=1){e=await t.evaluate(`() => ({
8
+ }`)}async function _(t){let e={href:"",ready:!1,bodyText:""};for(let n=0;n<S;n+=1){e=await t.evaluate(`() => ({
9
9
  href: location.href,
10
10
  ready: !!Array.from(document.querySelectorAll('input')).find(
11
11
  (el) => (el.placeholder || '').includes('填写作品标题')
@@ -13,7 +13,7 @@ import{DOUYIN_VIDEO_ARGS as w,validateDouyinSettings as v,setDouyinPublishSettin
13
13
  (el) => (el.textContent || '').includes('暂存离开')
14
14
  ),
15
15
  bodyText: document.body?.innerText || ''
16
- })`);if(e.ready)return;await t.wait({time:0.5})}throw new a("等待抖音草稿编辑页超时",`当前页面: ${e.href||"unknown"}`)}async function _(t,e){for(let n=0;n<E;n+=1){const o=await t.evaluate(`() => {
16
+ })`);if(e.ready)return;await t.wait({time:0.5})}throw new a("等待抖音草稿编辑页超时",`当前页面: ${e.href||"unknown"}`)}async function q(t,e){for(let n=0;n<I;n+=1){const i=await t.evaluate(`() => {
17
17
  const text = document.body?.innerText || '';
18
18
  const uploading = /上传中|上传\\s*\\d+%|视频上传中|处理中/.test(text);
19
19
  const saveBtn = Array.from(document.querySelectorAll('button')).find(
@@ -27,7 +27,23 @@ import{DOUYIN_VIDEO_ARGS as w,validateDouyinSettings as v,setDouyinPublishSettin
27
27
  (el) => (el.textContent || '').includes(${JSON.stringify(e)})
28
28
  );
29
29
  return { uploading, saveEnabled, hasSaveBtn: !!saveBtn, hasCaptionEditor, hasVisibility };
30
- }`);if(o.hasSaveBtn&&o.saveEnabled&&o.hasCaptionEditor&&o.hasVisibility&&!o.uploading)return;await t.wait({time:0.5})}}async function q(t,e){const n=60;let o=!1;for(let r=0;r<n;r+=1){o=await t.evaluate(`() => {
30
+ }`);if(i.hasSaveBtn&&i.saveEnabled&&i.hasCaptionEditor&&i.hasVisibility&&!i.uploading)return;await t.wait({time:0.5})}}export function normalizeCaptionText(t){return String(t??"").replace(/[\u200b\ufeff]/g,"").split(/\r?\n/).map((e)=>e.trim()).filter(Boolean).join(`
31
+ `)}function w(t){return`() => {
32
+ const editor = document.querySelector('[contenteditable="true"]');
33
+ if (!(editor instanceof HTMLElement)) return false;
34
+ editor.focus();
35
+ const target = ${t} < 0 ? editor : editor.querySelectorAll('.ace-line')[${t}];
36
+ if (!(target instanceof HTMLElement)) return false;
37
+ const range = document.createRange();
38
+ range.selectNodeContents(${t} < 0 ? editor : (target.querySelector('[data-line-wrapper]') || target));
39
+ if (${t} >= 0) range.collapse(true);
40
+ const selection = window.getSelection();
41
+ selection.removeAllRanges();
42
+ selection.addRange(range);
43
+ return true;
44
+ }`}async function L(t,e,n){if(typeof t.insertText!=="function")throw new a("填写抖音草稿正文失败: 当前浏览器连接不支持原生文字输入(insertText)","更新 PublishPort 客户端后重试");let i=!1;for(let r=0;r<n;r+=1){i=await t.evaluate(w(-1));if(i)break;await t.wait({time:0.5})}if(!i)throw new a("填写抖音草稿表单失败: caption-editor-missing");const o=String(e).replace(/\r\n?/g,`
45
+ `).replace(/\n+$/,"").split(`
46
+ `);if(o.length===1)await t.insertText(o[0]);else{await t.pressKey("Backspace");for(let r=1;r<o.length;r+=1)await t.pressKey("Enter");for(let r=0;r<o.length;r+=1){if(!o[r])continue;if(!await t.evaluate(w(r)))throw new a(`填写抖音草稿正文失败: 编辑器里找不到第 ${r+1} 行`);await t.insertText(o[r])}}await t.wait({time:0.5});const l=await t.evaluate(`() => document.querySelector('[contenteditable="true"]')?.innerText || ''`);if(normalizeCaptionText(l)!==normalizeCaptionText(e))throw new a(`填写抖音草稿正文失败: 回读与 --caption 不一致(页面上是「${String(l).replace(/[\u200b\ufeff]/g,"").slice(0,120)}」)`,"草稿尚未保存;可重试一次,仍不一致请把这条报错附在反馈里")}async function M(t,e){const n=60;let i=!1;for(let l=0;l<n;l+=1){i=await t.evaluate(`() => {
31
47
  const titleInput = Array.from(document.querySelectorAll('input')).find(
32
48
  (el) => (el.placeholder || '').includes('填写作品标题')
33
49
  );
@@ -55,23 +71,14 @@ import{DOUYIN_VIDEO_ARGS as w,validateDouyinSettings as v,setDouyinPublishSettin
55
71
  titleInput.dispatchEvent(new Event('blur', { bubbles: true }));
56
72
  }
57
73
  return true;
58
- }`);if(o)break;await t.wait({time:0.5})}if(!o)throw new a("填写抖音草稿表单失败: title-input-missing");if(e.caption){let r=!1;for(let l=0;l<n;l+=1){r=await t.evaluate(`() => {
59
- const editor = document.querySelector('[contenteditable="true"]');
60
- if (!(editor instanceof HTMLElement)) return false;
61
- editor.focus();
62
- editor.textContent = '';
63
- document.execCommand('selectAll', false);
64
- document.execCommand('insertText', false, ${JSON.stringify(e.caption)});
65
- editor.dispatchEvent(new Event('input', { bubbles: true }));
66
- return true;
67
- }`);if(r)break;await t.wait({time:0.5})}if(!r)throw new a("填写抖音草稿表单失败: caption-editor-missing")}let i=!1;for(let r=0;r<n;r+=1){i=await t.evaluate(`() => {
74
+ }`);if(i)break;await t.wait({time:0.5})}if(!i)throw new a("填写抖音草稿表单失败: title-input-missing");if(e.caption)await L(t,e.caption,n);let o=!1;for(let l=0;l<n;l+=1){o=await t.evaluate(`() => {
68
75
  const visibility = Array.from(document.querySelectorAll('label')).find(
69
76
  (el) => (el.textContent || '').includes(${JSON.stringify(e.visibilityLabel)})
70
77
  );
71
78
  if (!(visibility instanceof HTMLElement)) return false;
72
79
  visibility.click();
73
80
  return true;
74
- }`);if(i)break;await t.wait({time:0.5})}if(!i)throw new a("填写抖音草稿表单失败: visibility-missing")}async function L(t){let e="cover-input-missing";const n=await t.evaluate(`() => Array.from(document.querySelectorAll('input[type="file"]')).length`);for(let o=0;o<S;o+=1){const i=await t.evaluate(`() => {
81
+ }`);if(o)break;await t.wait({time:0.5})}if(!o)throw new a("填写抖音草稿表单失败: visibility-missing")}async function O(t){let e="cover-input-missing";const n=await t.evaluate(`() => Array.from(document.querySelectorAll('input[type="file"]')).length`);for(let i=0;i<k;i+=1){const o=await t.evaluate(`() => {
75
82
  const visible = (el) => { const r = el.getBoundingClientRect(); return r.width > 0 && r.height > 0; };
76
83
  const mark = (target) => {
77
84
  document
@@ -115,7 +122,7 @@ import{DOUYIN_VIDEO_ARGS as w,validateDouyinSettings as v,setDouyinPublishSettin
115
122
  return { ok: false, reason: 'cover-modal-input-missing' };
116
123
  }
117
124
  return { ok: true, selector: mark(zone), mode: 'modal' };
118
- }`);if(i?.ok&&i.selector)return{selector:i.selector,mode:i.mode||"label"};e=i?.reason||e;await t.wait({time:0.5})}throw new a(`准备抖音自定义封面输入框失败: ${e}`)}async function M(t){let e=null;for(let o=0;o<C;o+=1){e=await t.evaluate(`() => {
125
+ }`);if(o?.ok&&o.selector)return{selector:o.selector,mode:o.mode||"label"};e=o?.reason||e;await t.wait({time:0.5})}throw new a(`准备抖音自定义封面输入框失败: ${e}`)}async function P(t){let e=null;for(let i=0;i<C;i+=1){e=await t.evaluate(`() => {
119
126
  const visible = (el) => { const r = el.getBoundingClientRect(); return r.width > 0 && r.height > 0; };
120
127
  const dialogs = Array.from(document.querySelectorAll('.dy-creator-content-modal, [role="dialog"]')).filter(visible);
121
128
  // 点「完成」后若只设了竖封面,会再弹「设置横封面获更多流量」:选「暂不设置」。
@@ -162,7 +169,7 @@ import{DOUYIN_VIDEO_ARGS as w,validateDouyinSettings as v,setDouyinPublishSettin
162
169
  root = root.parentElement;
163
170
  }
164
171
  return '';
165
- }`}async function O(t){return await t.evaluate(buildCoverCheckPanelTextJs())||""}async function P(t){let e="",n=!1;for(let o=0;o<g;o+=1){const i=await O(t),r=i.includes("检测中"),l=i.includes("重新检测")||i.includes("横/竖双封面缺失");if(r)n=!0;if(n&&l&&!r)return;e=i;await t.wait({time:0.5})}throw new a("等待抖音封面处理完成超时",e||"unknown")}async function B(t){const e=60;let n=null;for(let o=0;o<e;o+=1){n=await t.evaluate(`() => {
172
+ }`}async function B(t){return await t.evaluate(buildCoverCheckPanelTextJs())||""}async function R(t){let e="",n=!1;for(let i=0;i<E;i+=1){const o=await B(t),l=o.includes("检测中"),r=o.includes("重新检测")||o.includes("横/竖双封面缺失");if(l)n=!0;if(n&&r&&!l)return;e=o;await t.wait({time:0.5})}throw new a("等待抖音封面处理完成超时",e||"unknown")}async function D(t){const e=60;let n=null;for(let i=0;i<e;i+=1){n=await t.evaluate(`() => {
166
173
  const extractCreationId = () => {
167
174
  const titleInput = Array.from(document.querySelectorAll('input')).find(
168
175
  (el) => (el.placeholder || '').includes('填写作品标题')
@@ -212,7 +219,7 @@ import{DOUYIN_VIDEO_ARGS as w,validateDouyinSettings as v,setDouyinPublishSettin
212
219
  text: (btn.textContent || '').trim(),
213
220
  creationId,
214
221
  };
215
- }`);if(n?.ok)break;await t.wait({time:0.5})}if(!n?.ok)throw new a(`点击草稿按钮失败: ${n?.reason||"unknown"}`);if(!n.creationId)throw new a("点击草稿按钮失败: creation-id-missing");return{text:n.text||"暂存离开",creationId:n.creationId}}async function D(t,e){let n={href:"",bodyText:""};for(let o=0;o<40;o+=1){n=await t.evaluate(`() => ({
222
+ }`);if(n?.ok)break;await t.wait({time:0.5})}if(!n?.ok)throw new a(`点击草稿按钮失败: ${n?.reason||"unknown"}`);if(!n.creationId)throw new a("点击草稿按钮失败: creation-id-missing");return{text:n.text||"暂存离开",creationId:n.creationId}}async function H(t,e){let n={href:"",bodyText:""};for(let i=0;i<40;i+=1){n=await t.evaluate(`() => ({
216
223
  href: location.href,
217
224
  bodyText: document.body?.innerText || ''
218
- })`);const i=n.href||"",r=n.bodyText||"",l=i.includes("/creator-micro/content/upload")&&/继续编辑/.test(r),u=/草稿保存成功|已保存到草稿|存草稿成功|保存成功/.test(r),d=/\/creator-micro\/content\/(manage|drafts|works)/.test(i)||/创作中心/.test(r)&&!i.includes("/content/upload");if(l||u||d)return e;await t.wait({time:1})}throw new a("未检测到抖音草稿保存确认",`当前页面: ${n.href||"unknown"}`)}A({site:"douyin",name:"draft",access:"write",description:"上传视频并保存为草稿",domain:"creator.douyin.com",strategy:x.COOKIE,navigateBefore:!1,defaultWindowMode:"foreground",args:[{name:"video",required:!0,positional:!0,help:"视频文件路径"},{name:"title",required:!0,help:"视频标题(≤30字)"},{name:"caption",fromFile:!0,default:"",help:"正文内容(≤1000字,支持 #话题)"},{name:"cover",default:"",help:"封面图片路径"},{name:"visibility",default:"public",choices:["public","friends","private"]},{name:"timeout",type:"int",default:180,help:"命令超时(秒),视频上传/转码慢时可调大"},{name:"ai-generated",type:"boolean",help:"声明内容由 AI 生成(发布和草稿均支持;设置失败时停止提交)"},...w],columns:["status","draft_id"],func:async(t,e)=>{v(e);const n=s.resolve(e.video);if(!m.existsSync(n))throw new c(`视频文件不存在: ${n}`);const o=s.extname(n).toLowerCase();if(![".mp4",".mov",".avi",".webm"].includes(o))throw new c(`不支持的视频格式: ${o}(支持 mp4/mov/avi/webm)`);const i=e.title;if(i.length>30)throw new c("标题不能超过 30 字");const r=e.caption||"";if(r.length>1000)throw new c("正文不能超过 1000 字");const l=e.cover;if(l){if(!m.existsSync(s.resolve(l)))throw new c(`封面文件不存在: ${s.resolve(l)}`)}const u=b[e.visibility]??b.public;await t.goto(T);await t.wait({selector:'input[type="file"]',timeout:20});await y(t);await p(t,'input[type="file"]',[n]);await I(t);await _(t,u);await y(t);if(l){const f=await L(t);await p(t,f.selector,[s.resolve(l)]);if(f.mode==="modal")await M(t);else await P(t)}await q(t,{title:i,caption:r,visibilityLabel:u});await t.wait({time:1});await h(t,{...e,visibility:void 0});const d=await B(t);return[{status:"✅ 草稿已保存,可在创作中心继续编辑",draft_id:await D(t,d.creationId)}]}});
225
+ })`);const o=n.href||"",l=n.bodyText||"",r=o.includes("/creator-micro/content/upload")&&/继续编辑/.test(l),u=/草稿保存成功|已保存到草稿|存草稿成功|保存成功/.test(l),d=/\/creator-micro\/content\/(manage|drafts|works)/.test(o)||/创作中心/.test(l)&&!o.includes("/content/upload");if(r||u||d)return e;await t.wait({time:1})}throw new a("未检测到抖音草稿保存确认",`当前页面: ${n.href||"unknown"}`)}T({site:"douyin",name:"draft",access:"write",description:"上传视频并保存为草稿(草稿不保存定时发布时间,定时请用 publish --schedule)",domain:"creator.douyin.com",strategy:x.COOKIE,navigateBefore:!1,defaultWindowMode:"foreground",args:[{name:"video",required:!0,positional:!0,help:"视频文件路径"},{name:"title",required:!0,help:"视频标题(≤30字)"},{name:"caption",fromFile:!0,default:"",help:"正文内容(≤1000字,支持 #话题)"},{name:"cover",default:"",help:"封面图片路径"},{name:"visibility",default:"public",choices:["public","friends","private"]},{name:"timeout",type:"int",default:180,help:"命令超时(秒),视频上传/转码慢时可调大"},{name:"ai-generated",type:"boolean",help:"声明内容由 AI 生成(发布和草稿均支持;设置失败时停止提交)"},...v.filter((t)=>t.name!=="schedule")],columns:["status","draft_id"],func:async(t,e)=>{h(e);const n=s.resolve(e.video);if(!m.existsSync(n))throw new c(`视频文件不存在: ${n}`);const i=s.extname(n).toLowerCase();if(![".mp4",".mov",".avi",".webm"].includes(i))throw new c(`不支持的视频格式: ${i}(支持 mp4/mov/avi/webm)`);const o=e.title;if(o.length>30)throw new c("标题不能超过 30 字");const l=e.caption||"";if(l.length>1000)throw new c("正文不能超过 1000 字");const r=e.cover;if(r){if(!m.existsSync(s.resolve(r)))throw new c(`封面文件不存在: ${s.resolve(r)}`)}const u=b[e.visibility]??b.public;await t.goto(g);await t.wait({selector:'input[type="file"]',timeout:20});await y(t);await p(t,'input[type="file"]',[n]);await _(t);await q(t,u);await y(t);if(r){const f=await O(t);await p(t,f.selector,[s.resolve(r)]);if(f.mode==="modal")await P(t);else await R(t)}await M(t,{title:o,caption:l,visibilityLabel:u});await t.wait({time:1});await A(t,{...e,visibility:void 0});const d=await D(t);return[{status:"✅ 草稿已保存,可在创作中心继续编辑",draft_id:await H(t,d.creationId)}]}});
@@ -1,11 +1,12 @@
1
- import{DOUYIN_DECLARATION_ARGS as Z,douyinDeclarationInfo as j}from"./_shared/publish-settings.js";import*as T from"node:fs";import*as y from"node:path";import{cli as Q,Strategy as k}from"@jackwener/opencli/registry";import{ArgumentError as l,CliError as ee,CommandExecutionError as w}from"@jackwener/opencli/errors";import{getUploadAuthV5Credentials as te,applyVideoUploadInner as ie,commitVideoUploadInner as oe}from"./_shared/vod-upload.js";import{tosUpload as ne}from"./_shared/tos-upload.js";import{imagexUpload as se}from"./_shared/imagex-upload.js";import{browserFetch as V}from"./_shared/browser-fetch.js";import{generateCreationId as re}from"./_shared/creation-id.js";import{validateTiming as ae,toUnixSeconds as ce}from"./_shared/timing.js";import{parseTextExtra as le,extractHashtagNames as z}from"./_shared/text-extra.js";const de={public:0,friends:2,private:1},me="aid=1128&cookie_enabled=true&screen_width=1512&screen_height=982&browser_language=zh-CN&browser_platform=MacIntel&browser_name=Mozilla&browser_online=true&timezone_name=Asia%2FTokyo&support_h265=1",pe=JSON.stringify({video_cover_source:2,cover_timestamp:0,recommend_timestamp:0,is_cover_edit:0,is_cover_template:0,cover_template_id:"",is_text_template:0,text_template_id:"",text_template_content:"",is_text:0,text_num:0,text_content:"",is_use_sticker:0,sticker_id:"",is_use_filter:0,filter_id:"",is_cover_modify:0,to_status:0,cover_type:0,initial_cover_uri:"",cut_coordinate:""});function _e(i){const e=i instanceof Error?i.message:String(i);return e.includes("post_assistant/fast_detect")&&(e.includes("Empty response")||e.includes("404")||e.includes("Not Found")||e.includes("Timeout")||e.includes("timed out")||e.includes("Failed to fetch"))}function E(i){return new Promise((e)=>setTimeout(e,i))}async function L(i,e,o,n){let c;for(let d=1;d<=3;d+=1)try{return{ok:!0,value:await V(i,e,o,n)}}catch(s){if(!_e(s))throw s;c=s;if(d<3)await E(500*d)}return{ok:!1,error:c}}const A=5;export async function inStage(i,e){try{return await e()}catch(o){if(o instanceof ee)throw o;const n=o instanceof Error?o.message:String(o),c=o?.name==="TimeoutError"?`请求超时(${n})`:n;throw new w(`抖音发布停在「${i}」:${c}`,"这一步在提交发布之前,作品尚未创建,可以直接重试;反复超时多为本机到抖音上传服务的网络慢,可换网络或压缩视频 / 封面后再试。")}}Q({site:"douyin",name:"publish",access:"write",description:"发布视频到抖音(指定 --schedule 定时,或显式 --immediate 立即发布)",domain:"creator.douyin.com",strategy:k.COOKIE,defaultWindowMode:"foreground",args:[{name:"video",required:!0,positional:!0,help:"视频文件路径"},{name:"title",required:!0,help:"视频标题(≤30字)"},{name:"schedule",help:"定时发布时间(ISO8601 或 Unix 秒,2h ~ 14天后),与 --immediate 二选一"},{name:"immediate",type:"boolean",help:"立即发布(必须显式指定,不能与 --schedule 同用)"},{name:"caption",fromFile:!0,default:"",help:"正文内容(≤1000字,支持 #话题)"},{name:"cover",default:"",help:"封面图片路径(不提供时使用视频截帧)"},{name:"visibility",default:"public",choices:["public","friends","private"]},{name:"allow_download",type:"bool",default:!1,help:"允许下载"},{name:"collection",default:"",help:"合集 ID"},{name:"activity",default:"",help:"活动 ID"},{name:"poi_id",default:"",help:"地理位置 ID"},{name:"poi_name",default:"",help:"地理位置名称"},{name:"hotspot",default:"",help:"关联热点词"},{name:"no_safety_check",type:"bool",default:!1,help:"跳过内容安全检测"},{name:"sync_toutiao",type:"bool",default:!1,help:"同步发布到头条"},{name:"ai-generated",type:"boolean",help:"声明内容由 AI 生成(可选,随定时发布请求提交)"},...Z],columns:["status","aweme_id","url","publish_time"],func:async(i,e)=>{const o=j(e);if(!!e.immediate===!!e.schedule)throw new l("必须指定 --schedule 或 --immediate,且只能选择一个");const n=y.resolve(e.video);if(!T.existsSync(n))throw new l(`视频文件不存在: ${n}`);const c=y.extname(n).toLowerCase();if(![".mp4",".mov",".avi",".webm"].includes(c))throw new l(`不支持的视频格式: ${c}(支持 mp4/mov/avi/webm)`);const d=T.statSync(n).size,s=e.title;if(s.length>30)throw new l("标题不能超过 30 字");const a=e.caption||"";if(a.length>1000)throw new l("正文不能超过 1000 字");const U=z(a);if(U.length>A)throw new l(`正文里有 ${U.length} 个 #话题,抖音最多 ${A} 个;删到 ${A} 个以内再发`);const I=e.immediate?0:ce(e.schedule);if(!e.immediate)ae(I);const H=de[e.visibility]??0,g=e.cover;if(g){if(!T.existsSync(y.resolve(g)))throw new l(`封面文件不存在: ${y.resolve(g)}`)}const v=await inStage("获取上传凭证",()=>te(i)),C=await inStage("申请视频上传地址",()=>ie(d,v));let m="",p=720,_=1280;await inStage("上传视频",()=>ne({filePath:n,uploadInfo:C,credentials:v,onProgress:(t,r)=>{const h=Math.round(t/r*100);process.stderr.write(`\r 上传进度: ${h}%`)}}));process.stderr.write(`
1
+ import{DOUYIN_DECLARATION_ARGS as j,douyinDeclarationInfo as Q}from"./_shared/publish-settings.js";import*as A from"node:fs";import*as v from"node:path";import{cli as k,Strategy as ee}from"@jackwener/opencli/registry";import{ArgumentError as m,CliError as te,CommandExecutionError as p}from"@jackwener/opencli/errors";import{getUploadAuthV5Credentials as ie,applyVideoUploadInner as oe,commitVideoUploadInner as re}from"./_shared/vod-upload.js";import{tosUpload as ne}from"./_shared/tos-upload.js";import{imagexUpload as se}from"./_shared/imagex-upload.js";import{browserFetch as J}from"./_shared/browser-fetch.js";import{fetchWorkListPage as ae}from"./_shared/work-list.js";import{generateCreationId as ce}from"./_shared/creation-id.js";import{validateTiming as de,toUnixSeconds as le}from"./_shared/timing.js";import{parseTextExtra as me,extractHashtagNames as L}from"./_shared/text-extra.js";const pe={public:0,friends:2,private:1},ue="aid=1128&cookie_enabled=true&screen_width=1512&screen_height=982&browser_language=zh-CN&browser_platform=MacIntel&browser_name=Mozilla&browser_online=true&timezone_name=Asia%2FTokyo&support_h265=1",_e=JSON.stringify({video_cover_source:2,cover_timestamp:0,recommend_timestamp:0,is_cover_edit:0,is_cover_template:0,cover_template_id:"",is_text_template:0,text_template_id:"",text_template_content:"",is_text:0,text_num:0,text_content:"",is_use_sticker:0,sticker_id:"",is_use_filter:0,filter_id:"",is_cover_modify:0,to_status:0,cover_type:0,initial_cover_uri:"",cut_coordinate:""});function fe(t){const e=t instanceof Error?t.message:String(t);return e.includes("post_assistant/fast_detect")&&(e.includes("Empty response")||e.includes("404")||e.includes("Not Found")||e.includes("Timeout")||e.includes("timed out")||e.includes("Failed to fetch"))}function O(t){return new Promise((e)=>setTimeout(e,t))}async function V(t,e,o,r){let a;for(let n=1;n<=3;n+=1)try{return{ok:!0,value:await J(t,e,o,r)}}catch(c){if(!fe(c))throw c;a=c;if(n<3)await O(500*n)}return{ok:!1,error:a}}const T=5;export function isEmptyCreateResponse(t){return/Douyin API error -2 at POST \S*\/aweme\/create_v2\//.test(t)&&/JSON parse failed: (Unexpected end of JSON input|$)/m.test(t)}export function isSubmittedWork(t,{title:e,timingTs:o,submittedAt:r}){if(!String(t?.desc??"").startsWith(e))return!1;if(o&&Number(t?.timer?.public_time)===o)return!0;return Number(t?.create_time)>=r-120}async function he(t,e){for(const o of[5000,15000]){await O(o);let r;try{({works:r}=await ae(t,{status:0,count:20,cursor:0}))}catch(n){throw new p(`抖音提交发布的接口返回空内容,回查作品列表也失败(${n instanceof Error?n.message:String(n)}),无法确认作品是否已创建`,"不要直接重发:稍后用 `ppcli douyin videos`(定时稿加 --status scheduled)确认没有这条再重试。")}const a=r.find((n)=>isSubmittedWork(n,e));if(a?.aweme_id)return a}return null}export async function inStage(t,e){try{return await e()}catch(o){if(o instanceof te)throw o;const r=o instanceof Error?o.message:String(o),a=o?.name==="TimeoutError"?`请求超时(${r})`:r;throw new p(`抖音发布停在「${t}」:${a}`,"这一步在提交发布之前,作品尚未创建,可以直接重试;反复超时多为本机到抖音上传服务的网络慢,可换网络或压缩视频 / 封面后再试。")}}k({site:"douyin",name:"publish",access:"write",description:"发布视频到抖音(指定 --schedule 定时,或显式 --immediate 立即发布)",domain:"creator.douyin.com",strategy:ee.COOKIE,defaultWindowMode:"foreground",args:[{name:"video",required:!0,positional:!0,help:"视频文件路径"},{name:"title",required:!0,help:"视频标题(≤30字)"},{name:"schedule",help:"定时发布时间(ISO8601 或 Unix 秒,2h ~ 14天后),与 --immediate 二选一"},{name:"immediate",type:"boolean",help:"立即发布(必须显式指定,不能与 --schedule 同用)"},{name:"caption",fromFile:!0,default:"",help:"正文内容(≤1000字,支持 #话题)"},{name:"cover",default:"",help:"封面图片路径(不提供时使用视频截帧)"},{name:"visibility",default:"public",choices:["public","friends","private"]},{name:"allow_download",type:"bool",default:!1,help:"允许下载"},{name:"collection",default:"",help:"合集 ID"},{name:"activity",default:"",help:"活动 ID"},{name:"poi_id",default:"",help:"地理位置 ID"},{name:"poi_name",default:"",help:"地理位置名称"},{name:"hotspot",default:"",help:"关联热点词"},{name:"no_safety_check",type:"bool",default:!1,help:"跳过内容安全检测"},{name:"sync_toutiao",type:"bool",default:!1,help:"同步发布到头条"},{name:"ai-generated",type:"boolean",help:"声明内容由 AI 生成(可选,随定时发布请求提交)"},...j],columns:["status","aweme_id","url","publish_time"],func:async(t,e)=>{const o=Q(e);if(!!e.immediate===!!e.schedule)throw new m("必须指定 --schedule 或 --immediate,且只能选择一个");const r=v.resolve(e.video);if(!A.existsSync(r))throw new m(`视频文件不存在: ${r}`);const a=v.extname(r).toLowerCase();if(![".mp4",".mov",".avi",".webm"].includes(a))throw new m(`不支持的视频格式: ${a}(支持 mp4/mov/avi/webm)`);const n=A.statSync(r).size,c=e.title;if(c.length>30)throw new m("标题不能超过 30 字");const d=e.caption||"";if(d.length>1000)throw new m("正文不能超过 1000 字");const N=L(d);if(N.length>T)throw new m(`正文里有 ${N.length} 个 #话题,抖音最多 ${T} 个;删到 ${T} 个以内再发`);const b=e.immediate?0:le(e.schedule);if(!e.immediate)de(b);const z=pe[e.visibility]??0,g=e.cover;if(g){if(!A.existsSync(v.resolve(g)))throw new m(`封面文件不存在: ${v.resolve(g)}`)}const S=await inStage("获取上传凭证",()=>ie(t)),U=await inStage("申请视频上传地址",()=>oe(n,S));let u="",_=720,f=1280;await inStage("上传视频",()=>ne({filePath:r,uploadInfo:U,credentials:S,onProgress:(i,s)=>{const l=Math.round(i/s*100);process.stderr.write(`\r 上传进度: ${l}%`)}}));process.stderr.write(`
2
2
  `);process.stderr.write(` 提交上传...
3
- `);const u=await inStage("确认视频上传",()=>oe(C,v)),O=u.video_id;process.stderr.write(` 上传已提交: ${O}
4
- `);p=u.width||p;_=u.height||_;if(!m&&u.poster_uri)m=u.poster_uri;if(e.cover){process.stderr.write(` 上传封面...
5
- `);const t=await inStage("上传封面",()=>se(y.resolve(e.cover),v));m=t.uri;p=t.width||p;_=t.height||_;process.stderr.write(` 封面已上传: ${m}
6
- `)}if(!e.no_safety_check){const t="https://creator.douyin.com/aweme/v1/post_assistant/fast_detect/pre_check",r={video_id:O,title:s,desc:a},h=await L(i,"POST",t,{body:r});if(!h.ok)process.stderr.write(` 内容安全预检接口无响应,继续轮询检测结果。
7
- `);const K="https://creator.douyin.com/aweme/v1/post_assistant/fast_detect/poll",X=Date.now()+30000;let M=!1,S=0;while(Date.now()<X){const R=await L(i,"POST",K,{body:r});if(!R.ok){S+=1;if(!h.ok&&S>=3)break;await E(2000);continue}S=0;const f=R.value;if(f.status===0||f.has_done===!0&&f.detect_result?.reason_code===0&&(f.detect_list?.length??0)===0){M=!0;break}if(f.status===1)throw new w("内容安全检测不通过,请修改后重试","使用 --no_safety_check 跳过");await E(2000)}if(!M)if(!h.ok&&S>=3)process.stderr.write(` 内容安全预检持续无响应,跳过本地预检,交由 create_v2 后的平台审核。
8
- `);else throw new w("内容安全检测超时(30s),请稍后重试","如确认要跳过本地预检,可使用 --no_safety_check;提交后仍会走抖音平台审核")}const J=z(a),N=[];let D=0;for(const t of J){const r=a.indexOf(`#${t}`,D);if(r===-1)continue;N.push({name:t,id:0,start:r,end:r+t.length+1});D=r+t.length+1}const F=a?`${s} ${a}`:s,P=a?s.length+1:0,B=le(F,N.map((t)=>({...t,start:t.start+P,end:t.end+P}))),q={item:{common:{text:F,caption:a,item_title:s,activity:JSON.stringify(e.activity?[e.activity]:[]),text_extra:JSON.stringify(B),challenges:"[]",mentions:"[]",hashtag_source:"",hot_sentence:e.hotspot||"",interaction_stickers:"[]",visibility_type:H,download:e.allow_download?1:0,timing:I,creation_id:re(),media_type:4,video_id:O,music_source:0,music_id:null,...e.poi_id?{poi_id:e.poi_id,poi_name:e.poi_name}:{}},cover:{poster:m,custom_cover_image_height:_,custom_cover_image_width:p,poster_delay:0,cover_tools_info:pe,cover_tools_extend_info:"{}"},mix:e.collection?{mix_id:e.collection,mix_order:0}:{},chapter:{chapter:JSON.stringify({chapter_abstract:"",chapter_details:[],chapter_type:0})},anchor:{},sync:{should_sync:!1,sync_to_toutiao:e.sync_toutiao?1:0},open_platform:{},assistant:{is_preview:0,is_post_assistant:1},declare:{user_declare_info:o}}},G=`https://creator.douyin.com/web/api/media/aweme/create_v2/?read_aid=2906&${me}`;process.stderr.write(e.immediate?` 创建发布...
3
+ `);const h=await inStage("确认视频上传",()=>re(U,S)),E=h.video_id;process.stderr.write(` 上传已提交: ${E}
4
+ `);_=h.width||_;f=h.height||f;if(!u&&h.poster_uri)u=h.poster_uri;if(e.cover){process.stderr.write(` 上传封面...
5
+ `);const i=await inStage("上传封面",()=>se(v.resolve(e.cover),S));u=i.uri;_=i.width||_;f=i.height||f;process.stderr.write(` 封面已上传: ${u}
6
+ `)}if(!e.no_safety_check){const i="https://creator.douyin.com/aweme/v1/post_assistant/fast_detect/pre_check",s={video_id:E,title:c,desc:d},l=await V(t,"POST",i,{body:s});if(!l.ok)process.stderr.write(` 内容安全预检接口无响应,继续轮询检测结果。
7
+ `);const X="https://creator.douyin.com/aweme/v1/post_assistant/fast_detect/poll",Z=Date.now()+30000;let M=!1,I=0;while(Date.now()<Z){const R=await V(t,"POST",X,{body:s});if(!R.ok){I+=1;if(!l.ok&&I>=3)break;await O(2000);continue}I=0;const y=R.value;if(y.status===0||y.has_done===!0&&y.detect_result?.reason_code===0&&(y.detect_list?.length??0)===0){M=!0;break}if(y.status===1)throw new p("内容安全检测不通过,请修改后重试","使用 --no_safety_check 跳过");await O(2000)}if(!M)if(!l.ok&&I>=3)process.stderr.write(` 内容安全预检持续无响应,跳过本地预检,交由 create_v2 后的平台审核。
8
+ `);else throw new p("内容安全检测超时(30s),请稍后重试","如确认要跳过本地预检,可使用 --no_safety_check;提交后仍会走抖音平台审核")}const W=L(d),C=[];let D=0;for(const i of W){const s=d.indexOf(`#${i}`,D);if(s===-1)continue;C.push({name:i,id:0,start:s,end:s+i.length+1});D=s+i.length+1}const P=d?`${c} ${d}`:c,F=d?c.length+1:0,H=me(P,C.map((i)=>({...i,start:i.start+F,end:i.end+F}))),B={item:{common:{text:P,caption:d,item_title:c,activity:JSON.stringify(e.activity?[e.activity]:[]),text_extra:JSON.stringify(H),challenges:"[]",mentions:"[]",hashtag_source:"",hot_sentence:e.hotspot||"",interaction_stickers:"[]",visibility_type:z,download:e.allow_download?1:0,timing:b,creation_id:ce(),media_type:4,video_id:E,music_source:0,music_id:null,...e.poi_id?{poi_id:e.poi_id,poi_name:e.poi_name}:{}},cover:{poster:u,custom_cover_image_height:f,custom_cover_image_width:_,poster_delay:0,cover_tools_info:_e,cover_tools_extend_info:"{}"},mix:e.collection?{mix_id:e.collection,mix_order:0}:{},chapter:{chapter:JSON.stringify({chapter_abstract:"",chapter_details:[],chapter_type:0})},anchor:{},sync:{should_sync:!1,sync_to_toutiao:e.sync_toutiao?1:0},open_platform:{},assistant:{is_preview:0,is_post_assistant:1},declare:{user_declare_info:o}}},q=`https://creator.douyin.com/web/api/media/aweme/create_v2/?read_aid=2906&${ue}`;process.stderr.write(e.immediate?` 创建发布...
9
9
  `:` 创建定时发布...
10
- `);let b;try{b=await V(i,"POST",G,{body:q})}catch(t){if((t instanceof Error?t.message:String(t)).includes("Failed to fetch"))throw new w("提交发布请求被浏览器侧拦截(疑似字节安全组件 secsdk)","不要直接重试:先用 `ppcli douyin videos` / 创作者中心确认作品是否已创建,避免重复投稿。"+"确认未创建后,用 `--window foreground` 前台窗口重试(视频已上传成功的部分无需重传)。");throw t}const x=b.aweme_id??b.item_id;if(!x)throw new w(`发布成功但未返回 aweme_id/item_id: ${JSON.stringify(b)}`);const W=`https://www.douyin.com/video/${x}`,Y=e.immediate?"立即发布":new Date(I*1000).toLocaleString("zh-CN",{timeZone:"Asia/Shanghai"});if(!e.immediate)process.stderr.write(` 定时稿已创建,到点前作品链接不可访问。核对:ppcli douyin videos --status scheduled(应能看到 ${x} 及计划时间)。
11
- `);return[{status:e.immediate?"✅ 发布请求已提交":"✅ 定时发布成功!",aweme_id:x,url:W,publish_time:Y}]}});
10
+ `);let w;const G=Math.floor(Date.now()/1000);try{w=await J(t,"POST",q,{body:B})}catch(i){const s=i instanceof Error?i.message:String(i);if(isEmptyCreateResponse(s)){const l=await he(t,{title:c,timingTs:b,submittedAt:G});if(!l)throw new p("抖音没有创建作品:提交发布的接口返回空内容,回查作品列表也没有这条(可放心重发,不会重复)","多为账号此时需要本人验证(短信 / 扫码)或平台临时拦截了接口提交。改用 `ppcli douyin draft` 存草稿,再在创作中心打开草稿点「发布」,按页面提示完成验证;验证通过后 publish 通常恢复。");w={aweme_id:l.aweme_id};process.stderr.write(` 提交接口返回空内容,但作品列表已有这条(${l.aweme_id})。
11
+ `)}else if(s.includes("Failed to fetch"))throw new p("提交发布请求被浏览器侧拦截(疑似字节安全组件 secsdk)","不要直接重试:先用 `ppcli douyin videos` / 创作者中心确认作品是否已创建,避免重复投稿。"+"确认未创建后,用 `--window foreground` 前台窗口重试(视频已上传成功的部分无需重传)。");else throw i}const x=w.aweme_id??w.item_id;if(!x)throw new p(`发布成功但未返回 aweme_id/item_id: ${JSON.stringify(w)}`);const Y=`https://www.douyin.com/video/${x}`,K=e.immediate?"立即发布":new Date(b*1000).toLocaleString("zh-CN",{timeZone:"Asia/Shanghai"});if(!e.immediate)process.stderr.write(` 定时稿已创建,到点前作品链接不可访问。核对:ppcli douyin videos --status scheduled(应能看到 ${x} 及计划时间)。
12
+ `);return[{status:e.immediate?"✅ 发布请求已提交":"✅ 定时发布成功!",aweme_id:x,url:Y,publish_time:K}]}});
@@ -1,4 +1,4 @@
1
- import*as ae from"node:fs";import*as C from"node:path";import{cli as oe,Strategy as le}from"@jackwener/opencli/registry";import{ArgumentError as f,AuthRequiredError as se,CommandExecutionError as c}from"@jackwener/opencli/errors";import{injectInputFiles as ue}from"../_shared/file-inject.js";const I="https://channels.weixin.qq.com/platform/post/create",ce=[".post-short-title-wrap input",'input[placeholder*="短标题"]','input[placeholder*="填写短标题"]','input.weui-desktop-form__input[placeholder*="短标题"]',"input.weui-desktop-form__input"],de=[".post-desc-box .input-editor",'div[contenteditable][data-placeholder="添加描述"]','div.input-editor[contenteditable=""][data-placeholder="添加描述"]','div[data-placeholder*="描述"][contenteditable]',"div.input-editor[contenteditable]"],fe=["span.add-icon.weui-icon-outlined-add","div.upload-content",".finder-video-upload-btn"],pe=new Set([".mp4",".mov",".avi",".webm"]),me=['.post-upload-wrap input[type="file"]','input[type="file"][accept*="video"]','input[type="file"]'],T="https://channels.weixin.qq.com/platform/post/list",j=/^[\u2103\u4E00-\u9FA5A-Za-z0-9《》""“”::+??%\s]+$/,F=16,L=6;function Q(e){if(!e)return;if(e.length>F)throw new f(`短标题超过 ${F} 字限制(当前 ${e.length} 字)`);if(e.length<L)throw new f(`短标题至少 ${L} 个字(当前 ${e.length} 字)`);if(!j.test(e)){const t=Array.from(new Set(Array.from(e).filter((i)=>!j.test(i)))).join(" ");throw new f(`短标题包含平台不接受的字符: ${t}`,"短标题只能用中文、英文字母、数字、空格,符号仅支持书名号、引号、冒号、加号、问号、百分号、摄氏度;逗号请改用空格")}}function he(e){if(e&&typeof e==="object"&&"data"in e&&"session"in e)return e.data;return e}async function d(e,t){return he(await e.evaluate(t))}function B(e,t,i){const r=C.resolve(String(e));let n;try{n=ae.statSync(r)}catch{throw new f(`${t}文件不存在: ${r}`)}if(!n.isFile())throw new f(`${t}路径不是文件: ${r}`);const a=C.extname(r).toLowerCase();if(!i.has(a))throw new f(`不支持的${t}格式: ${a}(支持 ${Array.from(i).join("/")})`);return r}function G(e){const t=e==null||e===""?600:Number(e);if(!Number.isInteger(t)||t<30)throw new f("--timeout must be an integer >= 30 seconds");return t}function H(e){if(!e)return null;const t=typeof e==="number"?new Date(e<1000000000000?e*1000:e):new Date(String(e));if(Number.isNaN(t.getTime()))throw new f(`无法解析定时时间: ${e}`);if(t.getTime()<=Date.now())throw new f("定时时间必须晚于当前时间");t.setSeconds(0,0);return t}function D(e){return e===!0||e==="true"||e==="1"||e===1}function we(e,t){const i=e-Date.now();if(i<=0)throw new c(`${t}超时,请增加 --timeout 后重试`);return i}function U({isDraft:e,finalUrl:t,successMsg:i}){const r=String(i||"");if(e)return/已保存|暂存成功|保存成功/.test(r);if(/已发表|发布成功|发表成功|审核中/.test(r))return!0;const n=String(t||"");return/\/platform\/post\/list\b/.test(n)}const p=`
1
+ import*as le from"node:fs";import*as q from"node:path";import{cli as se,Strategy as ue}from"@jackwener/opencli/registry";import{ArgumentError as p,AuthRequiredError as ce,CommandExecutionError as c}from"@jackwener/opencli/errors";import{injectInputFiles as de}from"../_shared/file-inject.js";const O="https://channels.weixin.qq.com/platform/post/create",fe=[".post-short-title-wrap input",'input[placeholder*="短标题"]','input[placeholder*="填写短标题"]','input.weui-desktop-form__input[placeholder*="短标题"]',"input.weui-desktop-form__input"],pe=[".post-desc-box .input-editor",'div[contenteditable][data-placeholder="添加描述"]','div.input-editor[contenteditable=""][data-placeholder="添加描述"]','div[data-placeholder*="描述"][contenteditable]',"div.input-editor[contenteditable]"],me=["span.add-icon.weui-icon-outlined-add","div.upload-content",".finder-video-upload-btn"],he=new Set([".mp4",".mov",".avi",".webm"]),we=['.post-upload-wrap input[type="file"]','input[type="file"][accept*="video"]','input[type="file"]'],T="https://channels.weixin.qq.com/platform/post/list",F=/^[\u2103\u4E00-\u9FA5A-Za-z0-9《》""“”::+??%\s]+$/,L=16,Q=6;function B(e){if(!e)return;if(e.length>L)throw new p(`短标题超过 ${L} 字限制(当前 ${e.length} 字)`);if(e.length<Q)throw new p(`短标题至少 ${Q} 个字(当前 ${e.length} 字)`);if(!F.test(e)){const t=Array.from(new Set(Array.from(e).filter((i)=>!F.test(i)))).join(" ");throw new p(`短标题包含平台不接受的字符: ${t}`,"短标题只能用中文、英文字母、数字、空格,符号仅支持书名号、引号、冒号、加号、问号、百分号、摄氏度;逗号请改用空格")}}function be(e){if(e&&typeof e==="object"&&"data"in e&&"session"in e)return e.data;return e}async function d(e,t){return be(await e.evaluate(t))}function H(e,t,i){const r=q.resolve(String(e));let n;try{n=le.statSync(r)}catch{throw new p(`${t}文件不存在: ${r}`)}if(!n.isFile())throw new p(`${t}路径不是文件: ${r}`);const a=q.extname(r).toLowerCase();if(!i.has(a))throw new p(`不支持的${t}格式: ${a}(支持 ${Array.from(i).join("/")})`);return r}function U(e){const t=e==null||e===""?600:Number(e);if(!Number.isInteger(t)||t<30)throw new p("--timeout must be an integer >= 30 seconds");return t}function G(e){if(!e)return null;const t=typeof e==="number"?new Date(e<1000000000000?e*1000:e):new Date(String(e));if(Number.isNaN(t.getTime()))throw new p(`无法解析定时时间: ${e}`);if(t.getTime()<=Date.now())throw new p("定时时间必须晚于当前时间");t.setSeconds(0,0);return t}function N(e){return e===!0||e==="true"||e==="1"||e===1}function ve(e,t){const i=e-Date.now();if(i<=0)throw new c(`${t}超时,请增加 --timeout 后重试`);return i}function J({isDraft:e,finalUrl:t,successMsg:i}){const r=String(i||"");if(e)return/已保存|暂存成功|保存成功/.test(r);if(/已发表|发布成功|发表成功|审核中/.test(r))return!0;const n=String(t||"");return/\/platform\/post\/list\b/.test(n)}const f=`
2
2
  function wujieRoot() {
3
3
  var w = document.querySelector('wujie-app');
4
4
  return (w && w.shadowRoot) || null;
@@ -45,7 +45,7 @@ import*as ae from"node:fs";import*as C from"node:path";import{cli as oe,Strategy
45
45
  }
46
46
  return null;
47
47
  }
48
- `,O=`
48
+ `,M=`
49
49
  function vmOf(el) {
50
50
  while (el) {
51
51
  if (el.__vue__) return el.__vue__;
@@ -110,10 +110,10 @@ import*as ae from"node:fs";import*as C from"node:path";import{cli as oe,Strategy
110
110
  titleError: titleErrEl ? (titleErrEl.innerText || titleErrEl.textContent || '').trim() : '',
111
111
  };
112
112
  }
113
- `;async function N(e){return d(e,`(() => { ${p} ${V} ${O} return readFormState(); })()`)}function J(e){if(!e)return{known:!1,seconds:null};const t=e.effectiveTime,i=t===null||typeof t==="number",r=i&&t?t:null,n=e.schedule,a=!!n&&Number.isFinite(n.time);let o=null;if(a&&n.checked&&n.time){const l=Number.isFinite(n.minTime)?Math.max(n.time,n.minTime):n.time;o=Math.floor(l/1000)}if(i&&a&&r!==o)return{known:!0,conflict:!0,seconds:r??o,formSeconds:r,pickerSeconds:o};if(i)return{known:!0,seconds:r};if(a)return{known:!0,seconds:o};return{known:!1,seconds:null}}function _(e){const t=new Date(e*1000),i=(r)=>String(r).padStart(2,"0");return`${t.getFullYear()}-${i(t.getMonth()+1)}-${i(t.getDate())} ${i(t.getHours())}:${i(t.getMinutes())}`}function q(e,{targetSeconds:t,isDraft:i}){if(e?.titleError)return`平台拒绝了短标题: ${e.titleError}`;if(Array.isArray(e?.files)){if(e.files.length===0)return"视频上传失败:上传区是空的,文件没有进入页面的上传队列";if(e.files.some((a)=>a.status==="error"))return"视频上传失败:页面把文件标记为上传出错";const n=e.files.filter((a)=>a.status!=="done");if(n.length)return`视频还没上传完成(状态 ${n.map((a)=>`${a.status||"未知"} ${a.percent}%`).join(", ")})`}const r=J(e);if(r.conflict){const n=(a)=>a?_(a):"不定时";return`表单内部的定时值互相矛盾(表单 ${n(r.formSeconds)} / 时间选择器 ${n(r.pickerSeconds)}),为避免错时发布已中止`}if(t){if(!r.known)return"无法回读表单里的定时发表时间,为避免错时发布已中止";if(r.seconds!==t)return`表单里的定时发表时间与目标不一致:目标 ${_(t)},表单实际 ${r.seconds?_(r.seconds):"不定时"},为避免错时发布已中止`;if(e.isEffectiveTimeValid===!1)return"页面判定定时发表时间不合法,已中止"}else if(r.known&&r.seconds)return`表单处于定时发表状态(${_(r.seconds)}),但本次没有指定 --schedule,已中止`;if(i&&e?.isPostByTime)return"定时发表状态下平台不允许保存草稿";return null}async function be(e){return await d(e,`
113
+ `;async function C(e){return d(e,`(() => { ${f} ${V} ${M} return readFormState(); })()`)}function Y(e){if(!e)return{known:!1,seconds:null};const t=e.effectiveTime,i=t===null||typeof t==="number",r=i&&t?t:null,n=e.schedule,a=!!n&&Number.isFinite(n.time);let o=null;if(a&&n.checked&&n.time){const l=Number.isFinite(n.minTime)?Math.max(n.time,n.minTime):n.time;o=Math.floor(l/1000)}if(i&&a&&r!==o)return{known:!0,conflict:!0,seconds:r??o,formSeconds:r,pickerSeconds:o};if(i)return{known:!0,seconds:r};if(a)return{known:!0,seconds:o};return{known:!1,seconds:null}}function y(e){const t=new Date(e*1000),i=(r)=>String(r).padStart(2,"0");return`${t.getFullYear()}-${i(t.getMonth()+1)}-${i(t.getDate())} ${i(t.getHours())}:${i(t.getMinutes())}`}function R(e,{targetSeconds:t,isDraft:i}){if(e?.titleError)return`平台拒绝了短标题: ${e.titleError}`;if(Array.isArray(e?.files)){if(e.files.length===0)return"视频上传失败:上传区是空的,文件没有进入页面的上传队列";if(e.files.some((a)=>a.status==="error"))return"视频上传失败:页面把文件标记为上传出错";const n=e.files.filter((a)=>a.status!=="done");if(n.length)return`视频还没上传完成(状态 ${n.map((a)=>`${a.status||"未知"} ${a.percent}%`).join(", ")})`}const r=Y(e);if(r.conflict){const n=(a)=>a?y(a):"不定时";return`表单内部的定时值互相矛盾(表单 ${n(r.formSeconds)} / 时间选择器 ${n(r.pickerSeconds)}),为避免错时发布已中止`}if(t){if(!r.known)return"无法回读表单里的定时发表时间,为避免错时发布已中止";if(r.seconds!==t)return`表单里的定时发表时间与目标不一致:目标 ${y(t)},表单实际 ${r.seconds?y(r.seconds):"不定时"},为避免错时发布已中止`;if(e.isEffectiveTimeValid===!1)return"页面判定定时发表时间不合法,已中止"}else if(r.known&&r.seconds)return`表单处于定时发表状态(${y(r.seconds)}),但本次没有指定 --schedule,已中止`;if(i&&e?.isPostByTime)return"定时发表状态下平台不允许保存草稿";return null}async function ge(e){return await d(e,`
114
114
  (() => {
115
- ${p}
116
- var sels = ${JSON.stringify(fe)};
115
+ ${f}
116
+ var sels = ${JSON.stringify(me)};
117
117
  for (var i = 0; i < sels.length; i++) {
118
118
  var el = deepQuery(sels[i]);
119
119
  if (el && isVisible(el)) {
@@ -123,17 +123,31 @@ import*as ae from"node:fs";import*as C from"node:path";import{cli as oe,Strategy
123
123
  }
124
124
  return { ok: false };
125
125
  })()
126
- `)}async function ve(e,t=15000){const i=500,r=Math.max(1,Math.ceil(t/i));for(let n=0;n<r;n++){if(await d(e,`
126
+ `)}async function m(e,t){const i=Promise.resolve().then(()=>e.screenshot({path:t}));let r;const n=new Promise((a,o)=>{r=setTimeout(()=>o(Error("8 秒内未完成")),8000)});try{await Promise.race([i,n]);return!0}catch(a){i.catch((o)=>process.stderr.write(` 排障截图 ${t} 最终失败: ${o instanceof Error?o.message:String(o)}
127
+ `));process.stderr.write(` 排障截图 ${t} 未保存: ${a instanceof Error?a.message:String(a)}
128
+ `);return!1}finally{clearTimeout(r)}}const W=`(() => {
129
+ ${f}
130
+ var w = document.querySelector('wujie-app');
131
+ var sr = w && w.shadowRoot;
132
+ return {
133
+ wujie: !!w,
134
+ shadowNodes: sr ? sr.querySelectorAll('*').length : 0,
135
+ fileInput: !!deepQuery('input[type="file"]'),
136
+ url: location.href,
137
+ title: document.title,
138
+ bodyText: (document.body && document.body.innerText || '').trim().slice(0, 160),
139
+ };
140
+ })()`;async function _e(e,t=30000){const i=Math.max(1,Math.ceil(t/1000));let r=null;for(let n=0;n<i;n++){r=await d(e,W);if(r&&(r.fileInput||r.shadowNodes>20))return r;if(n<i-1)await e.wait({time:1})}throw new c(`视频号发布页没有渲染出来:${Math.round(t/1000)} 秒内页面里没有发布表单(${r?.wujie?"wujie 子应用已挂载但内容为空":"子应用未挂载"};标题「${r?.title||""}」,正文「${r?.bodyText||""}」)`,"本次没有上传也没有提交,可以直接重试。反复出现时在专用浏览器里手动打开 "+O+",看能否显示上传区:显示不出来多为本机网络加载不了视频号页面脚本(代理 / 防火墙拦了 res.wx.qq.com 等域名),或浏览器渲染卡住,可执行 `ppcli profile stop <名称>` 后重跑。")}async function ye(e,t=15000){const i=500,r=Math.max(1,Math.ceil(t/i));for(let n=0;n<r;n++){if(await d(e,`
127
141
  (() => {
128
- ${p}
142
+ ${f}
129
143
  var inputSels = ['input[type="file"][accept*="video"]', 'input[type="file"]'];
130
144
  for (var i = 0; i < inputSels.length; i++) {
131
145
  if (deepQuery(inputSels[i])) return true;
132
146
  }
133
147
  return false;
134
148
  })()
135
- `))return!0;if(n<r-1)await e.wait({time:i/1000})}return!1}const Y=`((sel) => {
136
- ${p}
149
+ `))return!0;if(n<r-1)await e.wait({time:i/1000})}return!1}const K=`((sel) => {
150
+ ${f}
137
151
  var real = deepQuery(sel);
138
152
  if (!real) return null;
139
153
  var win = (real.ownerDocument && real.ownerDocument.defaultView) || window;
@@ -162,11 +176,11 @@ import*as ae from"node:fs";import*as C from"node:path";import{cli as oe,Strategy
162
176
  return real.dispatchEvent(new win.Event(ev.type, { bubbles: true }));
163
177
  },
164
178
  };
165
- })`;async function ge(e,t){await be(e);await e.wait({time:1});await ve(e);let i;for(const r of me)try{await ue(e,r,[t],{findInputJs:Y});const n=await d(e,"(() => { var r = window.__ppWxInject || null; delete window.__ppWxInject; return r; })()");if(!n||n.error||n.count!==1||!n.realm)throw new c(`文件没能交给页面的上传控件: ${n?.error||`count=${n?.count??"未知"} realm=${n?.realm??"未知"}`}`);return}catch(n){i=n;if(!(n instanceof Error?n.message:String(n)).includes("未找到文件上传输入框"))break}await e.screenshot({path:"/tmp/wechat-channels_publish_upload_debug.png"});throw new c(`视频文件注入失败: ${i instanceof Error?i.message:String(i)}
166
- 截图已保存到 /tmp/wechat-channels_publish_upload_debug.png`)}function W(e){if(!Array.isArray(e))return"unknown";if(e.length===0)return"empty";if(e.some((t)=>t.status==="error"))return"error";return e.every((t)=>t.status==="done")?"done":"pending"}async function _e(e,t,i=180000){const r=3000,n=Math.ceil(i/r),a=Math.ceil(20000/r);let o=0;for(let l=0;l<n;l++){let s;try{s=await d(e,`
179
+ })`;async function ke(e,t){await ge(e);await e.wait({time:1});await ye(e);let i;for(const r of we)try{await de(e,r,[t],{findInputJs:K});const n=await d(e,"(() => { var r = window.__ppWxInject || null; delete window.__ppWxInject; return r; })()");if(!n||n.error||n.count!==1||!n.realm)throw new c(`文件没能交给页面的上传控件: ${n?.error||`count=${n?.count??"未知"} realm=${n?.realm??"未知"}`}`);return}catch(n){i=n;if(!(n instanceof Error?n.message:String(n)).includes("未找到文件上传输入框"))break}await m(e,"/tmp/wechat-channels_publish_upload_debug.png");throw new c(`视频文件注入失败: ${i instanceof Error?i.message:String(i)}
180
+ 截图已保存到 /tmp/wechat-channels_publish_upload_debug.png`)}function X(e){if(!Array.isArray(e))return"unknown";if(e.length===0)return"empty";if(e.some((t)=>t.status==="error"))return"error";return e.every((t)=>t.status==="done")?"done":"pending"}async function Se(e,t,i=180000){const r=3000,n=Math.ceil(i/r),a=Math.ceil(20000/r);let o=0;for(let l=0;l<n;l++){let s;try{s=await d(e,`
167
181
  ((fileName) => {
168
- ${p}
169
- ${O}
182
+ ${f}
183
+ ${M}
170
184
  var files = readFormState().files;
171
185
  if (Array.isArray(files)) return { files: files };
172
186
 
@@ -185,10 +199,10 @@ import*as ae from"node:fs";import*as C from"node:path";import{cli as oe,Strategy
185
199
  var hasFileEvidence = fileName && bodyText.indexOf(fileName) >= 0;
186
200
  return { done: !uploading && (preview || hasFileEvidence), failed: false };
187
201
  })(${JSON.stringify(t)})
188
- `)}catch(u){const h=u instanceof Error?u.message:String(u);if(h.includes("ECONNRESET")||h.includes("fetch failed")){process.stderr.write(` [retry] bridge reconnecting after page re-render (${l+1}/${n})...
189
- `);await e.wait({time:r/1000});continue}throw u}const m=W(s?.files);if(m==="error"||s?.failed){await e.screenshot({path:"/tmp/wechat-channels_publish_upload_debug.png"});throw new c("视频上传失败:页面把文件标记为上传出错,请检查文件格式和网络连接","截图: /tmp/wechat-channels_publish_upload_debug.png。本次没有提交任何内容,可以直接重试")}if(m==="done"||m==="unknown"&&s?.done)return;if(m==="empty"){o+=1;if(o>=a){await e.screenshot({path:"/tmp/wechat-channels_publish_upload_debug.png"});throw new c("视频上传失败:文件已注入但页面上传区仍为空,页面没有收下这个文件","截图: /tmp/wechat-channels_publish_upload_debug.png。本次没有提交任何内容,可以直接重试;反复出现说明视频号上传控件改版")}}else o=0;await e.wait({time:r/1000})}throw new c(`视频上传/转码超时(${Math.ceil(i/1000)}秒),请检查网络或稍后重试`)}async function K(e,t,i,r){const n=30;let a;for(let o=0;o<n;o++){a=await d(e,`
202
+ `)}catch(u){const w=u instanceof Error?u.message:String(u);if(w.includes("ECONNRESET")||w.includes("fetch failed")){process.stderr.write(` [retry] bridge reconnecting after page re-render (${l+1}/${n})...
203
+ `);await e.wait({time:r/1000});continue}throw u}const h=X(s?.files);if(h==="error"||s?.failed){await m(e,"/tmp/wechat-channels_publish_upload_debug.png");throw new c("视频上传失败:页面把文件标记为上传出错,请检查文件格式和网络连接","截图: /tmp/wechat-channels_publish_upload_debug.png。本次没有提交任何内容,可以直接重试")}if(h==="done"||h==="unknown"&&s?.done)return;if(h==="empty"){o+=1;if(o>=a){await m(e,"/tmp/wechat-channels_publish_upload_debug.png");throw new c("视频上传失败:文件已注入但页面上传区仍为空,页面没有收下这个文件","截图: /tmp/wechat-channels_publish_upload_debug.png。本次没有提交任何内容,可以直接重试;反复出现说明视频号上传控件改版")}}else o=0;await e.wait({time:r/1000})}throw new c(`视频上传/转码超时(${Math.ceil(i/1000)}秒),请检查网络或稍后重试`)}async function z(e,t,i,r){const n=30;let a;for(let o=0;o<n;o++){a=await d(e,`
190
204
  (function(selectors, text) {
191
- ${p}
205
+ ${f}
192
206
 
193
207
  var el = null;
194
208
  var foundSel = null;
@@ -233,10 +247,10 @@ import*as ae from"node:fs";import*as C from"node:path";import{cli as oe,Strategy
233
247
  el.blur();
234
248
  return { ok: actual.indexOf(text) >= 0, sel: foundSel, actual: actual };
235
249
  })(${JSON.stringify(t)}, ${JSON.stringify(i)})
236
- `);if(a?.ok)break;if(o<n-1)await e.wait({time:0.5})}if(!a?.ok){await e.screenshot({path:`/tmp/wechat-channels_publish_${r}_debug.png`});throw new c(`找不到 ${r} 输入框,截图已保存到 /tmp/wechat-channels_publish_${r}_debug.png`)}}const X=`
250
+ `);if(a?.ok)break;if(o<n-1)await e.wait({time:0.5})}if(!a?.ok){await m(e,`/tmp/wechat-channels_publish_${r}_debug.png`);throw new c(`找不到 ${r} 输入框,截图已保存到 /tmp/wechat-channels_publish_${r}_debug.png`)}}const Z=`
237
251
  (async function(TY, TM, TD, TH, TMin, TARGET_MS) {
238
- ${p}
239
- ${O}
252
+ ${f}
253
+ ${M}
240
254
  function sleep(ms) { return new Promise(function(r) { setTimeout(r, ms); }); }
241
255
  function click(el) {
242
256
  el.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true, view: window }));
@@ -385,10 +399,10 @@ import*as ae from"node:fs";import*as C from"node:path";import{cli as oe,Strategy
385
399
  var inp = dateDl.querySelector('dt input') || deepQuery('input[placeholder*="发表时间"]');
386
400
  return { ok: true, value: inp ? inp.value : null, pick: pickOf(), commit: commit.join('+'), state: readFormState() };
387
401
  })
388
- `;async function ye(e,t){const i=t.getFullYear(),r=t.getMonth()+1,n=t.getDate(),a=t.getHours(),o=t.getMinutes(),l=(y)=>String(y).padStart(2,"0"),s=t.getTime(),m=Math.floor(s/1000),u=await d(e,`${X}(${i}, ${r}, ${n}, ${a}, ${o}, ${s})`);if(!u?.ok){await e.screenshot({path:"/tmp/wechat-channels_schedule_debug.png"});const y=u?.reason?String(u.reason):"empty picker result";if(y==="timezone-mismatch")throw new c("定时设置失败:浏览器与命令行所在时区不一致,无法按钟点可靠地选中目标时刻,已中止");throw new c(`定时设置失败 (${y}),截图: /tmp/wechat-channels_schedule_debug.png`)}const h=`${i}-${l(r)}-${l(n)} ${l(a)}:${l(o)}`,w=[];if(!String(u.value||"").includes(h))w.push(`显示框=${u.value||"空"}`);if(u.pick!=null&&Math.floor(u.pick/1000)!==m)w.push(`时间选择器选中=${_(Math.floor(u.pick/1000))}`);const k=q({...u.state,files:null,titleError:""},{targetSeconds:m,isDraft:!1});if(k)w.push(k);if(w.length){await e.screenshot({path:"/tmp/wechat-channels_schedule_debug.png"});throw new c(`定时设置未验证成功: 目标=${h};${w.join(";")}`,"本次没有提交任何内容。截图: /tmp/wechat-channels_schedule_debug.png")}process.stderr.write(` 定时设置完成: ${u.value||h}(表单回读一致)
389
- `)}const z=`
402
+ `;async function Te(e,t){const i=t.getFullYear(),r=t.getMonth()+1,n=t.getDate(),a=t.getHours(),o=t.getMinutes(),l=(k)=>String(k).padStart(2,"0"),s=t.getTime(),h=Math.floor(s/1000),u=await d(e,`${Z}(${i}, ${r}, ${n}, ${a}, ${o}, ${s})`);if(!u?.ok){await m(e,"/tmp/wechat-channels_schedule_debug.png");const k=u?.reason?String(u.reason):"empty picker result";if(k==="timezone-mismatch")throw new c("定时设置失败:浏览器与命令行所在时区不一致,无法按钟点可靠地选中目标时刻,已中止");throw new c(`定时设置失败 (${k}),截图: /tmp/wechat-channels_schedule_debug.png`)}const w=`${i}-${l(r)}-${l(n)} ${l(a)}:${l(o)}`,b=[];if(!String(u.value||"").includes(w))b.push(`显示框=${u.value||"空"}`);if(u.pick!=null&&Math.floor(u.pick/1000)!==h)b.push(`时间选择器选中=${y(Math.floor(u.pick/1000))}`);const S=R({...u.state,files:null,titleError:""},{targetSeconds:h,isDraft:!1});if(S)b.push(S);if(b.length){await m(e,"/tmp/wechat-channels_schedule_debug.png");throw new c(`定时设置未验证成功: 目标=${w};${b.join(";")}`,"本次没有提交任何内容。截图: /tmp/wechat-channels_schedule_debug.png")}process.stderr.write(` 定时设置完成: ${u.value||w}(表单回读一致)
403
+ `)}const ee=`
390
404
  (function(isDraft, labels) {
391
- ${p}
405
+ ${f}
392
406
  function isDisabled(btn) {
393
407
  return btn.disabled || btn.getAttribute('disabled') !== null ||
394
408
  btn.classList.contains('weui-desktop-btn_disabled');
@@ -426,9 +440,9 @@ import*as ae from"node:fs";import*as C from"node:path";import{cli as oe,Strategy
426
440
  target.click();
427
441
  return { ok: true, how: how, text: (target.innerText || target.textContent || '').trim() };
428
442
  })
429
- `,Z=`
443
+ `,te=`
430
444
  (async function(choice) {
431
- ${p}
445
+ ${f}
432
446
  ${V}
433
447
  function sleep(ms) { return new Promise(function (r) { setTimeout(r, ms); }); }
434
448
  function fire(el) {
@@ -523,22 +537,22 @@ import*as ae from"node:fs";import*as C from"node:path";import{cli as oe,Strategy
523
537
  }
524
538
  return { ok: false, reason: 'dialog-still-open', label: label, termsCount: terms.length, dialogText: oTextOf(dialog).slice(0, 200) };
525
539
  })
526
- `,ke={"dialog-not-found":"页面状态显示被原创确认框拦下,但没找到含「直接发表 / 声明原创」按钮的弹窗(平台可能改版)","terms-not-found":"弹窗里有原创权益须知,但没认出它的勾选框,未点击「声明原创」","terms-unchecked":"勾选原创权益须知后回读仍未勾上","button-not-found":"确认框里没有找到对应按钮","button-disabled":"确认框里的按钮一直是禁用状态(--original 时多半是须知没勾上,或账号当前不能声明原创)","dialog-still-open":"点了按钮后确认框没有关闭"};async function Te(e,t){const r=await d(e,`${Z}(${JSON.stringify(t?"original":"direct")})`);if(!r?.ok){await e.screenshot({path:"/tmp/wechat-channels_publish_result_debug.png"});const a=ke[r?.reason]||`确认框响应异常: ${JSON.stringify(r)}`;throw new c(`发表被平台的原创声明确认框拦下,自动选择「${t?"声明原创":"直接发表"}」失败:${a},作品尚未发出`,`先到 ${T} 确认作品列表里没有这条再重试;也可以换 ${t?"不带 --original(直接发表)":"--original(声明原创)"} 重试,`+"或加 --manual --site-session persistent 后在浏览器里手动选择。截图: /tmp/wechat-channels_publish_result_debug.png"+(r?.dialogText?`;弹窗文字: ${r.dialogText}`:""))}const n=!t?"":r.termsCount?`(须知勾选框 ${r.termsCount} 个,已回读勾上)`:"(弹窗没有须知勾选框)";process.stderr.write(` 原创确认框: 已选择「${r.label}」${n},弹窗已关闭
527
- `);return r}async function Se(e,t){const i=t?["保存草稿","存草稿","草稿"]:["发表","发布"],r=t?"保存草稿":"发表",n=30;let a;for(let o=0;o<n;o++){a=await d(e,`${z}(${JSON.stringify(t)}, ${JSON.stringify(i)})`);if(a?.ok)break;if(o<n-1)await e.wait({time:0.5})}if(!a?.ok){await e.screenshot({path:"/tmp/wechat-channels_publish_submit_debug.png"});const o=await N(e).catch(()=>null),l=a?.found?`「${r}」按钮一直是禁用状态${o?.disabledTip?`,页面给出的原因: ${o.disabledTip}`:""}`:`页面上没有「${r}」按钮`;throw new c(`${l}。本次没有提交任何内容`,"截图: /tmp/wechat-channels_publish_submit_debug.png")}return a}oe({site:"wechat-channels",name:"publish",access:"write",description:"发布视频到视频号",domain:"channels.weixin.qq.com",strategy:le.COOKIE,browser:!0,navigateBefore:!1,args:[{name:"video",required:!0,positional:!0,help:"视频文件路径 (.mp4/.mov/.avi/.webm)"},{name:"title",required:!1,help:"短标题(6-16 字;只能用中文/字母/数字/空格和 《》“”:+?% ℃,逗号请用空格代替)"},{name:"caption",fromFile:!0,required:!1,help:"描述内容,支持直接写 #话题(如:日常生活 #搞笑 #生活)"},{name:"schedule",required:!1,help:'定时发布时间(ISO8601 或 Unix 秒,如 "2026-05-20 10:00",精确到分钟;不能与 --draft 同用)'},{name:"draft",type:"bool",default:!1,help:"保存为草稿(平台不允许定时稿存草稿)"},{name:"manual",type:"bool",default:!1,help:"填完所有字段后不自动发布,由用户手动点击发表(务必同时传 --site-session persistent,否则表单页约 30 秒后会被重置为空白页)"},{name:"timeout",type:"int",required:!1,default:600,help:"命令整体超时秒数(含登录等待 + 上传转码,默认 600)"},{name:"original",type:"bool",default:!1,help:"创作分成计划账号发表时会弹「声明原创的视频有机会获得广告分成」确认框:默认自动点「直接发表」;传 --original 则勾选原创权益须知并点「声明原创」。不弹框的账号此参数无效果"}],columns:["status","title","detail","id","manage_url"],func:async(e,t)=>{if(!e)throw new c("需要浏览器页面");const i=G(t.timeout),r=Date.now()+i*1000,n=B(t.video,"视频",pe),a=String(t.title??"").trim(),o=String(t.caption??"").trim(),l=H(t.schedule||null),s=D(t.draft),m=D(t.manual),u=D(t.original);Q(a);if(u&&(s||m))throw new f("--original 只在自动发表时生效:原创确认框在点「发表」后才出现,不能与 --draft / --manual 同用");if(s&&l)throw new f("--draft 不能与 --schedule 同用:视频号在定时发表状态下禁用保存草稿");const h=l?Math.floor(l.getTime()/1000):0;await e.goto(I);await e.wait({time:4});{const b=(A)=>typeof A==="string"&&A.includes("/platform/post/create"),E=await d(e,"() => location.href");if(!b(E)){process.stderr.write(`
540
+ `,xe={"dialog-not-found":"页面状态显示被原创确认框拦下,但没找到含「直接发表 / 声明原创」按钮的弹窗(平台可能改版)","terms-not-found":"弹窗里有原创权益须知,但没认出它的勾选框,未点击「声明原创」","terms-unchecked":"勾选原创权益须知后回读仍未勾上","button-not-found":"确认框里没有找到对应按钮","button-disabled":"确认框里的按钮一直是禁用状态(--original 时多半是须知没勾上,或账号当前不能声明原创)","dialog-still-open":"点了按钮后确认框没有关闭"};async function $e(e,t){const r=await d(e,`${te}(${JSON.stringify(t?"original":"direct")})`);if(!r?.ok){await m(e,"/tmp/wechat-channels_publish_result_debug.png");const a=xe[r?.reason]||`确认框响应异常: ${JSON.stringify(r)}`;throw new c(`发表被平台的原创声明确认框拦下,自动选择「${t?"声明原创":"直接发表"}」失败:${a},作品尚未发出`,`先到 ${T} 确认作品列表里没有这条再重试;也可以换 ${t?"不带 --original(直接发表)":"--original(声明原创)"} 重试,`+"或加 --manual --site-session persistent 后在浏览器里手动选择。截图: /tmp/wechat-channels_publish_result_debug.png"+(r?.dialogText?`;弹窗文字: ${r.dialogText}`:""))}const n=!t?"":r.termsCount?`(须知勾选框 ${r.termsCount} 个,已回读勾上)`:"(弹窗没有须知勾选框)";process.stderr.write(` 原创确认框: 已选择「${r.label}」${n},弹窗已关闭
541
+ `);return r}async function Ee(e,t){const i=t?["保存草稿","存草稿","草稿"]:["发表","发布"],r=t?"保存草稿":"发表",n=30;let a;for(let o=0;o<n;o++){a=await d(e,`${ee}(${JSON.stringify(t)}, ${JSON.stringify(i)})`);if(a?.ok)break;if(o<n-1)await e.wait({time:0.5})}if(!a?.ok){await m(e,"/tmp/wechat-channels_publish_submit_debug.png");const o=await C(e).catch(()=>null),l=a?.found?`「${r}」按钮一直是禁用状态${o?.disabledTip?`,页面给出的原因: ${o.disabledTip}`:""}`:`页面上没有「${r}」按钮`;throw new c(`${l}。本次没有提交任何内容`,"截图: /tmp/wechat-channels_publish_submit_debug.png")}return a}se({site:"wechat-channels",name:"publish",access:"write",description:"发布视频到视频号",domain:"channels.weixin.qq.com",strategy:ue.COOKIE,browser:!0,navigateBefore:!1,args:[{name:"video",required:!0,positional:!0,help:"视频文件路径 (.mp4/.mov/.avi/.webm)"},{name:"title",required:!1,help:"短标题(6-16 字;只能用中文/字母/数字/空格和 《》“”:+?% ℃,逗号请用空格代替)"},{name:"caption",fromFile:!0,required:!1,help:"描述内容,支持直接写 #话题(如:日常生活 #搞笑 #生活)"},{name:"schedule",required:!1,help:'定时发布时间(ISO8601 或 Unix 秒,如 "2026-05-20 10:00",精确到分钟;不能与 --draft 同用)'},{name:"draft",type:"bool",default:!1,help:"保存为草稿(平台不允许定时稿存草稿)"},{name:"manual",type:"bool",default:!1,help:"填完所有字段后不自动发布,由用户手动点击发表(务必同时传 --site-session persistent,否则表单页约 30 秒后会被重置为空白页)"},{name:"timeout",type:"int",required:!1,default:600,help:"命令整体超时秒数(含登录等待 + 上传转码,默认 600)"},{name:"original",type:"bool",default:!1,help:"创作分成计划账号发表时会弹「声明原创的视频有机会获得广告分成」确认框:默认自动点「直接发表」;传 --original 则勾选原创权益须知并点「声明原创」。不弹框的账号此参数无效果"}],columns:["status","title","detail","id","manage_url"],func:async(e,t)=>{if(!e)throw new c("需要浏览器页面");const i=U(t.timeout),r=Date.now()+i*1000,n=H(t.video,"视频",he),a=String(t.title??"").trim(),o=String(t.caption??"").trim(),l=G(t.schedule||null),s=N(t.draft),h=N(t.manual),u=N(t.original);B(a);if(u&&(s||h))throw new p("--original 只在自动发表时生效:原创确认框在点「发表」后才出现,不能与 --draft / --manual 同用");if(s&&l)throw new p("--draft 不能与 --schedule 同用:视频号在定时发表状态下禁用保存草稿");const w=l?Math.floor(l.getTime()/1000):0;await e.goto(O);await e.wait({time:4});{const v=(D)=>typeof D==="string"&&D.includes("/platform/post/create"),A=await d(e,"() => location.href");if(!v(A)){process.stderr.write(`
528
542
  ⚠️ 未登录视频号(已被重定向离开发布页)。请在 Chrome 中扫码登录...
529
- `+" 当前地址: "+E+`
543
+ `+" 当前地址: "+A+`
530
544
  `+` 登录完成后将自动继续发布。
531
545
 
532
- `);const A=Math.min(r,Date.now()+120000);let P=!1;while(Date.now()<A){await e.wait({time:3});await e.goto(I);await e.wait({time:2});const ie=await d(e,"() => location.href");if(b(ie)){P=!0;break}process.stderr.write(` 等待扫码中...
533
- `)}if(!P)throw new se("channels.weixin.qq.com","登录超时(2分钟),请手动登录后重试");process.stderr.write(`✅ 登录成功,继续发布...
546
+ `);const D=Math.min(r,Date.now()+120000);let j=!1;while(Date.now()<D){await e.wait({time:3});await e.goto(O);await e.wait({time:2});const oe=await d(e,"() => location.href");if(v(oe)){j=!0;break}process.stderr.write(` 等待扫码中...
547
+ `)}if(!j)throw new ce("channels.weixin.qq.com","登录超时(2分钟),请手动登录后重试");process.stderr.write(`✅ 登录成功,继续发布...
534
548
 
535
- `);await e.wait({time:3});await e.goto(I);await e.wait({time:5})}}await ge(e,n);await e.wait({time:2});await _e(e,C.basename(n),Math.min(180000,we(r,"视频上传/转码")));await e.wait({time:1});if(a){await K(e,ce,a,"title");await e.wait({time:0.5});const b=await N(e);if(b?.titleError)throw new c(`平台拒绝了短标题: ${b.titleError}`,"本次没有提交任何内容,修改 --title 后重试")}if(o){await K(e,de,o,"caption");await e.wait({time:0.5})}if(l){await ye(e,l);await e.wait({time:0.5})}if(m){process.stderr.write(`
549
+ `);await e.wait({time:3});await e.goto(O);await e.wait({time:5})}}await _e(e);await ke(e,n);await e.wait({time:2});await Se(e,q.basename(n),Math.min(180000,ve(r,"视频上传/转码")));await e.wait({time:1});if(a){await z(e,fe,a,"title");await e.wait({time:0.5});const v=await C(e);if(v?.titleError)throw new c(`平台拒绝了短标题: ${v.titleError}`,"本次没有提交任何内容,修改 --title 后重试")}if(o){await z(e,pe,o,"caption");await e.wait({time:0.5})}if(l){await Te(e,l);await e.wait({time:0.5})}if(h){process.stderr.write(`
536
550
  ℹ️ 手动模式:表单已填好,请在浏览器中检查并点击「发表」。
537
551
  `+` 若未加 --site-session persistent,此标签页约 30 秒后会被重置为空白页。
538
552
 
539
- `);return[{status:"⏸️ 已填写完毕,请在浏览器中手动点击发表",title:a||"",detail:[l?`定时: ${_(h)}(已回读表单确认)`:null].filter(Boolean).join(" · ")||"表单已就绪",id:"",manage_url:T}]}const w=await N(e),k=q(w,{targetSeconds:h,isDraft:s});if(k){await e.screenshot({path:"/tmp/wechat-channels_publish_submit_debug.png"});throw new c(`${k}。本次没有提交任何内容`,"截图: /tmp/wechat-channels_publish_submit_debug.png")}await Se(e,s);await e.wait({time:s?1:4});const y=s?["已保存","暂存成功","保存成功"]:["已发表","发布成功","发表成功","审核中"];let M="",S="",x=!1,R="",v=null;const ee=w?.draftObjectId||"";let g=null;for(let b=0;b<30;b++){v=await N(e).catch(()=>null);if(s&&!ee&&v?.draftObjectId&&v.isCaching===!1){R=v.draftObjectId;x=!0;break}const E=g?v?.originalDialog:v?.originalIntercept||v?.originalDialog;if(!s&&E){if(g){await e.screenshot({path:"/tmp/wechat-channels_publish_result_debug.png"});throw new c(`已在原创确认框里选择「${g.label}」,但确认框再次出现,作品尚未发出`,`先到 ${T} 确认作品列表里没有这条,再加 --manual --site-session persistent 后在浏览器里手动处理。截图: /tmp/wechat-channels_publish_result_debug.png`)}g=await Te(e,u);await e.wait({time:1});continue}M=await d(e,"() => location.href");S=await d(e,`
553
+ `);return[{status:"⏸️ 已填写完毕,请在浏览器中手动点击发表",title:a||"",detail:[l?`定时: ${y(w)}(已回读表单确认)`:null].filter(Boolean).join(" · ")||"表单已就绪",id:"",manage_url:T}]}const b=await C(e),S=R(b,{targetSeconds:w,isDraft:s});if(S){await m(e,"/tmp/wechat-channels_publish_submit_debug.png");throw new c(`${S}。本次没有提交任何内容`,"截图: /tmp/wechat-channels_publish_submit_debug.png")}await Ee(e,s);await e.wait({time:s?1:4});const k=s?["已保存","暂存成功","保存成功"]:["已发表","发布成功","发表成功","审核中"];let I="",x="",E=!1,P="",g=null;const re=b?.draftObjectId||"";let _=null;for(let v=0;v<30;v++){g=await C(e).catch(()=>null);if(s&&!re&&g?.draftObjectId&&g.isCaching===!1){P=g.draftObjectId;E=!0;break}const A=_?g?.originalDialog:g?.originalIntercept||g?.originalDialog;if(!s&&A){if(_){await m(e,"/tmp/wechat-channels_publish_result_debug.png");throw new c(`已在原创确认框里选择「${_.label}」,但确认框再次出现,作品尚未发出`,`先到 ${T} 确认作品列表里没有这条,再加 --manual --site-session persistent 后在浏览器里手动处理。截图: /tmp/wechat-channels_publish_result_debug.png`)}_=await $e(e,u);await e.wait({time:1});continue}I=await d(e,"() => location.href");x=await d(e,`
540
554
  (function(markers) {
541
- ${p}
555
+ ${f}
542
556
  var all = deepQueryAll('*');
543
557
  for (var i = 0; i < all.length; i++) {
544
558
  var el = all[i];
@@ -550,5 +564,5 @@ import*as ae from"node:fs";import*as C from"node:path";import{cli as oe,Strategy
550
564
  }
551
565
  }
552
566
  return '';
553
- })(${JSON.stringify(y)})
554
- `);x=U({isDraft:s,finalUrl:M,successMsg:S});if(x)break;await e.wait({time:0.5})}if(!x){await e.screenshot({path:"/tmp/wechat-channels_publish_result_debug.png"});throw new c(`已点击${s?"保存草稿":"发表"},但未能确认是否成功(结果未知)`,`不要直接重试,先到 ${T} 核对${s?"草稿箱":"作品列表"}里是否已有这条,避免重复发布。`+`截图: /tmp/wechat-channels_publish_result_debug.png;url=${M||""} message=${S||""}`)}const te=s?"草稿已保存":l?"定时发表已提交":"发布成功",re=[l?`定时: ${_(h)}(已回读表单确认)`:null,g?`原创确认框: 已选「${g.label}」`:null,u&&!g?"平台未弹原创确认框,未声明原创(账号可能不在创作分成计划内)":null,S||null,s?"草稿不公开,到管理页的草稿箱继续编辑":l?"定时稿到点前没有公开链接,到管理页核对计划时间":"平台提交后不返回作品链接,到管理页查看"].filter(Boolean),ne=[{status:`✅ ${te}`,title:a||"",detail:re.join(" · "),id:R,manage_url:T}];await e.goto("https://channels.weixin.qq.com/platform/post/list",{waitUntil:"none"}).catch(()=>{});return ne}});export const __test__={parseTimeoutSeconds:G,parseScheduleDate:H,parseBooleanFlag:D,requireFilePath:B,submitSucceeded:U,validateShortTitle:Q,submittedScheduleSeconds:J,preSubmitBlocker:q,uploadProgress:W,DEEP_QUERY_FN:p,FORM_STATE_FN:O,REALM_FILE_INPUT_JS:Y,SCHEDULE_PICK_JS:X,SUBMIT_CLICK_JS:z,ORIGINAL_DIALOG_FN:V,ORIGINAL_ANSWER_JS:Z};
567
+ })(${JSON.stringify(k)})
568
+ `);E=J({isDraft:s,finalUrl:I,successMsg:x});if(E)break;await e.wait({time:0.5})}if(!E){await m(e,"/tmp/wechat-channels_publish_result_debug.png");throw new c(`已点击${s?"保存草稿":"发表"},但未能确认是否成功(结果未知)`,`不要直接重试,先到 ${T} 核对${s?"草稿箱":"作品列表"}里是否已有这条,避免重复发布。`+`截图: /tmp/wechat-channels_publish_result_debug.png;url=${I||""} message=${x||""}`)}const ne=s?"草稿已保存":l?"定时发表已提交":"发布成功",ie=[l?`定时: ${y(w)}(已回读表单确认)`:null,_?`原创确认框: 已选「${_.label}」`:null,u&&!_?"平台未弹原创确认框,未声明原创(账号可能不在创作分成计划内)":null,x||null,s?"草稿不公开,到管理页的草稿箱继续编辑":l?"定时稿到点前没有公开链接,到管理页核对计划时间":"平台提交后不返回作品链接,到管理页查看"].filter(Boolean),ae=[{status:`✅ ${ne}`,title:a||"",detail:ie.join(" · "),id:P,manage_url:T}];await e.goto("https://channels.weixin.qq.com/platform/post/list",{waitUntil:"none"}).catch(()=>{});return ae}});export const __test__={PUBLISH_FORM_READY_JS:W,parseTimeoutSeconds:U,parseScheduleDate:G,parseBooleanFlag:N,requireFilePath:H,submitSucceeded:J,validateShortTitle:B,submittedScheduleSeconds:Y,preSubmitBlocker:R,uploadProgress:X,DEEP_QUERY_FN:f,FORM_STATE_FN:M,REALM_FILE_INPUT_JS:K,SCHEDULE_PICK_JS:Z,SUBMIT_CLICK_JS:ee,ORIGINAL_DIALOG_FN:V,ORIGINAL_ANSWER_JS:te};
@@ -1,4 +1,4 @@
1
- import{existsSync as I,mkdirSync as b,readFileSync as k,renameSync as N,writeFileSync as P}from"node:fs";import{homedir as w}from"node:os";import{join as p}from"node:path";import{AuthRequiredError as T}from"@jackwener/opencli/errors";import{registerWatch as C}from"../_shared/watch.js";import{buildChatUrl as O,buildInboxUrl as f}from"./im.js";const A=/"lwp"\s*:\s*"\/s\//,J=40000,M=20,U=20000,D=20000,B=120000,F=1e4,h=`
1
+ import{existsSync as k,mkdirSync as P,readFileSync as b,renameSync as T,writeFileSync as A}from"node:fs";import{homedir as w}from"node:os";import{join as p}from"node:path";import{AuthRequiredError as N}from"@jackwener/opencli/errors";import{registerWatch as O}from"../_shared/watch.js";import{buildChatUrl as C,buildInboxUrl as f}from"./im.js";const L=/"lwp"\s*:\s*"\/s\//,M=40000,U=20,D=20000,J=20000,F=120000,B=1e4,q=1800000,R=30000,h=300000,W=/400600001|flow controled/,_=`
2
2
  (() => {
3
3
  const P = WebSocket.prototype;
4
4
  if (!P.__ppXianyuSend) {
@@ -28,7 +28,7 @@ import{existsSync as I,mkdirSync as b,readFileSync as k,renameSync as N,writeFil
28
28
  const me = (document.cookie.match(/(?:^|;\\s*)unb=(\\d+)/) || [])[1] || '';
29
29
  return JSON.stringify({ ready: !!(ws && ws.readyState === 1), me });
30
30
  })()
31
- `,L=`
31
+ `,j=`
32
32
  (async () => {
33
33
  const out = (o) => JSON.stringify(o);
34
34
  if (!/goofish\\.com\\/im/.test(location.href)) return out({ state: 'nopage', href: location.href });
@@ -45,7 +45,7 @@ import{existsSync as I,mkdirSync as b,readFileSync as k,renameSync as N,writeFil
45
45
  };
46
46
  const t = setTimeout(() => { ws.removeEventListener('message', h); res(null); }, 5000);
47
47
  ws.addEventListener('message', h);
48
- ws.send(JSON.stringify({ lwp: '/r/Conversation/listNewestPagination', headers: { mid }, body: [9007199254740991, ${M}] }));
48
+ ws.send(JSON.stringify({ lwp: '/r/Conversation/listNewestPagination', headers: { mid }, body: [9007199254740991, ${U}] }));
49
49
  });
50
50
  if (!r) return out({ state: 'timeout' });
51
51
  if (r.code !== 200) return out({ state: 'error', reason: JSON.stringify(r.body || {}).slice(0, 300) });
@@ -74,10 +74,10 @@ import{existsSync as I,mkdirSync as b,readFileSync as k,renameSync as N,writeFil
74
74
  }
75
75
  return out({ state: 'ok', me, convs });
76
76
  })()
77
- `,q="(() => { setTimeout(() => location.reload(), 200); return 1; })()",R=(e)=>new Promise((t)=>setTimeout(t,e));export function unpackMsgpack(e){let t=0;const n=(r)=>{const d=e.toString("utf8",t,t+r);t+=r;return d},o=(r)=>{const d=e.subarray(t,t+r);t+=r;return d},s=(r)=>{const d=[];for(let l=0;l<r;l++)d.push(u());return d},i=(r)=>{const d={};for(let l=0;l<r;l++){const E=u();d[E]=u()}return d},c=(r)=>{t+=1;return o(r)},a=(r)=>{const d=e.readUIntBE(t,r);t+=r;return d},m=(r)=>{const d=e.readIntBE(t,r);t+=r;return d};function u(){if(t>=e.length)throw Error("msgpack 数据提前结束");const r=e[t++];if(r<=127)return r;if(r>=224)return r-256;if((r&240)===128)return i(r&15);if((r&240)===144)return s(r&15);if((r&224)===160)return n(r&31);switch(r){case 192:return null;case 194:return!1;case 195:return!0;case 196:return o(a(1));case 197:return o(a(2));case 198:return o(a(4));case 199:return c(a(1));case 200:return c(a(2));case 201:return c(a(4));case 202:{const d=e.readFloatBE(t);t+=4;return d}case 203:{const d=e.readDoubleBE(t);t+=8;return d}case 204:return a(1);case 205:return a(2);case 206:return a(4);case 207:{const d=Number(e.readBigUInt64BE(t));t+=8;return d}case 208:return m(1);case 209:return m(2);case 210:return m(4);case 211:{const d=Number(e.readBigInt64BE(t));t+=8;return d}case 212:return c(1);case 213:return c(2);case 214:return c(4);case 215:return c(8);case 216:return c(16);case 217:return n(a(1));case 218:return n(a(2));case 219:return n(a(4));case 220:return s(a(2));case 221:return s(a(4));case 222:return i(a(2));case 223:return i(a(4))}throw Error(`msgpack 不认识的类型 0x${r.toString(16)}(第 ${t-1} 字节)`)}return u()}function g(e,t,n,o,s){if(e===101&&t){const i=JSON.parse(t);return[i.contentType,i.contentType===1&&i.text&&i.text.text||n||s||""]}return[e,o||n||s||""]}export function decodePushFrame(e){if(!A.test(e))return[];const t=JSON.parse(e).body||{},n=[];for(const o of t.syncPushPackage?.data||[]){if(o.objectType!==J||!o.data)continue;const s=unpackMsgpack(Buffer.from(o.data,"base64"))[1]||{},i=s[10]||{},c=s[6]||{},a=c[3]||{},[m,u]=g(c[1],a[5],a[2],"",i.reminderContent),r=new URLSearchParams(String(i.reminderUrl||"").split("?")[1]||"");n.push({cid:String(s[2]||""),id:String(s[3]||""),at:Number(s[5]||0),sender:String(s[1]&&s[1][1]||i.senderUserId||"").split("@")[0],type:m,text:u,title:String(i.reminderTitle||""),item_id:r.get("itemId")||""})}return n}function y(){const e=String(process.env.PPCLI_ACTIVE_PROFILE??"").trim();return p(w(),".ppcli","watch",`xianyu${e?`@${e}`:""}.watch.convs.json`)}function j(){const e=y();if(!I(e))return{};try{return JSON.parse(k(e,"utf-8"))}catch(t){process.stderr.write(`[xianyu-watch] 会话表 ${e} 读不了,从空表开始:${t?.message??t}
78
- `);return{}}}function W(e){const t=y();b(p(w(),".ppcli","watch"),{recursive:!0});const n=`${t}.${process.pid}`;P(n,JSON.stringify(e),"utf-8");N(n,t)}function X(e,t){const n=e.state.convs[t.cid]||{},o=n.peer||(t.sender&&t.sender!==e.state.me?t.sender:""),s=!!o&&t.sender===o,i=n.item_id||t.item_id||"",c=t.cid.split("@")[0];return{event:"dm",id:t.id,ts:t.at,conversation_id:c,sender:{id:t.sender,name:s?t.title:""},text:t.text,url:i&&o?O(i,o):f(),raw:{session_id:c,session_type:1,peer_user_id:o,item_id:i,item_title:n.item_title||"",price:"",seller_id:n.seller_id||"",content_type:t.type,unread_count:0,from_peer:s}}}function S(e,t){return t.map((n)=>X(e,n)).filter((n)=>n.raw.from_peer||e.includeOwn)}async function _(e,t){let n;try{n=JSON.parse(await e.evaluate(L))}catch(i){n={state:"evalfail",reason:String(i?.message??i).slice(0,300)}}if(n.state==="nologin")throw new T("www.goofish.com","Xianyu IM requires a logged-in browser session");if(n.state!=="ok"){if(n.state==="nows")await e.evaluate(h).catch(()=>null);process.stderr.write(`[xianyu-watch] 调会话列表没成功:${JSON.stringify(n)}
79
- `);return null}t.state.me||=n.me;let o=!1;const s=[];for(const i of n.convs){const c={item_id:i.item_id,item_title:i.item_title,seller_id:i.seller_id,peer:i.peer};if(JSON.stringify(t.state.convs[i.cid])!==JSON.stringify(c)){t.state.convs[i.cid]=c;o=!0}const a=i.last,m=a.custom?Buffer.from(a.custom.data,"base64").toString("utf8"):"",[u,r]=g(a.type,m,a.custom?.summary,a.text,a.reminder);s.push({cid:i.cid,id:a.id,at:a.at,sender:a.sender,type:u,text:r,title:a.title,item_id:i.item_id})}if(o)W(t.state.convs);return s}async function x(e,t){process.stderr.write(`[xianyu-watch] ${t},重新加载监听页后退出,由 supervisor 重启监听
80
- `);await e.evaluate(q).catch((n)=>process.stderr.write(`[xianyu-watch] 重新加载监听页失败:${n?.message??n}
81
- `));process.exit(75)}async function v(e,t){const n=Date.now()-Math.max(t.state.lastFrameAt||0,t.state.firstAttachedAt||0);if(t.state.firstAttachedAt&&n>B)await x(e,`IM 长连接已 ${Math.round(n/1000)} 秒没有任何帧`)}C({site:"xianyu",name:"watch",domain:"www.goofish.com",description:"闲鱼私信监听:解网页版 IM 长连接上的新消息推送,买家的新消息按 NDJSON 逐条输出",watchUrl:f(),pattern:"wss-goofish.dingtalk.com",reconcileSeconds:180,quietSeconds:50,onAttach:async(e,t)=>{t.state.convs??=j();t.state.known??=new Set;t.state.startedAt??=Date.now();t.state.firstAttachedAt??=Date.now();const n=Date.now()+U;for(;;){const o=JSON.parse(await e.evaluate(h).catch(()=>"")||"{}");if(o.me)t.state.me=o.me;if(o.ready||Date.now()>n)break;await R(500)}t.state.quietPage=e;t.state.quietTimer??=setInterval(()=>v(t.state.quietPage,t),F).unref()},parse:async(e,t)=>{t.state.lastFrameAt=Date.now();const n=String(e?.responsePreview??"");let o;try{o=decodePushFrame(n)}catch(s){process.stderr.write(`[xianyu-watch] 解推送失败:${s?.message??s};原帧前 500 字:${n.slice(0,500)}
82
- `);return null}if(!o.length)return null;for(const s of o)t.state.known.add(s.id);if(o.some((s)=>!t.state.convs[s.cid])){await _(t.page,t);for(const s of o)if(!t.state.convs[s.cid])process.stderr.write(`[xianyu-watch] 会话 ${s.cid} 查不到商品标题和卖家,按推送里有的字段先发出去
83
- `)}return S(t,o)},reconcile:async(e,t)=>{await v(e,t);const n=await(e.getCurrentUrl?e.getCurrentUrl().catch(()=>""):Promise.resolve(""));if(!/https:\/\/www\.goofish\.com\/im\b/.test(String(n||"")))await e.goto(f());const o=await _(e,t);if(!o)return[];const s=S(t,o),i=s.filter((c)=>c.raw.from_peer&&!t.state.known.has(c.id)&&c.ts>t.state.startedAt&&Date.now()-c.ts>D);for(const c of s)t.state.known.add(c.id);if(t.state.known.size>5000)t.state.known=new Set([...t.state.known].slice(-2000));if(i.length){const c=`对账发现推送没带来的买家消息 ${i.map((a)=>`${a.id}(说完 ${Math.round((Date.now()-a.ts)/1000)} 秒)`).join("、")},这条长连接收不到推送了`;setTimeout(()=>x(e,c),3000)}return s}});
77
+ `,H="(() => { setTimeout(() => location.reload(), 200); return 1; })()",X=(e)=>new Promise((t)=>setTimeout(t,e));export function unpackMsgpack(e){let t=0;const n=(a)=>{const u=e.toString("utf8",t,t+a);t+=a;return u},r=(a)=>{const u=e.subarray(t,t+a);t+=a;return u},c=(a)=>{const u=[];for(let m=0;m<a;m++)u.push(d());return u},s=(a)=>{const u={};for(let m=0;m<a;m++){const I=d();u[I]=d()}return u},o=(a)=>{t+=1;return r(a)},i=(a)=>{const u=e.readUIntBE(t,a);t+=a;return u},l=(a)=>{const u=e.readIntBE(t,a);t+=a;return u};function d(){if(t>=e.length)throw Error("msgpack 数据提前结束");const a=e[t++];if(a<=127)return a;if(a>=224)return a-256;if((a&240)===128)return s(a&15);if((a&240)===144)return c(a&15);if((a&224)===160)return n(a&31);switch(a){case 192:return null;case 194:return!1;case 195:return!0;case 196:return r(i(1));case 197:return r(i(2));case 198:return r(i(4));case 199:return o(i(1));case 200:return o(i(2));case 201:return o(i(4));case 202:{const u=e.readFloatBE(t);t+=4;return u}case 203:{const u=e.readDoubleBE(t);t+=8;return u}case 204:return i(1);case 205:return i(2);case 206:return i(4);case 207:{const u=Number(e.readBigUInt64BE(t));t+=8;return u}case 208:return l(1);case 209:return l(2);case 210:return l(4);case 211:{const u=Number(e.readBigInt64BE(t));t+=8;return u}case 212:return o(1);case 213:return o(2);case 214:return o(4);case 215:return o(8);case 216:return o(16);case 217:return n(i(1));case 218:return n(i(2));case 219:return n(i(4));case 220:return c(i(2));case 221:return c(i(4));case 222:return s(i(2));case 223:return s(i(4))}throw Error(`msgpack 不认识的类型 0x${a.toString(16)}(第 ${t-1} 字节)`)}return d()}function g(e,t,n,r,c){if(e===101&&t){const s=JSON.parse(t);return[s.contentType,s.contentType===1&&s.text&&s.text.text||n||c||""]}return[e,r||n||c||""]}export function decodePushFrame(e){if(!L.test(e))return[];const t=JSON.parse(e).body||{},n=[];for(const r of t.syncPushPackage?.data||[]){if(r.objectType!==M||!r.data)continue;const c=unpackMsgpack(Buffer.from(r.data,"base64"))[1]||{},s=c[10]||{},o=c[6]||{},i=o[3]||{},[l,d]=g(o[1],i[5],i[2],"",s.reminderContent),a=new URLSearchParams(String(s.reminderUrl||"").split("?")[1]||"");n.push({cid:String(c[2]||""),id:String(c[3]||""),at:Number(c[5]||0),sender:String(c[1]&&c[1][1]||s.senderUserId||"").split("@")[0],type:l,text:d,title:String(s.reminderTitle||""),item_id:a.get("itemId")||""})}return n}function S(){const e=String(process.env.PPCLI_ACTIVE_PROFILE??"").trim();return p(w(),".ppcli","watch",`xianyu${e?`@${e}`:""}.watch.convs.json`)}function K(){const e=S();if(!k(e))return{};try{return JSON.parse(b(e,"utf-8"))}catch(t){process.stderr.write(`[xianyu-watch] 会话表 ${e} 读不了,从空表开始:${t?.message??t}
78
+ `);return{}}}function G(e){const t=S();P(p(w(),".ppcli","watch"),{recursive:!0});const n=`${t}.${process.pid}`;A(n,JSON.stringify(e),"utf-8");T(n,t)}function Q(e,t){const n=e.state.convs[t.cid]||{},r=n.peer||(t.sender&&t.sender!==e.state.me?t.sender:""),c=!!r&&t.sender===r,s=n.item_id||t.item_id||"",o=t.cid.split("@")[0];return{event:"dm",id:t.id,ts:t.at,conversation_id:o,sender:{id:t.sender,name:c?t.title:""},text:t.text,url:s&&r?C(s,r):f(),raw:{session_id:o,session_type:1,peer_user_id:r,item_id:s,item_title:n.item_title||"",price:"",seller_id:n.seller_id||"",content_type:t.type,unread_count:0,from_peer:c}}}function y(e,t){return t.map((n)=>Q(e,n)).filter((n)=>n.raw.from_peer||e.includeOwn)}async function v(e,t){if(Date.now()<(t.state.listPausedUntil||0))return null;let n;try{n=JSON.parse(await e.evaluate(j))}catch(s){n={state:"evalfail",reason:String(s?.message??s).slice(0,300)}}if(n.state==="nologin")throw new N("www.goofish.com","Xianyu IM requires a logged-in browser session");if(n.state!=="ok"){if(n.state==="nows")await e.evaluate(_).catch(()=>null);const s=n.state==="error"&&W.test(String(n.reason||""));if(s)t.state.listPausedUntil=Date.now()+h;process.stderr.write(`[xianyu-watch] 调会话列表没成功${s?`(被限流,${h/60000} 分钟内不再调)`:""}:${JSON.stringify(n)}
79
+ `);return null}t.state.me||=n.me;let r=!1;const c=[];for(const s of n.convs){const o={item_id:s.item_id,item_title:s.item_title,seller_id:s.seller_id,peer:s.peer};if(JSON.stringify(t.state.convs[s.cid])!==JSON.stringify(o)){t.state.convs[s.cid]=o;r=!0}const i=s.last,l=i.custom?Buffer.from(i.custom.data,"base64").toString("utf8"):"",[d,a]=g(i.type,l,i.custom?.summary,i.text,i.reminder);c.push({cid:s.cid,id:i.id,at:i.at,sender:i.sender,type:d,text:a,title:i.title,item_id:s.item_id})}if(r)G(t.state.convs);return c}async function z(e,t){const n=Date.now(),r=e.state.unlisted??=new Map;for(const[o,i]of r)if(n-i>q)r.delete(o);const c=[...new Set(t.map((o)=>o.cid))].filter((o)=>!e.state.convs[o]&&!r.has(o));if(!c.length)return;if(!e.state.pushListing&&n-(e.state.pushListedAt||0)>=R){e.state.pushListedAt=n;e.state.pushListing=v(e.page,e).finally(()=>{e.state.pushListing=null})}const s=e.state.pushListing?await e.state.pushListing:void 0;for(const o of c){if(e.state.convs[o])continue;process.stderr.write(`[xianyu-watch] 会话 ${o} 查不到商品标题和卖家,按推送里有的字段先发出去
80
+ `);if(s)r.set(o,Date.now())}}async function x(e,t){process.stderr.write(`[xianyu-watch] ${t},重新加载监听页后退出,由 supervisor 重启监听
81
+ `);await e.evaluate(H).catch((n)=>process.stderr.write(`[xianyu-watch] 重新加载监听页失败:${n?.message??n}
82
+ `));process.exit(75)}async function E(e,t){const n=Date.now()-Math.max(t.state.lastFrameAt||0,t.state.firstAttachedAt||0);if(t.state.firstAttachedAt&&n>F)await x(e,`IM 长连接已 ${Math.round(n/1000)} 秒没有任何帧`)}O({site:"xianyu",name:"watch",domain:"www.goofish.com",description:"闲鱼私信监听:解网页版 IM 长连接上的新消息推送,买家的新消息按 NDJSON 逐条输出",watchUrl:f(),pattern:"wss-goofish.dingtalk.com",reconcileSeconds:180,quietSeconds:50,onAttach:async(e,t)=>{t.state.convs??=K();t.state.known??=new Set;t.state.startedAt??=Date.now();t.state.firstAttachedAt??=Date.now();const n=Date.now()+D;for(;;){const r=JSON.parse(await e.evaluate(_).catch(()=>"")||"{}");if(r.me)t.state.me=r.me;if(r.ready||Date.now()>n)break;await X(500)}t.state.quietPage=e;t.state.quietTimer??=setInterval(()=>E(t.state.quietPage,t),B).unref()},parse:async(e,t)=>{t.state.lastFrameAt=Date.now();const n=String(e?.responsePreview??"");let r;try{r=decodePushFrame(n)}catch(c){process.stderr.write(`[xianyu-watch] 解推送失败:${c?.message??c};原帧前 500 字:${n.slice(0,500)}
83
+ `);return null}if(!r.length)return null;for(const c of r)t.state.known.add(c.id);await z(t,r);return y(t,r)},reconcile:async(e,t)=>{await E(e,t);const n=await(e.getCurrentUrl?e.getCurrentUrl().catch(()=>""):Promise.resolve(""));if(!/https:\/\/www\.goofish\.com\/im\b/.test(String(n||"")))await e.goto(f());const r=await v(e,t);if(!r)return[];const c=y(t,r),s=c.filter((o)=>o.raw.from_peer&&!t.state.known.has(o.id)&&o.ts>t.state.startedAt&&Date.now()-o.ts>J);for(const o of c)t.state.known.add(o.id);if(t.state.known.size>5000)t.state.known=new Set([...t.state.known].slice(-2000));if(s.length){const o=`对账发现推送没带来的买家消息 ${s.map((i)=>`${i.id}(说完 ${Math.round((Date.now()-i.ts)/1000)} 秒)`).join("、")},这条长连接收不到推送了`;setTimeout(()=>x(e,o),3000)}return c}});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "publishport-opencli",
3
- "version": "1.0.65",
3
+ "version": "1.0.67",
4
4
  "publishConfig": {
5
5
  "access": "public",
6
6
  "provenance": false