publishport-opencli 1.0.63 → 1.0.65
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/clis/_shared/watch.js +4 -3
- package/clis/douyin/draft.js +82 -30
- package/clis/douyin/publish.js +9 -9
- package/clis/wechat-channels/publish.js +63 -33
- package/clis/xiaohongshu/publish.js +20 -39
- package/package.json +1 -1
package/clis/_shared/watch.js
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
|
-
import{existsSync as ue,mkdirSync as le,readFileSync as de,writeFileSync as fe}from"node:fs";import{homedir as pe}from"node:os";import{dirname as we,join as H}from"node:path";import{cli as me,Strategy as he}from"@jackwener/opencli/registry";import{AuthRequiredError as
|
|
1
|
+
import{existsSync as ue,mkdirSync as le,readFileSync as de,writeFileSync as fe}from"node:fs";import{homedir as pe}from"node:os";import{dirname as we,join as H}from"node:path";import{cli as me,Strategy as he}from"@jackwener/opencli/registry";import{AuthRequiredError as q,CommandExecutionError as V}from"@jackwener/opencli/errors";const U=1000,Q=300,X=60,M=30,Se=600,Y=30000,Z=2000,ve=20;function ye(){return H(pe(),".ppcli","watch")}function ee(e,r){const t=String(process.env.PPCLI_ACTIVE_PROFILE??"").trim();return H(ye(),`${e}${t?`@${t}`:""}.${r}.seen.json`)}function _e(e,r){const t=ee(e,r);try{if(!ue(t))return{ids:[],set:new Set,lastTs:0,firstRun:!0};const i=JSON.parse(de(t,"utf-8")),a=Array.isArray(i?.ids)?i.ids.map(String):[],c=Number.isFinite(i?.lastTs)?Number(i.lastTs):0;return{ids:a,set:new Set(a),lastTs:c,firstRun:c<=0}}catch{return{ids:[],set:new Set,lastTs:0,firstRun:!0}}}function C(e,r,t){const i=ee(e,r);try{le(we(i),{recursive:!0});fe(i,JSON.stringify({ids:t.ids.slice(-Z),lastTs:t.lastTs||0}),"utf-8")}catch{}}function Ne(e,r){if(e.set.has(r))return!1;e.set.add(r);e.ids.push(r);while(e.ids.length>Z){const t=e.ids.shift();e.set.delete(t)}return!0}function F(e){process.stdout.write(`${JSON.stringify(e)}
|
|
2
2
|
`)}function d(e,r,t={}){F({type:"status",site:e,state:r,ts:Date.now(),...t})}function te(e,r){if(!r||typeof r!=="object")return null;const t=r.id==null?"":String(r.id);if(!t)return null;const i=r.sender&&typeof r.sender==="object"?{id:r.sender.id==null?"":String(r.sender.id),name:String(r.sender.name??"")}:{id:"",name:String(r.sender??"")};return{type:"event",site:e,event:String(r.event??"message"),id:t,ts:Number.isFinite(r.ts)?Number(r.ts):Date.now(),conversation_id:r.conversation_id==null?"":String(r.conversation_id),sender:i,text:String(r.text??""),url:r.url==null?"":String(r.url),raw:r.raw??null}}function re(e){if(!e)return[];return Array.isArray(e)?e.filter(Boolean):[e]}function ne(e){try{return new URL(e).origin}catch{return""}}function be(e,r){const t=(i)=>{try{const a=new URL(i);if(a.protocol==="https:"&&a.port==="443"||a.protocol==="http:"&&a.port==="80")a.port="";return`${a.protocol}//${a.host}${a.pathname==="/"?"":a.pathname}${a.search}${a.hash}`}catch{return String(i??"")}};return Boolean(e)&&t(e)===t(r)}async function Ee(e,r){if(typeof e.getCurrentUrl!=="function")return!1;try{if(!be(await e.getCurrentUrl(),r))return!1;await e.evaluate("(function(){ window.__pp_watch_doc = 1; return 1; })()");return!0}catch{return!1}}async function Te(e){try{return await e.evaluate("(function(){ return window.__pp_watch_doc === 1; })()")===!0}catch{return!1}}async function ae(e){await e.evaluate("(function(){ window.__pp_watch_doc = 1; setTimeout(function(){ location.reload(); }, 0); return 1; })()");const r=Date.now()+Y;while(Date.now()<r){await new Promise((t)=>setTimeout(t,500));try{if(await e.evaluate('(function(){ return window.__pp_watch_doc === 1 ? "old" : document.readyState; })()')==="complete")return}catch{}}throw new V(`监听页 ${Y/1000} 秒内没有重新加载完`)}function ie(){return`(function(){
|
|
3
3
|
if (window.__pp_timers) return;
|
|
4
|
+
if (window.top !== window || !/^https?:$/.test(location.protocol)) return;
|
|
4
5
|
window.__pp_timers = 'native';
|
|
5
6
|
var worker;
|
|
6
7
|
try {
|
|
7
8
|
var src = "var t={};onmessage=function(e){var d=e.data;if(d[0]==='s'){t[d[1]]=(d[3]?setInterval:setTimeout)(function(){postMessage(d[1]);},d[2]);}else{clearTimeout(t[d[1]]);clearInterval(t[d[1]]);delete t[d[1]];}};";
|
|
8
|
-
worker = new Worker(
|
|
9
|
+
worker = new Worker('data:text/javascript,' + encodeURIComponent(src));
|
|
9
10
|
} catch (e) { window.__pp_timers = 'worker-failed: ' + e; return; }
|
|
10
11
|
var nST = window.setTimeout, nCT = window.clearTimeout, nSI = window.setInterval, nCI = window.clearInterval;
|
|
11
12
|
var seq = 1000000000, cbs = {};
|
|
@@ -96,4 +97,4 @@ import{existsSync as ue,mkdirSync as le,readFileSync as de,writeFileSync as fe}f
|
|
|
96
97
|
WrappedES.prototype = NativeES.prototype;
|
|
97
98
|
window.EventSource = WrappedES;
|
|
98
99
|
}
|
|
99
|
-
})()`}async function Ie(e){let r;try{r=await e.evaluate("(function(){ var o = window.__pp_stream || []; window.__pp_stream = []; return JSON.stringify(o); })()")}catch{return[]}let t;try{t=JSON.parse(typeof r==="string"?r:"[]")}catch{return[]}if(!Array.isArray(t))return[];return t.map((i)=>({kind:"page-hook",channel:i.channel,direction:i.direction,url:i.url,method:i.channel==="websocket"?"WS":"SSE",eventName:i.eventName||void 0,responseStatus:200,responseContentType:i.binary?"application/octet-stream":"text/plain",responsePreview:i.binary?"":String(i.data??""),timestamp:i.ts||Date.now()}))}export function registerWatch(e){if(!e?.site||!e?.domain||!e?.watchUrl||typeof e.parse!=="function")throw Error("registerWatch 需要 site、domain、watchUrl 和 parse");const r=e.name??"watch",t=e.site,i=ne(e.watchUrl);me({site:t,name:r,access:"read",description:e.description??`长驻监听${t}的新消息,旁听页面自身的实时通道并按 NDJSON 逐条输出(不对平台发轮询请求)`,domain:e.domain,strategy:he.COOKIE,browser:!0,navigateBefore:!1,sessionKey:e.sessionKey??"watch",siteSession:"persistent",defaultWindowMode:"background",args:[{name:"interval",type:"int",required:!1,default:
|
|
100
|
+
})()`}async function Ie(e){let r;try{r=await e.evaluate("(function(){ var o = window.__pp_stream || []; window.__pp_stream = []; return JSON.stringify(o); })()")}catch{return[]}let t;try{t=JSON.parse(typeof r==="string"?r:"[]")}catch{return[]}if(!Array.isArray(t))return[];return t.map((i)=>({kind:"page-hook",channel:i.channel,direction:i.direction,url:i.url,method:i.channel==="websocket"?"WS":"SSE",eventName:i.eventName||void 0,responseStatus:200,responseContentType:i.binary?"application/octet-stream":"text/plain",responsePreview:i.binary?"":String(i.data??""),timestamp:i.ts||Date.now()}))}export function registerWatch(e){if(!e?.site||!e?.domain||!e?.watchUrl||typeof e.parse!=="function")throw Error("registerWatch 需要 site、domain、watchUrl 和 parse");const r=e.name??"watch",t=e.site,i=ne(e.watchUrl);me({site:t,name:r,access:"read",description:e.description??`长驻监听${t}的新消息,旁听页面自身的实时通道并按 NDJSON 逐条输出(不对平台发轮询请求)`,domain:e.domain,strategy:he.COOKIE,browser:!0,navigateBefore:!1,sessionKey:e.sessionKey??"watch",siteSession:"persistent",defaultWindowMode:"background",args:[{name:"interval",type:"int",required:!1,default:U,help:`本机取帧间隔毫秒(默认 ${U})。纯本机 IPC,不发平台请求`},{name:"reconcile-interval",type:"int",required:!1,default:0,help:`对账间隔秒(0 = 用该平台的默认值:${Number(e.reconcileSeconds)>0?`本平台 ${Number(e.reconcileSeconds)} 秒`:`可旁听实时通道的平台 ${Q} 秒兜底,只能靠拉取的平台 ${X} 秒一轮`});-1 = 彻底关闭对账`},{name:"quiet-seconds",type:"int",required:!1,default:0,help:`实时通道这么多秒一帧都没收到就重载监听页重连(0 = 用该平台的默认值${Number(e.quietSeconds)>0?`:本平台 ${Number(e.quietSeconds)} 秒`:";本平台默认不查"})`},{name:"heartbeat",type:"int",required:!1,default:M,help:`心跳间隔秒(默认 ${M}),无事件时输出一行 status 表示还活着`},{name:"events",type:"str",required:!1,help:"只输出这些事件类型,逗号分隔(如 dm,comment);默认全部"},{name:"once",type:"bool",required:!1,default:!1,help:"只跑一轮对账后退出,不长驻。用于验证解析器和补历史"},{name:"replay-seen",type:"bool",required:!1,default:!1,help:"忽略去重表,把解析到的事件全部重新输出(调试用,会导致重复触发)"},{name:"backfill",type:"bool",required:!1,default:!1,help:"首次运行时把已存在的历史消息也当成新事件输出(默认只静默登记,不触发)"},{name:"dump-frames",type:"bool",required:!1,default:!1,help:"侦察模式:把收到的每一条原始帧(url / 通道 / 内容片段)也打出来,用来给新平台摸清事件通道"},{name:"include-own",type:"bool",required:!1,default:!1,help:"连自己发出去的消息也当成事件(默认不算——否则自动回复会追着自己的回复自我触发)。调试解析用"}],columns:["event","id","sender","text","ts"],func:async(a,c)=>{const oe=Math.max(200,Number(c.interval??U)),x=e.mode==="reconcile"?"reconcile":"stream",I=Number(c["reconcile-interval"]??0),D=I<0?0:I>0?I:Number(e.reconcileSeconds)>0?Number(e.reconcileSeconds):x==="reconcile"?X:Q,B=Math.max(0,Number(c.heartbeat??M)),J=c.once===!0||c.once==="true",S=c["replay-seen"]===!0||c["replay-seen"]==="true",O=c.backfill===!0||c.backfill==="true",se=c["dump-frames"]===!0||c["dump-frames"]==="true",v=String(c.events??"").split(",").map((u)=>u.trim()).filter(Boolean);if(typeof a.startNetworkCapture!=="function"||typeof a.readNetworkCapture!=="function")throw new V("当前浏览器通道不支持网络捕获,watch 无法工作(需要 CDP 或扩展路径)");const f=_e(t,r),g={site:t,page:a,state:{},includeOwn:c["include-own"]===!0||c["include-own"]==="true"};let w=0,A=0,y=!1;const W=[];let m=f.firstRun&&!O&&!S,k=!1;const _=f.lastTs,G=(u)=>{const o=te(t,u);if(!o)return!1;if(v.length&&!v.includes(o.event))return!1;if(!S&&!Ne(f,`${o.event}:${o.id}`))return!1;if(o.ts>f.lastTs)f.lastTs=o.ts;if(m){A++;return!1}if(!O&&!S&&_>0&&o.ts>0&&o.ts<=_){A++;return!1}if(!J)F(o);W.push(o);w++;return!0},ce=(u)=>{let o=0;for(const l of u){const n=te(t,l);if(!n)continue;if(v.length&&!v.includes(n.event))continue;if(f.set.has(`${n.event}:${n.id}`))continue;if(_>0&&n.ts>0&&n.ts<=_)continue;o++}return o},h=async(u,o=!1)=>{if(typeof e.reconcile!=="function")return;try{const l=re(await e.reconcile(a,g));if(o&&!m&&!O&&!S&&ce(l)>ve){m=!0;k=!0}let n=0;for(const s of l)if(G(s))n++;d(t,"reconciled",{reason:u,scanned:l.length,new:n})}catch(l){if(l instanceof q)throw l;d(t,"reconcile_failed",{reason:u,error:l?.message??String(l)})}},N=async(u)=>{let o=!1;try{o=await a.startNetworkCapture(e.pattern??"")!==!1}catch{o=!1}const l=Ce(e.pattern??"");y=!1;let n=!1;if(typeof a.cdp==="function")try{await a.cdp("Page.enable",{});await a.cdp("Page.addScriptToEvaluateOnNewDocument",{source:l});if(e.unthrottleTimers!==!1)await a.cdp("Page.addScriptToEvaluateOnNewDocument",{source:ie()});n=!0;y=!0}catch{}const s=await Ee(a,e.watchUrl);await a.goto(e.watchUrl,{waitUntil:n?"load":"none"});if(s&&await Te(a)){d(t,"page_reloading",{reason:u});await ae(a);await a.goto(e.watchUrl,{waitUntil:n?"load":"none"})}if(!n){if(e.unthrottleTimers!==!1)await a.evaluate(ie()).catch((p)=>d(t,"timer_shim_failed",{error:p?.message??String(p)}));try{await a.evaluate(l);y=!0;d(t,"page_hook_late",{note:"浏览器扩展版本较旧,旁听脚本只能在导航后注入;页面在此之前已建立的连接要等它重连才能被看到"})}catch(p){d(t,"page_hook_unavailable",{error:p?.message??String(p)})}}if(!o){await a.startNetworkCapture(e.pattern??"");await ae(a);await a.goto(e.watchUrl,{waitUntil:"load"})}if(typeof e.onAttach==="function")await e.onAttach(a,g);d(t,"watching",{reason:u,mode:x,url:e.watchUrl,pattern:e.pattern??"",reconcile_seconds:D})};await N("start");await h("startup",!0);if(m){C(t,r,f);d(t,"seeded",{seeded:A,desynced:k,note:k?"去重表和收件箱对不上(上次没跑完 / 换了账号 / 表被裁剪),本轮把当前收件箱重新登记为「已见过」,不触发任何事件。从现在起只有新消息才会上报":"首次运行:已把当前收件箱登记为「已见过」,不触发任何事件。从现在起只有新消息才会上报(要补历史请加 --backfill)"});m=!1}if(J){C(t,r,f);return W}let L=!1;const b=()=>{L=!0};process.on("SIGINT",b);process.on("SIGTERM",b);let j=Date.now(),P=Date.now(),K=w;const z=Math.max(0,Number(c["quiet-seconds"]??0)||Number(e.quietSeconds??0)||0);let E=Date.now(),R=0,T=0;try{while(!L){await new Promise((n)=>setTimeout(n,oe));if(L)break;let u=[];try{u=await a.readNetworkCapture()??[];if(y)u=u.concat(await Ie(a))}catch(n){d(t,"reattaching",{error:n?.message??String(n)});try{await N("capture_lost");await h("reattach")}catch(s){if(s instanceof q)throw s;d(t,"reattach_failed",{error:s?.message??String(s)})}continue}if(u.some((n)=>n?.direction==="sent"))R=Date.now();if(u.some((n)=>n?.direction!=="sent")){E=Date.now();T=0}for(const n of u){if(se)F({type:"frame",site:t,via:n?.kind==="page-hook"?"page-hook":"cdp",channel:n?.channel??"http",direction:n?.direction??"",method:n?.method??"",url:String(n?.url??"").slice(0,200),size:n?.responseBodyFullSize??String(n?.responsePreview??"").length,preview:String(n?.responsePreview??"").slice(0,600)});if(n?.direction==="sent")continue;let s;try{s=await e.parse(n,g)}catch(p){d(t,"parse_failed",{url:n?.url??"",error:p?.message??String(p)});continue}for(const p of re(s))G(p)}if(w!==K){C(t,r,f);K=w;P=Date.now()}if(i&&typeof a.getCurrentUrl==="function")try{const n=await a.getCurrentUrl();if(n&&ne(n)!==i){d(t,"page_drifted",{url:n});await N("drift");await h("drift")}}catch{}const o=Math.min(z*2**T,Se);if(z&&Date.now()-E>=o*1000){let n=null;try{n=await a.evaluate('(function(){ return JSON.stringify({ href: location.href, ready: document.readyState, hidden: document.hidden, buffered: Array.isArray(window.__pp_stream) ? window.__pp_stream.length : -1, hooked: !!window.__pp_stream_hooked, closed: window.__pp_stream_closed || null, timers: String(window.__pp_timers || "") }); })()')}catch(s){n=`evaluate 失败:${s?.message??String(s)}`}d(t,"quiet",{silent_ms:Date.now()-E,sent_ago_ms:R?Date.now()-R:-1,strikes:T,page:n});T++;E=Date.now();try{await N("quiet");await h("quiet")}catch(s){if(s instanceof q)throw s;d(t,"reattach_failed",{error:s?.message??String(s)})}continue}const l=Date.now();if(D&&l-j>=D*1000){j=l;await h("interval")}if(B&&l-P>=B*1000){P=l;d(t,"alive",{emitted:w})}}}finally{process.off("SIGINT",b);process.off("SIGTERM",b);C(t,r,f);d(t,"stopped",{emitted:w})}return W}})}export function frameJson(e){const r=e?.responsePreview;if(typeof r!=="string"||!r)return null;if(r.startsWith("base64:"))return null;try{return JSON.parse(r)}catch{return null}}
|
package/clis/douyin/draft.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import{DOUYIN_VIDEO_ARGS as w,validateDouyinSettings as v,setDouyinPublishSettings as h}from"./_shared/publish-settings.js";import*as
|
|
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(`() => {
|
|
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
|
|
8
|
+
}`)}async function I(t){let e={href:"",ready:!1,bodyText:""};for(let n=0;n<k;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(
|
|
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(`() => {
|
|
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(
|
|
@@ -24,10 +24,10 @@ import{DOUYIN_VIDEO_ARGS as w,validateDouyinSettings as v,setDouyinPublishSettin
|
|
|
24
24
|
: false;
|
|
25
25
|
const hasCaptionEditor = !!document.querySelector('[contenteditable="true"]');
|
|
26
26
|
const hasVisibility = !!Array.from(document.querySelectorAll('label')).find(
|
|
27
|
-
(el) => (el.textContent || '').includes(${JSON.stringify(
|
|
27
|
+
(el) => (el.textContent || '').includes(${JSON.stringify(e)})
|
|
28
28
|
);
|
|
29
29
|
return { uploading, saveEnabled, hasSaveBtn: !!saveBtn, hasCaptionEditor, hasVisibility };
|
|
30
|
-
}`);if(
|
|
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(`() => {
|
|
31
31
|
const titleInput = Array.from(document.querySelectorAll('input')).find(
|
|
32
32
|
(el) => (el.placeholder || '').includes('填写作品标题')
|
|
33
33
|
);
|
|
@@ -36,12 +36,12 @@ import{DOUYIN_VIDEO_ARGS as w,validateDouyinSettings as v,setDouyinPublishSettin
|
|
|
36
36
|
const props = propKey ? titleInput[propKey] : null;
|
|
37
37
|
if (props?.onChange) {
|
|
38
38
|
props.onChange({
|
|
39
|
-
target: { value: ${JSON.stringify(
|
|
40
|
-
currentTarget: { value: ${JSON.stringify(
|
|
39
|
+
target: { value: ${JSON.stringify(e.title)} },
|
|
40
|
+
currentTarget: { value: ${JSON.stringify(e.title)} },
|
|
41
41
|
});
|
|
42
42
|
} else {
|
|
43
43
|
titleInput.focus();
|
|
44
|
-
titleInput.value = ${JSON.stringify(
|
|
44
|
+
titleInput.value = ${JSON.stringify(e.title)};
|
|
45
45
|
titleInput.dispatchEvent(new Event('input', { bubbles: true }));
|
|
46
46
|
titleInput.dispatchEvent(new Event('change', { bubbles: true }));
|
|
47
47
|
}
|
|
@@ -55,44 +55,96 @@ import{DOUYIN_VIDEO_ARGS as w,validateDouyinSettings as v,setDouyinPublishSettin
|
|
|
55
55
|
titleInput.dispatchEvent(new Event('blur', { bubbles: true }));
|
|
56
56
|
}
|
|
57
57
|
return true;
|
|
58
|
-
}`);if(
|
|
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
59
|
const editor = document.querySelector('[contenteditable="true"]');
|
|
60
60
|
if (!(editor instanceof HTMLElement)) return false;
|
|
61
61
|
editor.focus();
|
|
62
62
|
editor.textContent = '';
|
|
63
63
|
document.execCommand('selectAll', false);
|
|
64
|
-
document.execCommand('insertText', false, ${JSON.stringify(
|
|
64
|
+
document.execCommand('insertText', false, ${JSON.stringify(e.caption)});
|
|
65
65
|
editor.dispatchEvent(new Event('input', { bubbles: true }));
|
|
66
66
|
return true;
|
|
67
|
-
}`);if(
|
|
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(`() => {
|
|
68
68
|
const visibility = Array.from(document.querySelectorAll('label')).find(
|
|
69
|
-
(el) => (el.textContent || '').includes(${JSON.stringify(
|
|
69
|
+
(el) => (el.textContent || '').includes(${JSON.stringify(e.visibilityLabel)})
|
|
70
70
|
);
|
|
71
71
|
if (!(visibility instanceof HTMLElement)) return false;
|
|
72
72
|
visibility.click();
|
|
73
73
|
return true;
|
|
74
|
-
}`);if(
|
|
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(`() => {
|
|
75
|
+
const visible = (el) => { const r = el.getBoundingClientRect(); return r.width > 0 && r.height > 0; };
|
|
76
|
+
const mark = (target) => {
|
|
77
|
+
document
|
|
78
|
+
.querySelectorAll('[data-opencli-cover-input="1"]')
|
|
79
|
+
.forEach((el) => el.removeAttribute('data-opencli-cover-input'));
|
|
80
|
+
target.setAttribute('data-opencli-cover-input', '1');
|
|
81
|
+
return '[data-opencli-cover-input="1"]';
|
|
82
|
+
};
|
|
83
|
+
// 新版页面里仍留着一个不可见的「上传新封面」label,点它不会出新输入框:只认可见的。
|
|
75
84
|
const coverLabel = Array.from(document.querySelectorAll('label')).find(
|
|
76
|
-
(el) => (el.textContent || '').includes('上传新封面')
|
|
85
|
+
(el) => (el.textContent || '').includes('上传新封面') && visible(el)
|
|
77
86
|
);
|
|
78
87
|
if (coverLabel instanceof HTMLElement) {
|
|
79
88
|
coverLabel.click();
|
|
89
|
+
const inputs = Array.from(document.querySelectorAll('input[type="file"]'));
|
|
90
|
+
const target = inputs
|
|
91
|
+
.slice(${JSON.stringify(n)})
|
|
92
|
+
.find((el) => el instanceof HTMLInputElement && !el.disabled);
|
|
93
|
+
if (!(target instanceof HTMLInputElement)) {
|
|
94
|
+
return { ok: false, reason: 'cover-input-pending' };
|
|
95
|
+
}
|
|
96
|
+
return { ok: true, selector: mark(target), mode: 'label' };
|
|
80
97
|
}
|
|
81
98
|
|
|
82
|
-
const
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
.
|
|
86
|
-
|
|
87
|
-
return { ok: false, reason: 'cover-
|
|
99
|
+
const modal = Array.from(document.querySelectorAll('.dy-creator-content-modal, [role="dialog"]'))
|
|
100
|
+
.find((el) => visible(el) && (el.textContent || '').includes('上传封面'));
|
|
101
|
+
if (!modal) {
|
|
102
|
+
const slots = Array.from(document.querySelectorAll('[class*="coverControl"]')).filter(visible);
|
|
103
|
+
const slot = slots.find((el) => (el.textContent || '').includes('竖封面')) || slots[0];
|
|
104
|
+
if (!slot) return { ok: false, reason: 'cover-slot-missing' };
|
|
105
|
+
const entry = Array.from(slot.querySelectorAll('div')).find((el) => (el.textContent || '').trim() === '选择封面' && visible(el)) || slot;
|
|
106
|
+
entry.click();
|
|
107
|
+
return { ok: false, reason: 'cover-modal-opening' };
|
|
88
108
|
}
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
.
|
|
92
|
-
.
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
109
|
+
const zone = Array.from(modal.querySelectorAll('input[type="file"]')).find((el) => {
|
|
110
|
+
if (!(el instanceof HTMLInputElement) || el.disabled || /replace/.test(el.className || '')) return false;
|
|
111
|
+
const box = el.closest('.semi-upload') || el.parentElement;
|
|
112
|
+
return !!box && (box.textContent || '').includes('点击上传');
|
|
113
|
+
});
|
|
114
|
+
if (!(zone instanceof HTMLInputElement)) {
|
|
115
|
+
return { ok: false, reason: 'cover-modal-input-missing' };
|
|
116
|
+
}
|
|
117
|
+
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(`() => {
|
|
119
|
+
const visible = (el) => { const r = el.getBoundingClientRect(); return r.width > 0 && r.height > 0; };
|
|
120
|
+
const dialogs = Array.from(document.querySelectorAll('.dy-creator-content-modal, [role="dialog"]')).filter(visible);
|
|
121
|
+
// 点「完成」后若只设了竖封面,会再弹「设置横封面获更多流量」:选「暂不设置」。
|
|
122
|
+
for (const d of dialogs) {
|
|
123
|
+
const skip = Array.from(d.querySelectorAll('button')).find((b) => (b.textContent || '').trim() === '暂不设置' && visible(b));
|
|
124
|
+
if (skip) {
|
|
125
|
+
skip.click();
|
|
126
|
+
return { closed: false, clicked: true, skippedHorizontal: true, text: (d.innerText || '').replace(/\\s+/g, ' ').slice(0, 200) };
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
const modal = dialogs.find((el) => /设置竖封面|设置横封面|上传封面/.test(el.textContent || ''));
|
|
130
|
+
if (!modal) return { closed: true };
|
|
131
|
+
const text = (modal.innerText || '').replace(/\\s+/g, ' ');
|
|
132
|
+
const uploading = /上传中|检测中|处理中/.test(text);
|
|
133
|
+
// 「上传封面」格子在图片读入后多出一张 data: / blob: 背景缩略图;拖放区文字始终都在,不能作信号。
|
|
134
|
+
// 上传后页面会重建 input(打的标记随之消失),按「上传封面」文字找格子。
|
|
135
|
+
const tiles = Array.from(modal.querySelectorAll('.semi-upload'))
|
|
136
|
+
.map((el) => el.parentElement)
|
|
137
|
+
.filter((el) => el && (el.textContent || '').includes('上传封面'));
|
|
138
|
+
const pending = !tiles.some((tile) => Array.from(tile.querySelectorAll('[style*="background-image"]'))
|
|
139
|
+
.some((el) => /data:|blob:/.test(el.style.backgroundImage || '')));
|
|
140
|
+
const done = Array.from(modal.querySelectorAll('button')).find((b) => (b.textContent || '').trim() === '完成' && visible(b));
|
|
141
|
+
const disabled = !done || done.disabled || done.getAttribute('aria-disabled') === 'true' || /disabled/.test(done.className || '');
|
|
142
|
+
if (uploading || pending || disabled) {
|
|
143
|
+
return { closed: false, clicked: false, uploading, pending, disabled, text: text.slice(0, 200) };
|
|
144
|
+
}
|
|
145
|
+
done.click();
|
|
146
|
+
return { closed: false, clicked: true, text: text.slice(0, 200) };
|
|
147
|
+
}`);if(e?.closed)return;await t.wait({time:e?.clicked?1:0.5})}const n=!e?"unknown":e.clicked?"已点「完成」,弹窗未关闭":e.uploading?"封面仍在上传或检测":e.pending?"「上传封面」格子里没有出现上传的图片":"「完成」按钮不可点击";throw new a(`抖音封面弹窗未完成:${n}`,e?.text?`弹窗文字: ${e.text}`:"unknown")}export function buildCoverCheckPanelTextJs(){return`() => {
|
|
96
148
|
const normalize = (value) => (value || '').replace(/\\s+/g, ' ').trim();
|
|
97
149
|
const stateTexts = ['检测', '检测中', '封面检测中', '重新检测', '横/竖双封面缺失'];
|
|
98
150
|
const marker = Array.from(document.querySelectorAll('div,span,p,button')).find(
|
|
@@ -110,7 +162,7 @@ import{DOUYIN_VIDEO_ARGS as w,validateDouyinSettings as v,setDouyinPublishSettin
|
|
|
110
162
|
root = root.parentElement;
|
|
111
163
|
}
|
|
112
164
|
return '';
|
|
113
|
-
}`}async function O(t){return await t.evaluate(buildCoverCheckPanelTextJs())||""}async function
|
|
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(`() => {
|
|
114
166
|
const extractCreationId = () => {
|
|
115
167
|
const titleInput = Array.from(document.querySelectorAll('input')).find(
|
|
116
168
|
(el) => (el.placeholder || '').includes('填写作品标题')
|
|
@@ -160,7 +212,7 @@ import{DOUYIN_VIDEO_ARGS as w,validateDouyinSettings as v,setDouyinPublishSettin
|
|
|
160
212
|
text: (btn.textContent || '').trim(),
|
|
161
213
|
creationId,
|
|
162
214
|
};
|
|
163
|
-
}`);if(
|
|
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(`() => ({
|
|
164
216
|
href: location.href,
|
|
165
217
|
bodyText: document.body?.innerText || ''
|
|
166
|
-
})`);const
|
|
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)}]}});
|
package/clis/douyin/publish.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import{DOUYIN_DECLARATION_ARGS as Z,douyinDeclarationInfo as j}from"./_shared/publish-settings.js";import*as T from"node:fs";import*as
|
|
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(`
|
|
2
2
|
`);process.stderr.write(` 提交上传...
|
|
3
|
-
`);const
|
|
4
|
-
`);
|
|
5
|
-
`);const t=await se(
|
|
6
|
-
`)}if(!e.no_safety_check){const t="https://creator.douyin.com/aweme/v1/post_assistant/fast_detect/pre_check",
|
|
7
|
-
`);const K="https://creator.douyin.com/aweme/v1/post_assistant/fast_detect/poll",X=Date.now()+30000;let M=!1,
|
|
8
|
-
`);else throw new
|
|
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?` 创建发布...
|
|
9
9
|
`:` 创建定时发布...
|
|
10
|
-
`);let
|
|
11
|
-
`);return[{status:e.immediate?"✅ 发布请求已提交":"✅ 定时发布成功!",aweme_id:
|
|
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}]}});
|
|
@@ -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
|
|
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=`
|
|
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
|
-
`,
|
|
48
|
+
`,O=`
|
|
49
49
|
function vmOf(el) {
|
|
50
50
|
while (el) {
|
|
51
51
|
if (el.__vue__) return el.__vue__;
|
|
@@ -110,7 +110,7 @@ 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
|
|
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,`
|
|
114
114
|
(() => {
|
|
115
115
|
${p}
|
|
116
116
|
var sels = ${JSON.stringify(fe)};
|
|
@@ -123,7 +123,7 @@ 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
|
|
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,`
|
|
127
127
|
(() => {
|
|
128
128
|
${p}
|
|
129
129
|
var inputSels = ['input[type="file"][accept*="video"]', 'input[type="file"]'];
|
|
@@ -132,7 +132,7 @@ import*as ae from"node:fs";import*as C from"node:path";import{cli as oe,Strategy
|
|
|
132
132
|
}
|
|
133
133
|
return false;
|
|
134
134
|
})()
|
|
135
|
-
`))return!0;if(r
|
|
135
|
+
`))return!0;if(n<r-1)await e.wait({time:i/1000})}return!1}const Y=`((sel) => {
|
|
136
136
|
${p}
|
|
137
137
|
var real = deepQuery(sel);
|
|
138
138
|
if (!real) return null;
|
|
@@ -162,11 +162,11 @@ import*as ae from"node:fs";import*as C from"node:path";import{cli as oe,Strategy
|
|
|
162
162
|
return real.dispatchEvent(new win.Event(ev.type, { bubbles: true }));
|
|
163
163
|
},
|
|
164
164
|
};
|
|
165
|
-
})`;async function ge(e,t){await
|
|
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
|
|
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,`
|
|
167
167
|
((fileName) => {
|
|
168
168
|
${p}
|
|
169
|
-
${
|
|
169
|
+
${O}
|
|
170
170
|
var files = readFormState().files;
|
|
171
171
|
if (Array.isArray(files)) return { files: files };
|
|
172
172
|
|
|
@@ -185,8 +185,8 @@ import*as ae from"node:fs";import*as C from"node:path";import{cli as oe,Strategy
|
|
|
185
185
|
var hasFileEvidence = fileName && bodyText.indexOf(fileName) >= 0;
|
|
186
186
|
return { done: !uploading && (preview || hasFileEvidence), failed: false };
|
|
187
187
|
})(${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}/${
|
|
189
|
-
`);await e.wait({time:
|
|
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,`
|
|
190
190
|
(function(selectors, text) {
|
|
191
191
|
${p}
|
|
192
192
|
|
|
@@ -233,10 +233,10 @@ import*as ae from"node:fs";import*as C from"node:path";import{cli as oe,Strategy
|
|
|
233
233
|
el.blur();
|
|
234
234
|
return { ok: actual.indexOf(text) >= 0, sel: foundSel, actual: actual };
|
|
235
235
|
})(${JSON.stringify(t)}, ${JSON.stringify(i)})
|
|
236
|
-
`);if(a?.ok)break;if(o<
|
|
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=`
|
|
237
237
|
(async function(TY, TM, TD, TH, TMin, TARGET_MS) {
|
|
238
238
|
${p}
|
|
239
|
-
${
|
|
239
|
+
${O}
|
|
240
240
|
function sleep(ms) { return new Promise(function(r) { setTimeout(r, ms); }); }
|
|
241
241
|
function click(el) {
|
|
242
242
|
el.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true, view: window }));
|
|
@@ -385,7 +385,7 @@ import*as ae from"node:fs";import*as C from"node:path";import{cli as oe,Strategy
|
|
|
385
385
|
var inp = dateDl.querySelector('dt input') || deepQuery('input[placeholder*="发表时间"]');
|
|
386
386
|
return { ok: true, value: inp ? inp.value : null, pick: pickOf(), commit: commit.join('+'), state: readFormState() };
|
|
387
387
|
})
|
|
388
|
-
`;async function ye(e,t){const i=t.getFullYear(),
|
|
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
389
|
`)}const z=`
|
|
390
390
|
(function(isDraft, labels) {
|
|
391
391
|
${p}
|
|
@@ -443,25 +443,47 @@ import*as ae from"node:fs";import*as C from"node:path";import{cli as oe,Strategy
|
|
|
443
443
|
el.dispatchEvent(new MouseEvent('click', opts));
|
|
444
444
|
}
|
|
445
445
|
function btnDisabled(b) {
|
|
446
|
-
|
|
446
|
+
if (b.disabled || b.getAttribute('disabled') !== null || b.getAttribute('aria-disabled') === 'true') return true;
|
|
447
|
+
if (/disabled/.test(b.className || '')) return true;
|
|
448
|
+
try { return getComputedStyle(b).pointerEvents === 'none'; } catch (e) { return false; }
|
|
447
449
|
}
|
|
448
450
|
// 须知勾选框:优先 .original-proto-wrapper;没有这层时取框内文案像「须知 / 条款 / 同意」的勾选框,
|
|
449
|
-
//
|
|
451
|
+
// 绝不碰「不再提醒」那个(勾了会改账号设置)。勾选框不一定是原生 input:ant / weui 的自绘勾选框
|
|
452
|
+
// 只有 span / i,按 role 与类名一起找,每组只取最外层的包装元素。
|
|
450
453
|
function termsBoxes(dialog) {
|
|
451
454
|
var scope = dialog.querySelector('.original-proto-wrapper');
|
|
452
|
-
var
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
455
|
+
var root = scope || dialog;
|
|
456
|
+
var cands = Array.prototype.slice.call(root.querySelectorAll(
|
|
457
|
+
'input[type="checkbox"], [role="checkbox"], label, [class*="checkbox"]'));
|
|
458
|
+
var wraps = [];
|
|
459
|
+
cands.forEach(function (el) {
|
|
460
|
+
if (el.tagName === 'LABEL' && !el.querySelector('input[type="checkbox"], [role="checkbox"], [class*="checkbox"]')) return;
|
|
461
|
+
if (/checkbox-group/.test(String(el.className || ''))) return;
|
|
462
|
+
if (wraps.some(function (w) { return w === el || w.contains(el); })) return;
|
|
463
|
+
wraps.push(el);
|
|
464
|
+
});
|
|
465
|
+
return wraps.map(function (wrap) {
|
|
466
|
+
var input = wrap.matches('input[type="checkbox"]') ? wrap : wrap.querySelector('input[type="checkbox"]');
|
|
467
|
+
// 文案优先取包装元素自己的;自绘勾选框自身无字时才看父节点(父节点同时含「不再提醒」则不认)。
|
|
468
|
+
var own = oTextOf(wrap);
|
|
469
|
+
var text = own || oTextOf(wrap.parentNode || wrap);
|
|
470
|
+
return { input: input, wrap: wrap, text: text, own: !!own };
|
|
456
471
|
}).filter(function (b) {
|
|
457
|
-
if (b.text.indexOf('不再提醒') >= 0 && !scope) return false;
|
|
472
|
+
if (b.text.indexOf('不再提醒') >= 0 && (b.own || !scope)) return false;
|
|
458
473
|
return scope ? true : /须知|条款|同意|阅读|权益/.test(b.text);
|
|
459
474
|
});
|
|
460
475
|
}
|
|
461
476
|
function boxChecked(b) {
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
477
|
+
if (b.input && b.input.checked) return true;
|
|
478
|
+
var nodes = [b.wrap].concat(Array.prototype.slice.call(b.wrap.querySelectorAll('*')));
|
|
479
|
+
return nodes.some(function (n) {
|
|
480
|
+
if (n.getAttribute && n.getAttribute('aria-checked') === 'true') return true;
|
|
481
|
+
return /(^|[\\s_-])(is-)?checked(\\s|$)/.test(String(n.className && n.className.baseVal !== undefined ? n.className.baseVal : n.className || ''));
|
|
482
|
+
});
|
|
483
|
+
}
|
|
484
|
+
function clickTarget(b) {
|
|
485
|
+
if (b.input && b.input.getBoundingClientRect().width) return b.input;
|
|
486
|
+
return b.wrap.querySelector('[class*="checkbox"]:not([class*="wrapper"])') || b.wrap;
|
|
465
487
|
}
|
|
466
488
|
var dialog = findOriginalDialog();
|
|
467
489
|
if (!dialog) return { ok: false, reason: 'dialog-not-found' };
|
|
@@ -470,12 +492,16 @@ import*as ae from"node:fs";import*as C from"node:path";import{cli as oe,Strategy
|
|
|
470
492
|
var terms = [];
|
|
471
493
|
if (choice === 'original') {
|
|
472
494
|
terms = termsBoxes(dialog);
|
|
495
|
+
// 弹窗写着「须知」却一个勾选框都没认出来:不点灰着的「声明原创」,直接报错。
|
|
496
|
+
if (!terms.length && /须知/.test(dialogText)) {
|
|
497
|
+
return { ok: false, reason: 'terms-not-found', dialogText: dialogText };
|
|
498
|
+
}
|
|
473
499
|
for (var t = 0; t < terms.length; t++) {
|
|
474
|
-
if (!boxChecked(terms[t])) fire(
|
|
500
|
+
if (!boxChecked(terms[t])) fire(clickTarget(terms[t]));
|
|
475
501
|
}
|
|
476
502
|
for (var w = 0; w < 15 && terms.some(function (b) { return !boxChecked(b); }); w++) await sleep(200);
|
|
477
503
|
if (terms.some(function (b) { return !boxChecked(b); })) {
|
|
478
|
-
return { ok: false, reason: 'terms-unchecked', dialogText: dialogText };
|
|
504
|
+
return { ok: false, reason: 'terms-unchecked', termsCount: terms.length, dialogText: dialogText };
|
|
479
505
|
}
|
|
480
506
|
}
|
|
481
507
|
var btn = null;
|
|
@@ -487,26 +513,30 @@ import*as ae from"node:fs";import*as C from"node:path";import{cli as oe,Strategy
|
|
|
487
513
|
if (!btn) return { ok: false, reason: 'button-not-found', label: label, dialogText: dialogText };
|
|
488
514
|
if (btnDisabled(btn)) return { ok: false, reason: 'button-disabled', label: label, termsCount: terms.length, dialogText: dialogText };
|
|
489
515
|
fire(btn);
|
|
516
|
+
// 以这一个弹窗节点本身是否消失为准;重新按「直接发表」按钮找弹窗会在弹窗换了一屏内容时误判为已关闭。
|
|
517
|
+
function dialogGone() {
|
|
518
|
+
return !dialog.isConnected || !isVisible(dialog) || !oButtons(dialog, label).length;
|
|
519
|
+
}
|
|
490
520
|
for (var c = 0; c < 25; c++) {
|
|
491
521
|
await sleep(200);
|
|
492
|
-
if (
|
|
522
|
+
if (dialogGone()) return { ok: true, label: label, termsCount: terms.length };
|
|
493
523
|
}
|
|
494
|
-
return { ok: false, reason: 'dialog-still-open', label: label, termsCount: terms.length, dialogText:
|
|
524
|
+
return { ok: false, reason: 'dialog-still-open', label: label, termsCount: terms.length, dialogText: oTextOf(dialog).slice(0, 200) };
|
|
495
525
|
})
|
|
496
|
-
`,ke={"dialog-not-found":"页面状态显示被原创确认框拦下,但没找到含「直接发表 / 声明原创」按钮的弹窗(平台可能改版)","terms-unchecked":"勾选原创权益须知后回读仍未勾上","button-not-found":"确认框里没有找到对应按钮","button-disabled":"确认框里的按钮一直是禁用状态(--original 时多半是须知没勾上,或账号当前不能声明原创)","dialog-still-open":"点了按钮后确认框没有关闭"};async function Te(e,t){const
|
|
497
|
-
`);return
|
|
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(`
|
|
498
528
|
⚠️ 未登录视频号(已被重定向离开发布页)。请在 Chrome 中扫码登录...
|
|
499
529
|
`+" 当前地址: "+E+`
|
|
500
530
|
`+` 登录完成后将自动继续发布。
|
|
501
531
|
|
|
502
|
-
`);const
|
|
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(` 等待扫码中...
|
|
503
533
|
`)}if(!P)throw new se("channels.weixin.qq.com","登录超时(2分钟),请手动登录后重试");process.stderr.write(`✅ 登录成功,继续发布...
|
|
504
534
|
|
|
505
|
-
`);await e.wait({time:3});await e.goto(I);await e.wait({time:5})}}await ge(e,
|
|
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(`
|
|
506
536
|
ℹ️ 手动模式:表单已填好,请在浏览器中检查并点击「发表」。
|
|
507
537
|
`+` 若未加 --site-session persistent,此标签页约 30 秒后会被重置为空白页。
|
|
508
538
|
|
|
509
|
-
`);return[{status:"⏸️ 已填写完毕,请在浏览器中手动点击发表",title:a||"",detail:[l?`定时: ${_(h)}(已回读表单确认)`:null].filter(Boolean).join(" · ")||"表单已就绪",id:"",manage_url:T}]}const w=await
|
|
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,`
|
|
510
540
|
(function(markers) {
|
|
511
541
|
${p}
|
|
512
542
|
var all = deepQueryAll('*');
|
|
@@ -521,4 +551,4 @@ import*as ae from"node:fs";import*as C from"node:path";import{cli as oe,Strategy
|
|
|
521
551
|
}
|
|
522
552
|
return '';
|
|
523
553
|
})(${JSON.stringify(y)})
|
|
524
|
-
`);x=
|
|
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};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/topics.js";import{XHS_PUBLISH_ARGS as wt,validateXhsSettings as gt,setXhsPublishSettings as _t}from"./_shared/publish-settings.js";import*as
|
|
1
|
+
import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/topics.js";import{XHS_PUBLISH_ARGS as wt,validateXhsSettings as gt,setXhsPublishSettings as _t}from"./_shared/publish-settings.js";import*as O from"node:fs";import*as N from"node:path";import{CommandExecutionError as u,ArgumentError as b}from"@jackwener/opencli/errors";import{cli as xt,Strategy as yt}from"@jackwener/opencli/registry";import{assertLiteralContent as vt}from"../_shared/content-guard.js";import{setInputFiles as St}from"../_shared/file-inject.js";import{humanType as z,humanWait as I,humanMoveTo as Tt,elementViewportCenter as kt}from"./human.js";import{loadNoteManagerNotes as $t}from"./_shared/note-manager.js";const At="https://creator.xiaohongshu.com/publish/publish?from=menu_left&target=image",F=18,H=20,X=3000,G="|||",k="基础",Y=[["基础","默认兜底,万能"],["边框","金句/要点卡"],["备忘","提醒/随手记"],["清新","日常/清单贴士"],["涂写","随笔/碎碎念"],["便签","笔记/提醒"],["光影","情绪/文艺"],["涂鸦","趣味/童话"],["简约","干货/观点"],["手写","日记/情感"],["插图","生活方式/轻松话题"],["美漫","活力/趣味/故事感"],["弥散","弥散光氛围"],["柔和","柔和/温柔金句"],["印刷","印刷海报/排版"],["科技","科技/产品"],["贺卡","节日祝福"],["札记","艺术/水彩氛围"],["书摘","书摘/引用"],["手帐","手帐拼贴"],["几何","醒目/有力主张"]],ae=Y.map(([t])=>t),B="文字配图",K="再写一张",W="生成图片",Q="下一步",U=".tiptap.ProseMirror",Et=["_onPublish","onPublish","_onSubmit","_handlePublish"],Ct=["_onSave","_onSaveDraft","_onDraft"],Z=['[contenteditable="true"][placeholder*="标题"]','[contenteditable="true"][placeholder*="赞"]','input[placeholder*="标题"]','input[placeholder*="title" i]','[contenteditable="true"][class*="title"]','input[maxlength="20"]','input[class*="title"]',".title-input input",".note-title input","input[maxlength]"],tt=['[contenteditable="true"][class*="content"]','[contenteditable="true"][class*="editor"]','[contenteditable="true"][placeholder*="描述"]','[contenteditable="true"][placeholder*="正文"]','[contenteditable="true"][placeholder*="内容"]','.note-content [contenteditable="true"]','.editor-content [contenteditable="true"]','[contenteditable="true"]:not([placeholder*="标题"]):not([placeholder*="赞"]):not([placeholder*="title" i])'],Mt={".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".gif":"image/gif",".webp":"image/webp"};function _(t){if(t&&typeof t==="object"&&typeof t.session==="string"&&Object.prototype.hasOwnProperty.call(t,"data"))return t.data;return t}function Nt(t){return t.map((e)=>{const r=N.resolve(e);if(!O.existsSync(r))throw new b(`Image file not found: ${r}`);const n=N.extname(r).toLowerCase();if(!Mt[n])throw new b(`Unsupported image format "${n}". Supported: jpg, png, gif, webp`);return r})}const et='input[type="file"][accept*="image"],input[type="file"][accept*=".jpg"],input[type="file"][accept*=".jpeg"],input[type="file"][accept*=".png"],input[type="file"][accept*=".gif"],input[type="file"][accept*=".webp"]';async function It(t,e=15000){const r=500,n=Math.max(1,Math.ceil(e/r));for(let o=0;o<n;o++){if(await t.evaluate(`
|
|
2
2
|
(() => {
|
|
3
3
|
const sels = ${JSON.stringify(et)};
|
|
4
4
|
return !!document.querySelector(sels);
|
|
@@ -117,7 +117,7 @@ import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/to
|
|
|
117
117
|
return { ok: true };
|
|
118
118
|
})(${JSON.stringify(o.sel)})
|
|
119
119
|
`))?.ok){await t.screenshot({path:`/tmp/xhs_publish_${n}_debug.png`});throw Error(`Could not prepare ${n} input. Debug screenshot: /tmp/xhs_publish_${n}_debug.png`)}await t.wait({time:0.35});try{const s=String(r).split(`
|
|
120
|
-
`);for(let d=0;d<s.length;d++){if(d>0)await Pt(t,o.sel,d);if(s[d])await
|
|
120
|
+
`);for(let d=0;d<s.length;d++){if(d>0)await Pt(t,o.sel,d);if(s[d])await z(t,s[d])}a=await t.evaluate(`
|
|
121
121
|
((selector, expectedText) => {
|
|
122
122
|
const __opencli_xhs_fill_phase = "verify";
|
|
123
123
|
const normalize = (value) => (value || '').replace(/\\s+/g, ' ').trim();
|
|
@@ -143,7 +143,7 @@ import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/to
|
|
|
143
143
|
})(${JSON.stringify(o.sel)}, ${JSON.stringify(r)})
|
|
144
144
|
`)}catch(s){if(s instanceof u)throw s;if(String(r).includes(`
|
|
145
145
|
`))throw new u(`写入${n}失败:${String(s?.message||s)}。`+"正文含换行,不能回退到单段写入方式(那会把多段正文塞进一段),因此中止。"+"⚠️ 编辑器可能已自动保存草稿:请勿直接重试,先用 `ppcli xiaohongshu drafts` 查看。");a=await i()}}else a=await i();if(!a?.ok){await t.screenshot({path:`/tmp/xhs_publish_${n}_debug.png`});const l=typeof a?.actual==="string"?a.actual:"";throw Error(`Failed to set ${n}. ${describeTextMismatch(String(r).replace(/\s+/g," ").trim(),l,typeof a?.blocks==="number"?{expected:String(r).split(`
|
|
146
|
-
`).length,actual:a.blocks}:void 0)}`+" ⚠️ 编辑器可能已自动保存草稿:请勿直接重试,先用 `ppcli xiaohongshu drafts` 查看,"+"已存在则改为在该草稿上继续操作或先删除,避免建出重复草稿。"+` Debug screenshot: /tmp/xhs_publish_${n}_debug.png`)}}async function
|
|
146
|
+
`).length,actual:a.blocks}:void 0)}`+" ⚠️ 编辑器可能已自动保存草稿:请勿直接重试,先用 `ppcli xiaohongshu drafts` 查看,"+"已存在则改为在该草稿上继续操作或先删除,避免建出重复草稿。"+` Debug screenshot: /tmp/xhs_publish_${n}_debug.png`)}}async function Dt(t){const e=await t.evaluate(`
|
|
147
147
|
() => {
|
|
148
148
|
const isVisible = (el) => {
|
|
149
149
|
if (!el || el.offsetParent === null) return false;
|
|
@@ -192,7 +192,7 @@ import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/to
|
|
|
192
192
|
}
|
|
193
193
|
return { ok: false, visibleTexts };
|
|
194
194
|
}
|
|
195
|
-
`);if(e?.ok)await t.wait({time:1});return e}async function
|
|
195
|
+
`);if(e?.ok)await t.wait({time:1});return e}async function A(t,e,r=7000){const n=500,o=Math.max(1,Math.ceil(r/n));let i={ok:!1};for(let a=0;a<o;a++){i=_(await t.evaluate(`
|
|
196
196
|
((cfg) => {
|
|
197
197
|
const __opencli_xhs_click_label = { wantLabel: ${JSON.stringify(e)} };
|
|
198
198
|
const wantLabel = ${JSON.stringify(e)};
|
|
@@ -227,7 +227,7 @@ import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/to
|
|
|
227
227
|
}
|
|
228
228
|
return { ok: false };
|
|
229
229
|
})()
|
|
230
|
-
`));if(i?.ok)return i;await t.wait({time:n/1000})}return i}async function
|
|
230
|
+
`));if(i?.ok)return i;await t.wait({time:n/1000})}return i}async function Rt(t){const e=await t.evaluate(`
|
|
231
231
|
(() => {
|
|
232
232
|
const __opencli_xhs_focus_card = true;
|
|
233
233
|
const sel = ${JSON.stringify(U)};
|
|
@@ -262,16 +262,16 @@ import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/to
|
|
|
262
262
|
const activeText = active ? (active.innerText || active.textContent || '').trim() : '';
|
|
263
263
|
return { ok: true, count: editors.length, activeEmpty: !activeText };
|
|
264
264
|
})()
|
|
265
|
-
`);return _(e)}async function
|
|
265
|
+
`);return _(e)}async function Lt(t,e=8000){const r=300,n=Math.ceil(e/r);for(let o=0;o<n;o++){if((await it(t))?.count>=1)return!0;await t.wait({time:r/1000})}return!1}async function Ot(t,e,r=6000){const n=300,o=Math.ceil(r/n);for(let i=0;i<o;i++){const a=await it(t);if(a?.count>=e&&a?.activeEmpty)return!0;await t.wait({time:n/1000})}return!1}async function Ft(t,e,r=4){for(let n=0;n<r;n++){if(!(await A(t,K))?.ok)return!1;if(await Ot(t,e,2500))return!0}return!1}async function Bt(t){const e=await t.evaluate(`
|
|
266
266
|
(() => {
|
|
267
267
|
const __opencli_xhs_preview_ready = true;
|
|
268
268
|
const ready = Array.from(document.querySelectorAll('button'))
|
|
269
269
|
.some((b) => b.offsetParent !== null && (b.innerText || '').replace(/\\s+/g, '') === '下一步');
|
|
270
270
|
return { ok: ready };
|
|
271
271
|
})()
|
|
272
|
-
`);return _(e)}async function Ut(t,e=6){const r=400,n=Math.ceil(3000/r);for(let o=0;o<e;o++){if(!(await
|
|
273
|
-
`);if(!(await
|
|
274
|
-
`);for(let a=0;a<i.length;a++){if(a>0&&typeof t.pressKey==="function")await t.pressKey("Enter");if(i[a])await
|
|
272
|
+
`);return _(e)}async function Ut(t,e=6){const r=400,n=Math.ceil(3000/r);for(let o=0;o<e;o++){if(!(await A(t,W))?.ok&&o===0)return!1;for(let a=0;a<n;a++){if((await Bt(t))?.ok)return!0;await t.wait({time:r/1000})}}return!1}async function jt(t,e,r){e=String(e).replace(/\\n/g,`
|
|
273
|
+
`);if(!(await Rt(t))?.ok)throw new u(`文字配图: could not focus card editor #${r+1}`);if(typeof t.insertText==="function"){const i=e.split(`
|
|
274
|
+
`);for(let a=0;a<i.length;a++){if(a>0&&typeof t.pressKey==="function")await t.pressKey("Enter");if(i[a])await z(t,i[a])}}else await t.evaluate(`(t => document.execCommand('insertText', false, t))(${JSON.stringify(e)})`);await t.wait({time:0.4});if(!(await qt(t))?.ok)throw new u(`文字配图: card editor #${r+1} is empty after typing`)}async function Jt(t,e){if(!e||e===k)return k;const r=_(await t.evaluate(`
|
|
275
275
|
(async () => {
|
|
276
276
|
const __opencli_xhs_card_styles = true;
|
|
277
277
|
const want = ${JSON.stringify(e)};
|
|
@@ -300,39 +300,20 @@ import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/to
|
|
|
300
300
|
}
|
|
301
301
|
return { ok: seen.length > 0, styles: seen, found: false };
|
|
302
302
|
})()
|
|
303
|
-
`));if(!r?.found)throw new u(`文字配图: requested style "${e}" is not available for this content (options: ${(r?.styles||[]).join(" / ")||"none"}). Choose an available style or omit --card-style to use ${k}.`);if(!(await
|
|
303
|
+
`));if(!r?.found)throw new u(`文字配图: requested style "${e}" is not available for this content (options: ${(r?.styles||[]).join(" / ")||"none"}). Choose an available style or omit --card-style to use ${k}.`);if(!(await A(t,e))?.ok)throw new u(`文字配图: could not click requested style "${e}".`);await t.wait({time:0.6});return e}async function at(t){const e=await t.evaluate(`
|
|
304
304
|
(() => {
|
|
305
305
|
const __opencli_xhs_composer_media_count = true;
|
|
306
|
-
const
|
|
306
|
+
const visible = (el) => {
|
|
307
307
|
if (!el || el.offsetParent === null) return false;
|
|
308
308
|
const r = el.getBoundingClientRect();
|
|
309
|
-
return r.width > 0 && r.height > 0;
|
|
310
|
-
};
|
|
311
|
-
const visibleMedia = (el) => {
|
|
312
|
-
if (!visibleBox(el)) return false;
|
|
313
|
-
const r = el.getBoundingClientRect();
|
|
314
309
|
return r.width >= 48 && r.height >= 48;
|
|
315
310
|
};
|
|
316
|
-
const
|
|
317
|
-
|
|
318
|
-
.
|
|
319
|
-
.flat()
|
|
320
|
-
.find((el) => visibleBox(el));
|
|
321
|
-
const root = titleEl?.closest('form, [class*="publish"], [class*="editor"], [class*="note"]') || document.body;
|
|
322
|
-
const seen = new Set();
|
|
323
|
-
let count = 0;
|
|
324
|
-
for (const el of Array.from(root.querySelectorAll('img, video, canvas, [style*="background-image"]'))) {
|
|
325
|
-
if (!visibleMedia(el)) continue;
|
|
326
|
-
const rect = el.getBoundingClientRect();
|
|
327
|
-
const src = el.currentSrc || el.src || el.getAttribute('src') || el.style?.backgroundImage || '';
|
|
328
|
-
const key = src || String(Math.round(rect.left)) + ':' + String(Math.round(rect.top));
|
|
329
|
-
if (seen.has(key)) continue;
|
|
330
|
-
seen.add(key);
|
|
331
|
-
count += 1;
|
|
332
|
-
}
|
|
311
|
+
const count = Array.from(document.querySelectorAll('.img-container'))
|
|
312
|
+
.filter((card) => Array.from(card.querySelectorAll('img')).some(visible))
|
|
313
|
+
.length;
|
|
333
314
|
return { ok: true, count };
|
|
334
315
|
})()
|
|
335
|
-
`);return _(e)}async function st(t,e,r){const n=await at(t);if(!n||typeof n.count!=="number")throw new u(`${r}: could not verify current composer media count`);if(n.count<e){await t.screenshot({path:"/tmp/xhs_publish_media_debug.png"});throw new u(`${r}: expected at least ${e} visible media item(s), got ${n.count}. Debug screenshot: /tmp/xhs_publish_media_debug.png`)}}async function Vt(t,e,r){if(!(await
|
|
316
|
+
`);return _(e)}async function st(t,e,r){const n=await at(t);if(!n||typeof n.count!=="number")throw new u(`${r}: could not verify current composer media count`);if(n.count<e){await t.screenshot({path:"/tmp/xhs_publish_media_debug.png"});throw new u(`${r}: expected at least ${e} visible media item(s), got ${n.count}. Debug screenshot: /tmp/xhs_publish_media_debug.png`)}}async function Vt(t,e,r){if(!(await A(t,B))?.ok){await t.screenshot({path:"/tmp/xhs_publish_textimage_debug.png"});throw new u(`文字配图: could not click "${B}" entry. Debug: /tmp/xhs_publish_textimage_debug.png`)}if(!await Lt(t)){await t.screenshot({path:"/tmp/xhs_publish_textimage_debug.png"});throw new u(`文字配图: 写文字 card editor did not appear after clicking "${B}". Debug: /tmp/xhs_publish_textimage_debug.png`)}for(let l=0;l<e.length;l++){if(l>0){if(!await Ft(t,l+1)){await t.screenshot({path:"/tmp/xhs_publish_addcard_debug.png"});throw new u(`文字配图: new card editor #${l+1} did not render after "${K}". Debug: /tmp/xhs_publish_addcard_debug.png`)}}await jt(t,e[l],l)}if(!await Ut(t)){await t.screenshot({path:"/tmp/xhs_publish_generate_debug.png"});throw new u(`文字配图: "${W}" did not advance to the 预览图片 step. `+"Debug: /tmp/xhs_publish_generate_debug.png")}const i=await Jt(t,r);if(!(await A(t,Q))?.ok){await t.screenshot({path:"/tmp/xhs_publish_next_debug.png"});throw new u(`文字配图: could not click "${Q}". Debug: /tmp/xhs_publish_next_debug.png`)}await t.wait({time:2});return i}async function lt(t){return t.evaluate(`
|
|
336
317
|
() => {
|
|
337
318
|
const text = (document.body?.innerText || '').replace(/s+/g, ' ').trim();
|
|
338
319
|
const hasTitleInput = !!Array.from(document.querySelectorAll('input, textarea')).find((el) => {
|
|
@@ -364,7 +345,7 @@ import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/to
|
|
|
364
345
|
}
|
|
365
346
|
`)}async function zt(t,e=5000){const r=500,n=Math.max(1,Math.ceil(e/r));let o=await lt(t);for(let i=0;i<n;i++){if(o.state!=="video_surface")return o;if(i<n-1){await t.wait({time:r/1000});o=await lt(t)}}return o}async function Ht(t,e=1e4){const r=1000,n=Math.ceil(e/r);for(let o=0;o<n;o++){if(await t.evaluate(`
|
|
366
347
|
(() => {
|
|
367
|
-
const sels = ${JSON.stringify(
|
|
348
|
+
const sels = ${JSON.stringify(Z)};
|
|
368
349
|
for (const sel of sels) {
|
|
369
350
|
const el = document.querySelector(sel);
|
|
370
351
|
if (el && el.offsetParent !== null) return true;
|
|
@@ -408,7 +389,7 @@ import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/to
|
|
|
408
389
|
}
|
|
409
390
|
return removed;
|
|
410
391
|
})(${JSON.stringify(e)})
|
|
411
|
-
`));return Number(r)||0}function Gt(t){const e=String(t&&(t.url||t.key)||""),r=String(t&&t.method||"").toUpperCase(),n=Number(t&&t.status||0);if(r!=="PUT")return null;if(!/ros-upload[^/]*\/spectrum\//.test(e))return null;if(n<200||n>=300)return null;const o=e.match(/\/spectrum\/([^?#]+)/);return o?o[1]:e}function ut(t){return Math.min(45,6+t*4)}async function dt(t,e,r,n=90000){if(e<=0)return{ok:!0,completed:0};if(!r||typeof t.readNetworkCapture!=="function"){await t.wait({time:ut(e)});return{ok:!0,completed:null,viaFallback:!0}}const o=1500,a=Math.ceil(9000/o),l=Math.ceil(n/o),s=new Set;for(let d=0;d<l;d++){const w=await t.readNetworkCapture().catch(()=>[]);for(const v of Array.isArray(w)?w:[]){const m=Gt(v);if(m)s.add(m)}if(s.size>=e)return{ok:!0,completed:s.size};if(d>=a&&s.size===0){await t.wait({time:ut(e)});return{ok:!0,completed:null,viaFallback:!0}}await t.wait({time:o/1000})}return{ok:!1,completed:s.size}}const j=3;export function pickPublishedNote(t,e,r=Date.now()){const n=String(e||"").trim();return(Array.isArray(t)?t:[]).filter((i)=>!i.sticky).slice(0,j).find((i)=>{const a=String(i.title||"").trim();if(!a||!(a===n||a.startsWith(n)||n.startsWith(a)))return!1;const l=String(i.time||"").match(/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2})$/);if(!l)return!0;const s=Date.UTC(Number(l[1]),Number(l[2])-1,Number(l[3]),Number(l[4]),Number(l[5]))-28800000;return Math.abs(r-s)<=93600000})??null}async function Yt(t,e,r){let n="";for(let o=0;o<r;o++){if(o>0)await t.wait({time:3});let i;try{i=await
|
|
392
|
+
`));return Number(r)||0}function Gt(t){const e=String(t&&(t.url||t.key)||""),r=String(t&&t.method||"").toUpperCase(),n=Number(t&&t.status||0);if(r!=="PUT")return null;if(!/ros-upload[^/]*\/spectrum\//.test(e))return null;if(n<200||n>=300)return null;const o=e.match(/\/spectrum\/([^?#]+)/);return o?o[1]:e}function ut(t){return Math.min(45,6+t*4)}async function dt(t,e,r,n=90000){if(e<=0)return{ok:!0,completed:0};if(!r||typeof t.readNetworkCapture!=="function"){await t.wait({time:ut(e)});return{ok:!0,completed:null,viaFallback:!0}}const o=1500,a=Math.ceil(9000/o),l=Math.ceil(n/o),s=new Set;for(let d=0;d<l;d++){const w=await t.readNetworkCapture().catch(()=>[]);for(const v of Array.isArray(w)?w:[]){const m=Gt(v);if(m)s.add(m)}if(s.size>=e)return{ok:!0,completed:s.size};if(d>=a&&s.size===0){await t.wait({time:ut(e)});return{ok:!0,completed:null,viaFallback:!0}}await t.wait({time:o/1000})}return{ok:!1,completed:s.size}}const j=3;export function pickPublishedNote(t,e,r=Date.now()){const n=String(e||"").trim();return(Array.isArray(t)?t:[]).filter((i)=>!i.sticky).slice(0,j).find((i)=>{const a=String(i.title||"").trim();if(!a||!(a===n||a.startsWith(n)||n.startsWith(a)))return!1;const l=String(i.time||"").match(/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2})$/);if(!l)return!0;const s=Date.UTC(Number(l[1]),Number(l[2])-1,Number(l[3]),Number(l[4]),Number(l[5]))-28800000;return Math.abs(r-s)<=93600000})??null}async function Yt(t,e,r){let n="";for(let o=0;o<r;o++){if(o>0)await t.wait({time:3});let i;try{i=await $t(t,{tab:"all",limit:j+5})}catch(l){return{note:null,reason:`创作者后台笔记列表读取出错:${l?.message??String(l)}`}}const a=pickPublishedNote(i.notes,e);if(a)return{note:a,reason:""};n=i.notes.length===0?"创作者后台笔记列表为空":`创作者后台最新 ${Math.min(i.notes.length,j)} 条笔记里没有同标题笔记`}return{note:null,reason:n}}xt({site:"xiaohongshu",name:"publish",access:"write",description:"小红书发布图文笔记 (creator center UI automation)",domain:"creator.xiaohongshu.com",strategy:yt.COOKIE,browser:!0,navigateBefore:!1,args:[{name:"content",required:!1,positional:!0,help:"笔记正文(字面文本,不会展开 @文件 引用;长正文建议用 --file)"},{name:"file",required:!1,help:"从本机文件读取笔记正文(UTF-8),与位置参数 <content> 二选一"},{name:"title",required:!0,help:"笔记标题 (最多20字)"},{name:"images",required:!1,help:`图片路径,逗号分隔,最多${F}张 (jpg/png/gif/webp)`},{name:"card-text",required:!1,help:`文字配图卡片文字,多张卡片用 ${G} 分隔,卡内换行用 \\n`},{name:"card-style",required:!1,help:`文字配图卡片样式,运行时按页面实际选项匹配;找不到会失败。省略时使用${k}。可选: ${Y.map(([t,e])=>`${t}(${e})`).join(" ")}`},{name:"topics",required:!1,help:"话题名称,逗号分隔,最多10个;先用 topics 查询。无法准确选中时停止提交"},mt,{name:"draft",type:"bool",default:!1,help:"保存为草稿,不直接发布"},{name:"timeout",type:"int",default:300,help:"整段发布流程的等待预算(秒);超时后先用 creator-notes 回查,勿直接重复发布"},{name:"ai-generated",type:"boolean",help:"声明内容由 AI 生成(发布和草稿均支持;设置失败时停止提交)"},...wt],columns:["status","detail","url"],func:async(t,e)=>{gt(e);if(!t)throw Error("Browser page required");const r=String(e.title??"").trim(),n=e.file?String(e.file).trim():"";let o=String(e.content??"").trim();if(n){if(o)throw new b("正文位置参数和 --file 只能二选一,不能同时给");const c=N.resolve(n);if(!O.existsSync(c))throw new b(`--file 指向的文件不存在: ${c}`);o=O.readFileSync(c,"utf-8").trim();if(!o)throw new b(`--file 指向的文件内容为空: ${c}`)}const i=e.images?String(e.images).split(",").map((c)=>c.trim()).filter(Boolean):[],a=pt(e),l=a.map((c)=>c.name),s=Boolean(e.draft),d=e["card-text"]?String(e["card-text"]):"",w=d?d.split(G).map((c)=>c.trim()).filter(Boolean):[],v=e["card-style"]?String(e["card-style"]).trim():"",m=w.length>0;if(!r)throw new b("--title is required");if(r.length>H)throw new b(`Title is ${r.length} chars — must be ≤ ${H}`);if(!o)throw new b("缺少笔记正文:给位置参数 <content>(字面文本),或用 --file <本机文件路径>");vt(o,{fileFlag:"--file"});if(!m&&i.length===0)throw new b("Provide --card-text (text-image mode) or --images (upload mode); neither was given.");if(i.length>F)throw new b(`Too many images: ${i.length} (max ${F})`);if(m&&i.some((c)=>N.extname(c).toLowerCase()===".gif"))throw new b("文字配图模式追加的图片不支持 .gif(编辑器图片入口只接受 jpg/jpeg/png/webp)");const f=Nt(i);await t.goto(At);await t.wait({time:1});await t.evaluate("() => { try { window.onbeforeunload = null; } catch (e) {} location.reload(); }").catch(()=>{return});let x="";for(let c=0;c<30;c++){await t.wait({time:0.5});x=await t.evaluate("() => location.href");if(x.includes("creator.xiaohongshu.com"))break}if(!x.includes("creator.xiaohongshu.com")){await t.screenshot({path:"/tmp/xhs_publish_redirect_debug.png"});throw Error(`Redirected away from creator center (landed on ${x}) — session may have expired. `+"Re-capture browser login via: ppcli xiaohongshu creator-profile. Debug screenshot: /tmp/xhs_publish_redirect_debug.png")}const S=await Dt(t);if((await zt(t,S?.ok?5000:2000)).state==="video_surface"){await t.screenshot({path:"/tmp/xhs_publish_tab_debug.png"});const c=S?.ok?`clicked "${S.text}"`:`visible candidates: ${(S?.visibleTexts||[]).join(" | ")||"none"}`;throw Error("Still on the video publish page after trying to select 图文. "+`Details: ${c}. Debug screenshot: /tmp/xhs_publish_tab_debug.png`)}const E=await Xt(t);let C=v;if(m)C=await Vt(t,w,v);else{const c=typeof t.startNetworkCapture==="function"?await t.startNetworkCapture("").catch(()=>!1):!1,g=await nt(t,f);if(!g.ok){await t.screenshot({path:"/tmp/xhs_publish_upload_debug.png"});throw new u(`图片注入失败:${g.error??"unknown"}。`+"直接重新运行本 publish 命令即可(会自动重置发布页重传);请勿手动修改当前页面。"+"Debug: /tmp/xhs_publish_upload_debug.png")}await t.wait({time:X/1000});const y=await dt(t,f.length,c);if(!y.ok){await t.screenshot({path:"/tmp/xhs_publish_upload_debug.png"});throw new u(`图片上传未全部完成:只确认 ${y.completed}/${f.length} 张传到小红书 CDN,`+"继续发布会丢图(通常只剩封面)。直接重新运行本 publish 命令即可(会自动重置发布页重传);"+"请勿手动修改当前页面。Debug: /tmp/xhs_publish_upload_debug.png")}await rt(t);if(E.length){await ct(t,E);await t.wait({time:0.5})}const M=await at(t);if(M&&typeof M.count==="number"&&M.count>f.length){await t.screenshot({path:"/tmp/xhs_publish_dup_debug.png"});throw new u(`清掉恢复态旧图后编辑器内仍有 ${M.count} 张图,超过本次注入的 ${f.length} 张。`+"直接重新运行本 publish 命令即可(会自动重置发布页);请勿手动修改当前页面。Debug: /tmp/xhs_publish_dup_debug.png")}}if(!await Ht(t)){await t.screenshot({path:"/tmp/xhs_publish_form_debug.png"});throw new u("Editing form did not appear after image acquisition. The page layout may have changed. Debug screenshot: /tmp/xhs_publish_form_debug.png")}if(m)await st(t,w.length,"文字配图 generated images");if(m&&f.length>0){const c=typeof t.startNetworkCapture==="function"?await t.startNetworkCapture("").catch(()=>!1):!1,g=await nt(t,f);if(!g.ok){await t.screenshot({path:"/tmp/xhs_publish_append_debug.png"});throw new u(`追加图片失败:${g.error??"unknown"}。`+"直接重新运行本 publish 命令即可(会自动重置发布页重传);请勿手动修改当前页面。"+"Debug: /tmp/xhs_publish_append_debug.png")}await t.wait({time:X/1000});const y=await dt(t,f.length,c);if(!y.ok){await t.screenshot({path:"/tmp/xhs_publish_append_debug.png"});throw new u(`追加图片上传未全部完成:只确认 ${y.completed}/${f.length} 张传到小红书 CDN。`+"直接重新运行本 publish 命令即可(会自动重置发布页重传);请勿手动修改当前页面。"+"Debug: /tmp/xhs_publish_append_debug.png")}await rt(t);await st(t,w.length+f.length,"文字配图 appended images")}if(m&&E.length){await ct(t,E);await t.wait({time:0.5})}await ot(t,Z,r,"title");await I(t,0.6);await ot(t,tt,o,"content");await I(t,0.6);let P=[];if(l.length)P=await bt(t,tt,a);await _t(t,e);await I(t,1,0.6);const D=await kt(t,["xhs-publish-btn"]);if(D){await Tt(t,D.x,D.y);await I(t,0.4)}const J=s?["暂存离开","存草稿"]:["发布","发布笔记"],h=await t.evaluate(`
|
|
412
393
|
(cfg => {
|
|
413
394
|
const { isDraftMode, publishNames, draftNames, labels } = cfg;
|
|
414
395
|
const isVisible = (el) => {
|
|
@@ -447,7 +428,7 @@ import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/to
|
|
|
447
428
|
}
|
|
448
429
|
}
|
|
449
430
|
return { ok: false, via: 'none', hosts: hosts.length, lastMethodError };
|
|
450
|
-
})(${JSON.stringify({isDraftMode:s,publishNames:
|
|
431
|
+
})(${JSON.stringify({isDraftMode:s,publishNames:Et,draftNames:Ct,labels:J})})
|
|
451
432
|
`);if(!h?.ok){if(s){if(await t.evaluate(`
|
|
452
433
|
(() => {
|
|
453
434
|
const labels = ['返回', '关闭', '取消', '离开'];
|
|
@@ -486,7 +467,7 @@ import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/to
|
|
|
486
467
|
}
|
|
487
468
|
return false;
|
|
488
469
|
}
|
|
489
|
-
`)){h.ok=!0;h.via="auto-save"}}}}if(!h?.ok){await t.screenshot({path:"/tmp/xhs_publish_submit_debug.png"});const c=h?.via?` (via=${h.via})`:"",g=h?.error?`, error=${h.error}`:"",y=h?.lastMethodError?`, lastMethodError=${h.lastMethodError}`:"";throw Error(`未能触发「${
|
|
470
|
+
`)){h.ok=!0;h.via="auto-save"}}}}if(!h?.ok){await t.screenshot({path:"/tmp/xhs_publish_submit_debug.png"});const c=h?.via?` (via=${h.via})`:"",g=h?.error?`, error=${h.error}`:"",y=h?.lastMethodError?`, lastMethodError=${h.lastMethodError}`:"";throw Error(`未能触发「${J[0]}」按钮${c}${g}${y}。`+"直接重新运行本 publish 命令即可(会自动重置发布页);请勿手动修改当前页面。"+"Debug: /tmp/xhs_publish_submit_debug.png")}await t.wait({time:4});const T=await t.evaluate("() => location.href"),ft=s?["草稿已保存","暂存成功","保存成功","保存于","图文笔记("]:["发布成功","上传成功"],V=await t.evaluate(`
|
|
490
471
|
(markers => {
|
|
491
472
|
for (const el of document.querySelectorAll('*')) {
|
|
492
473
|
if (el.tagName === 'STYLE' || el.tagName === 'SCRIPT') continue;
|
|
@@ -496,4 +477,4 @@ import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/to
|
|
|
496
477
|
}
|
|
497
478
|
return '';
|
|
498
479
|
})(${JSON.stringify(ft)})
|
|
499
|
-
`),ht=!T.includes("/publish/publish");let
|
|
480
|
+
`),ht=!T.includes("/publish/publish");let R=V.length>0||ht;const q=s?"暂存成功":"发布成功";let p=null,L="";if(!s){const c=await Yt(t,r,R?2:4);p=c.note;L=c.reason;if(p)R=!0}if(!R){if(s)throw new u(`${q}无法确认:未观察到成功提示或提交后跳转。`+(T?`当前 URL: ${T}。`:"当前 URL 为空。")+"先用 `xiaohongshu drafts` 查草稿箱确认是否已存上;确认没有再重新运行本命令,避免堆出重复草稿。");throw new u(`${q}无法确认:未观察到成功提示或提交后跳转,创作者后台也暂未查到同标题笔记(${L||"未回查到"})。`+(T?`当前 URL: ${T}。`:"")+"注意:发布按钮已被触发,笔记仍可能延迟入库。禁止立即重发——请等 1-2 分钟后用 `xiaohongshu creator-notes` 回查本篇标题是否已出现;确认不存在后才重新运行本 publish 命令,否则会重复发布。")}return[{status:`✅ ${q}`,detail:[`"${r}"`,m?`${w.length}张文字配图${f.length?` + ${f.length}张图片`:""}${C&&C!==k?` (${C})`:""}`:`${f.length}张图片`,P.length?`话题: ${P.join(" ")}`:"",p?.id?`笔记ID: ${p.id}`:"",V||(p?"已在创作者后台确认":"")||T||"",p?.id?p.noteUrl?"链接需登录小红书后打开":"链接为创作者后台数据页,需登录":"",!s&&!p?.id?`未回查到笔记ID(${L||"未回查到"}),稍后用 creator-notes 按标题查`:""].filter(Boolean).join(" · "),url:p?.id?p.noteUrl||`https://creator.xiaohongshu.com/statistics/note-detail?noteId=${p.id}`:""}]}});
|