publishport-opencli 1.0.58 → 1.0.60

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
@@ -3209,14 +3209,29 @@
3209
3209
  "name": "title",
3210
3210
  "type": "str",
3211
3211
  "required": true,
3212
- "help": "视频标题(不足 8 字会自动补「你不知道的」,截断到 30 字)"
3212
+ "help": "视频标题,即百家号「作品描述」(不足 8 字会自动补「你不知道的」,截断到 50 字)"
3213
+ },
3214
+ {
3215
+ "name": "declaration",
3216
+ "type": "str",
3217
+ "default": "none",
3218
+ "required": false,
3219
+ "help": "创作声明(百家号必选):none 无需声明 / ai 含AI生成内容 / reprint 转载 / fiction 虚构演绎 / marketing 营销信息 / opinion 个人观点",
3220
+ "choices": [
3221
+ "none",
3222
+ "ai",
3223
+ "reprint",
3224
+ "fiction",
3225
+ "marketing",
3226
+ "opinion"
3227
+ ]
3213
3228
  },
3214
3229
  {
3215
3230
  "name": "schedule",
3216
3231
  "type": "str",
3217
3232
  "default": "",
3218
3233
  "required": false,
3219
- "help": "定时发布时间(ISO8601 或 Unix 秒;不填即立即发布)"
3234
+ "help": "定时发布时间(ISO8601 或 Unix 秒,须在当前时间后 1 小时至 7 天内,按北京时间选择;不填即立即发布)"
3220
3235
  },
3221
3236
  {
3222
3237
  "name": "timeout",
@@ -3229,6 +3244,8 @@
3229
3244
  "columns": [
3230
3245
  "status",
3231
3246
  "title",
3247
+ "article_id",
3248
+ "review_status",
3232
3249
  "url"
3233
3250
  ],
3234
3251
  "type": "js",
@@ -49276,6 +49293,12 @@
49276
49293
  "required": false,
49277
49294
  "help": "仅保存草稿(微信公众号目前只支持草稿,此参数保留兼容性)"
49278
49295
  },
49296
+ {
49297
+ "name": "cover",
49298
+ "type": "str",
49299
+ "required": false,
49300
+ "help": "封面图:本机图片路径(相对路径先按正文文件所在目录解析)或图片 URL。先转存到微信图床,再按 2.35:1 与 1:1 居中裁切填入封面;转存或裁切失败则报错且不生成草稿。不传则草稿没有封面,草稿箱会提示「图文内容不完整」"
49301
+ },
49279
49302
  {
49280
49303
  "name": "execute",
49281
49304
  "type": "boolean",
@@ -1,57 +1,69 @@
1
- import{cli as d,Strategy as f}from"@jackwener/opencli/registry";import{ArgumentError as h,CommandExecutionError as a}from"@jackwener/opencli/errors";import{resolveVideoFile as m,setVideoInput as v,unwrap as c,currentUrl as p,parseScheduleDate as y,clickByText as u,waitForUrlIncludes as s,waitForSelector as o,videoTimeoutArg as b}from"../_shared/video-publish.js";const x="https://baijiahao.baidu.com/builder/rc/edit?type=videoV2",S=["div[class^='video-main-container'] input","input[type='file']"];async function T(t,i){let e=i;if(e.length<=8)e+=" 你不知道的";e=e.slice(0,30);if(!Boolean(c(await t.evaluate(`
2
- ((text) => {
3
- const input = document.querySelector('input[placeholder="添加标题获得更多推荐"], textarea[placeholder="添加标题获得更多推荐"], [placeholder*="添加标题"]');
4
- if (!input) return false;
5
- input.focus();
6
- const proto = input.tagName === 'TEXTAREA' ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;
7
- const setter = Object.getOwnPropertyDescriptor(proto, 'value') && Object.getOwnPropertyDescriptor(proto, 'value').set;
8
- if (setter) setter.call(input, text); else input.value = text;
9
- input.dispatchEvent(new Event('input', { bubbles: true }));
10
- input.dispatchEvent(new Event('change', { bubbles: true }));
11
- return true;
12
- })(${JSON.stringify(e)})
13
- `))))throw new a("找不到百家号标题输入框");return e}async function E(t){const i=Date.now()+300000;while(Date.now()<i){const e=c(await t.evaluate(`
1
+ import{cli as j,Strategy as x}from"@jackwener/opencli/registry";import{ArgumentError as m,CommandExecutionError as o}from"@jackwener/opencli/errors";import{resolveVideoFile as q,setVideoInput as D,unwrap as l,currentUrl as E,parseScheduleDate as I,waitForUrlIncludes as J,waitForSelector as w,videoTimeoutArg as R}from"../_shared/video-publish.js";import{clickControl as U,verifyControl as f}from"../_shared/publish-controls.js";const M="https://baijiahao.baidu.com/builder/rc/edit?type=videoV2",k=["div[class^='video-main-container'] input","input[type='file']"],L=50,y='#formMain [data-lexical-editor="true"], #formMain [class*="contentEditable"][contenteditable="true"]';async function P(t,i){let e=i;if(e.length<=8)e+=" 你不知道的";e=Array.from(e).slice(0,L).join("");if(!await w(t,y,120000))throw new o("百家号发布停在「填写标题」:120 秒内未出现「作品描述」输入框,页面可能再次改版");if(!l(await t.evaluate(`
2
+ ((sel) => {
3
+ const ed = document.querySelector(sel);
4
+ if (!ed) return false;
5
+ ed.focus();
6
+ const range = document.createRange();
7
+ range.selectNodeContents(ed);
8
+ const s = window.getSelection();
9
+ s.removeAllRanges();
10
+ s.addRange(range);
11
+ return document.activeElement === ed;
12
+ })(${JSON.stringify(y)})
13
+ `)))throw new o("百家号发布停在「填写标题」:「作品描述」输入框无法获得焦点");await t.insertText(e);await t.wait({time:1});const r=String(l(await t.evaluate(`
14
+ ((sel) => { const ed = document.querySelector(sel); return ed ? ed.innerText.trim() : ''; })(${JSON.stringify(y)})
15
+ `))||"");if(r!==e)throw new o(`百家号发布停在「填写标题」:写入后回读不一致(期望「${e}」,实际「${r}」)`);return e}async function H(t,i){const e=Date.now()+i;while(Date.now()<e){const n=l(await t.evaluate(`
14
16
  (() => {
15
- const has = (txt) => Array.from(document.querySelectorAll('div .cover-overlay'))
16
- .some((el) => (el.innerText || el.textContent || '').includes(txt));
17
- if (has('上传失败')) return 'failed';
18
- if (has('上传中')) return 'uploading';
19
- return 'done';
17
+ const overlays = Array.from(document.querySelectorAll('[class*="tabCoverOverlay"], [class*="tabCoverPrecent"]'));
18
+ if (overlays.some((el) => (el.innerText || el.textContent || '').includes('失败'))) return 'failed';
19
+ return overlays.length ? 'uploading' : 'done';
20
20
  })()
21
- `));if(e==="failed")return!1;if(e==="done")return!0;await t.wait({time:2})}return!1}async function D(t,i){const e=i.getDate(),n=i.getMonth()+1,l=e>9?`${n}月${e}日`:`${n}月0${e}日`;if(!await o(t,"div.select-wrap",5000))throw new a("百家号定时选择器未出现");for(let r=0;r<3;r++){await t.evaluate("(() => { const w = document.querySelectorAll('div.select-wrap')[0]; if (w) w.click(); })()");if(await o(t,"div.rc-virtual-list div.cheetah-select-item",5000))break}await t.wait({time:2});await t.evaluate(`
22
- ((wantDay) => {
23
- for (const el of document.querySelectorAll('div.rc-virtual-list div.cheetah-select-item')) {
24
- if ((el.innerText || el.textContent || '').includes(wantDay)) { el.click(); return true; }
25
- }
26
- return false;
27
- })(${JSON.stringify(l)})
28
- `);await t.wait({time:2});for(let r=0;r<3;r++){await t.evaluate("(() => { const w = document.querySelectorAll('div.select-wrap')[1]; if (w) w.click(); })()");if(await o(t,"div.rc-virtual-list div.rc-virtual-list-holder-inner",5000))break}await t.wait({time:2});await t.evaluate(`
29
- (() => {
30
- const opts = Array.from(document.querySelectorAll('div.rc-virtual-list div.cheetah-select-item-option'))
31
- .filter((el) => el.offsetParent !== null);
32
- if (!opts.length) return false;
33
- const max = Math.max(1, opts.length - 3);
34
- const idx = Math.min(opts.length - 1, Math.max(1, Math.floor(Math.random() * (max - 1)) + 1));
35
- opts[idx].click();
36
- return true;
37
- })()
38
- `);await t.wait({time:2});await u(t,"定时发布",{timeoutMs:5000})}async function q(t,i){if(!Boolean(c(await t.evaluate(`
39
- (() => {
40
- const norm = (v) => (v || '').replace(/\\s+/g, ' ').trim();
41
- for (const c of document.querySelectorAll('div.op-btn-outter-content')) {
42
- if (norm(c.innerText || c.textContent).includes('定时发布')) {
43
- const parent = c.parentElement;
44
- const btn = parent ? parent.querySelector('button') : c.querySelector('button');
45
- if (btn) { btn.click(); return true; }
21
+ `));if(n==="failed")return"failed";if(n==="done")return"done";await t.wait({time:2})}return"timeout"}async function V(t){return String(l(await t.evaluate(`
22
+ (() => Array.from(document.querySelectorAll('.cheetah-message-notice, .cheetah-form-item-explain-error'))
23
+ .filter((el) => el.getClientRects().length)
24
+ .map((el) => (el.innerText || '').trim())
25
+ .filter(Boolean)
26
+ .join(' | ')
27
+ .slice(0, 300))()
28
+ `))||"")}async function S(t,i){const e=l(await t.evaluate(`
29
+ (async (title) => {
30
+ const html = await (await fetch('https://baijiahao.baidu.com/builder/rc/edit', { credentials: 'include' })).text();
31
+ const m = html.match(/window\\.__BJH__INIT__AUTH__\\s*=\\s*['"]([^'"]+)['"]/);
32
+ if (!m) return { error: '取不到 token' };
33
+ const qs = new URLSearchParams({ currentPage: '1', pageSize: '20', search: title, type: '', collection: '', dynamic: '1' });
34
+ const j = await (await fetch('https://baijiahao.baidu.com/pcui/article/lists?' + qs, { credentials: 'include', headers: { token: m[1] } })).json();
35
+ if (!j || !j.data) return { error: (j && j.errmsg) || '列表接口无数据' };
36
+ return { rows: (j.data.list || []).filter((a) => a.title === title).map((a) => ({ id: String(a.article_id), status: a.status || '' })) };
37
+ })(${JSON.stringify(i)})
38
+ `));if(!e||e.error)throw new o(`百家号内容列表查询失败:${e?e.error:"无返回"}`);return e.rows}const b={none:"无需声明",ai:"含AI生成内容",reprint:"内容为转载",fiction:"含虚构演绎内容",marketing:"内容含营销信息",opinion:"个人观点,仅供参考"},C='input[placeholder="请选择创作声明"]';async function u(t,i,e,n){const r=l(await t.evaluate(`
39
+ ((sel, text) => {
40
+ const hits = [...document.querySelectorAll(sel)]
41
+ .filter((e) => e.getClientRects().length && e.textContent.trim() === text);
42
+ if (hits.length !== 1) return '期望唯一控件「' + text + '」,找到 ' + hits.length;
43
+ if (hits[0].disabled || /disabled/.test(hits[0].className)) return '控件「' + text + '」不可用';
44
+ hits[0].click();
45
+ return 'ok';
46
+ })(${JSON.stringify(i)}, ${JSON.stringify(e)})
47
+ `));if(r!=="ok")throw new o(`百家号发布停在「${n}」:${r};已停止提交`)}async function B(t,i){const e=b[i],n=".cheetah-modal div.cursor-pointer";await U(t,C);await f(t,`[...document.querySelectorAll(${JSON.stringify(n)})].some(e => e.getClientRects().length && e.textContent.trim() === ${JSON.stringify(e)})`,"「创作声明」弹窗");await u(t,n,e,"创作声明");await f(t,`[...document.querySelectorAll(${JSON.stringify(n)})].some(e => e.getClientRects().length && e.textContent.trim() === ${JSON.stringify(e)} && e.querySelector('.cheetah-radio-wrapper-checked'))`,`创作声明「${e}」`);await u(t,".cheetah-modal .cheetah-btn-primary","确定","创作声明");await f(t,`(document.querySelector(${JSON.stringify(C)})?.value || '').includes(${JSON.stringify(e)})`,`创作声明「${e}」`)}const v=".cheetah-modal-confirm";function O(t){const i=new Date(t.getTime()+28800000);return[`${i.getUTCMonth()+1}月${i.getUTCDate()}日`,`${i.getUTCHours()}点`,`${i.getUTCMinutes()}分`]}async function F(t,i,e){const n=`${v} .cheetah-select-selector`;await t.evaluate(`document.querySelectorAll(${JSON.stringify(n)})[${i}]?.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }))`);for(let r=0;r<30;r++){await t.wait({time:0.3});const s=l(await t.evaluate(`
48
+ ((label) => {
49
+ const dd = Array.from(document.querySelectorAll('.cheetah-select-dropdown'))
50
+ .filter((d) => d.getClientRects().length && !d.className.includes('hidden')).pop();
51
+ if (!dd) return 'no-dropdown';
52
+ const opt = Array.from(dd.querySelectorAll('.cheetah-select-item-option')).find((o) => o.textContent.trim() === label);
53
+ if (opt) {
54
+ if (opt.className.includes('disabled')) return 'disabled';
55
+ return 'visible';
46
56
  }
47
- }
48
- return false;
49
- })()
50
- `))))throw new a("找不到百家号「定时发布」入口");if(!await o(t,"div.select-wrap",3000))throw new a("百家号定时面板未展开");await t.wait({time:2});await D(t,i)}d({site:"baijiahao",name:"publish",access:"write",description:"发布视频到百家号(一条命令完成上传+填写+发布;可选定时)",domain:"baijiahao.baidu.com",strategy:f.COOKIE,browser:!0,navigateBefore:!1,args:[{name:"video",required:!0,positional:!0,help:"视频文件路径"},{name:"title",required:!0,help:"视频标题(不足 8 字会自动补「你不知道的」,截断到 30 字)"},{name:"schedule",default:"",help:"定时发布时间(ISO8601 或 Unix 秒;不填即立即发布)"},b()],columns:["status","title","url"],func:async(t,i)=>{const e=String(i.title??"").trim();if(!e)throw new h("--title is required");const n=m(i.video),l=y(i.schedule);await t.goto(x);if(!await s(t,"builder/rc/edit",60000))throw new a("未能进入百家号视频编辑页(登录态可能失效,请先 ppcli baijiahao login)");if(!await o(t,"div[class^='video-main-container'] input, input[type='file']",30000))throw new a("百家号视频上传输入框未出现");await v(t,S,[n]);if(!await o(t,"div#formMain",60000))throw new a("百家号视频发布表单未出现");await t.wait({time:1});const r=await T(t,e);if(!await E(t))throw new a(`百家号视频上传失败: ${n}`);const w=Date.now()+120000;while(Date.now()<w){if(Boolean(c(await t.evaluate("(() => !!document.querySelector('div.cheetah-spin-container img'))()"))))break;await t.wait({time:3})}if(l)await q(t,l);else await u(t,"发布",{exact:!0,timeoutMs:1e4});await t.wait({time:2});if(Boolean(c(await t.evaluate(`
57
+ const holder = dd.querySelector('.rc-virtual-list-holder');
58
+ if (!holder || holder.scrollTop + holder.clientHeight >= holder.scrollHeight) return 'missing';
59
+ holder.scrollTop += holder.clientHeight / 2;
60
+ return 'scrolled';
61
+ })(${JSON.stringify(e)})
62
+ `));if(s==="visible"){await u(t,".cheetah-select-dropdown .cheetah-select-item-option",e,"定时发布");let c="";for(let h=0;h<10;h++){await t.wait({time:0.3});c=String(l(await t.evaluate(`document.querySelectorAll(${JSON.stringify(n)})[${i}]?.textContent.trim() || ''`))||"");if(c===e)return}throw new o(`百家号发布停在「定时发布」:选择「${e}」后显示为「${c}」;已停止提交`)}if(s==="missing"||s==="disabled")throw new o(`百家号发布停在「定时发布」:可选时间里没有「${e}」(百家号只允许当前时间后 1 小时至 7 天)`)}throw new o(`百家号发布停在「定时发布」:时间下拉中未找到「${e}」`)}async function W(t,i){await u(t,"button.cheetah-btn","定时发布","定时发布");await f(t,`[...document.querySelectorAll(${JSON.stringify(v)})].some(e => e.getClientRects().length && e.textContent.includes('定时发文'))`,"「定时发文」弹窗");const e=O(i);for(let n=0;n<e.length;n++)await F(t,n,e[n]);await u(t,`${v} .cheetah-btn-primary`,"定时发布","定时发布")}j({site:"baijiahao",name:"publish",access:"write",description:"发布视频到百家号(一条命令完成上传+填写+发布;可选定时)",domain:"baijiahao.baidu.com",strategy:x.COOKIE,browser:!0,navigateBefore:!1,args:[{name:"video",required:!0,positional:!0,help:"视频文件路径"},{name:"title",required:!0,help:"视频标题,即百家号「作品描述」(不足 8 字会自动补「你不知道的」,截断到 50 字)"},{name:"declaration",default:"none",choices:Object.keys(b),help:"创作声明(百家号必选):none 无需声明 / ai 含AI生成内容 / reprint 转载 / fiction 虚构演绎 / marketing 营销信息 / opinion 个人观点"},{name:"schedule",default:"",help:"定时发布时间(ISO8601 或 Unix 秒,须在当前时间后 1 小时至 7 天内,按北京时间选择;不填即立即发布)"},R()],columns:["status","title","article_id","review_status","url"],func:async(t,i)=>{const e=String(i.title??"").trim();if(!e)throw new m("--title is required");const n=q(i.video),r=I(i.schedule);if(r&&(r.getTime()<Date.now()+3600000||r.getTime()>Date.now()+604800000))throw new m("百家号视频定时发布时间须在当前时间后 1 小时至 7 天内");const s=String(i.declaration||"none");if(!Object.hasOwn(b,s))throw new m(`不支持的 --declaration: ${s}`);await t.goto(M);if(!await J(t,"builder/rc/edit",60000))throw new o("未能进入百家号视频编辑页(登录态可能失效,请先 ppcli baijiahao login)");if(!await w(t,"div[class^='video-main-container'] input, input[type='file']",30000))throw new o("百家号视频上传输入框未出现");await D(t,k,[n]);if(!await w(t,"div#formMain",60000))throw new o("百家号发布停在「上传视频」:选择文件后 60 秒内未出现发布表单");const c=await P(t,e),h=Math.max(60,Number(i.timeout)||540)*1000,p=await H(t,h);if(p==="failed")throw new o(`百家号发布停在「上传视频」:平台提示上传失败(${n})`);if(p==="timeout")throw new o(`百家号发布停在「上传视频」:${h/1000} 秒内未上传完成`,"大视频可调大 --timeout;本次未提交,可直接重试");if(!await w(t,'#formMain [class*="coverWrapper"] img',120000))throw new o("百家号发布停在「封面」:上传完成后 120 秒内未生成封面");await B(t,s);const g=new Set((await S(t,c)).map((a)=>a.id));if(r)await W(t,r);else await u(t,'button[data-testid="publish-btn"]',"发布","点击发布");await t.wait({time:2});if(Boolean(l(await t.evaluate(`
51
63
  (() => {
52
64
  for (const el of document.querySelectorAll('div.passMod_dialog-container')) {
53
65
  if (el.offsetParent !== null && (el.innerText || '').includes('百度安全验证')) return true;
54
66
  }
55
67
  return false;
56
68
  })()
57
- `))))throw new a("百家号出现百度安全验证,请在窗口内手动完成后重试");if(!await s(t,"builder/rc/clue",8000))throw new a("百家号发布未确认成功(未跳转到内容管理页),请检查页面状态");return[{status:l?"✅ 定时发布已提交":"✅ 发布成功",title:r,url:await p(t)}]}});
69
+ `))))throw new o("百家号发布停在「点击发布」:出现百度安全验证,请在窗口内手动完成后重试");const T=new Set,A=Date.now()+90000;let d=null;while(Date.now()<A){const a=await V(t);if(a)T.add(a);const _=await E(t);if(/发布成功/.test(a)||_.includes("builder/rc/clue")||_.includes("builder/rc/content")){d=(await S(t,c)).find((N)=>!g.has(N.id))||null;if(d)break}await t.wait({time:2})}if(!d)d=(await S(t,c)).find((a)=>!g.has(a.id))||null;if(!d){const a=[...T].join(" | ");throw new o(`百家号发布停在「确认结果」:点击发布后 90 秒内容列表中未出现该作品${a?`,页面提示:${a}`:""}`,"先用 ppcli baijiahao lists --search <标题> 回查,再决定是否重发")}return[{status:r?`✅ 定时发布已提交(北京时间 ${O(r).join(" ")})`:"✅ 发布成功",title:c,article_id:d.id,review_status:d.status,url:"https://baijiahao.baidu.com/builder/rc/content"}]}});
@@ -1 +1 @@
1
- import{CliError as l,CommandExecutionError as x}from"@jackwener/opencli/errors";import{cli as k,Strategy as b}from"@jackwener/opencli/registry";import{formatImageReport as N,publishArticle as q}from"../_shared/article/publish.js";import{readFile as M,stat as T}from"node:fs/promises";import{rememberArticleFile as v}from"../_shared/article/images.js";function P(t){if(!t.execute)throw new l("INVALID_INPUT","微信公众号写操作需要 --execute 确认,避免误发。注意:本报错仅表示缺少 --execute,并未校验其余参数,不能当 dry-run 预览用")}async function A(t){const i=typeof t.text==="string"?t.text:void 0,e=typeof t.file==="string"?t.file:void 0;if(i&&e)throw new l("INVALID_INPUT","请只提供 <text> 或 --file 中的一种,不能同时使用。");let n=i??"";if(e){v(e);let r;try{r=await T(e)}catch{throw new l("INVALID_INPUT",`文件不存在:${e}`)}if(!r.isFile())throw new l("INVALID_INPUT",`路径不是可读文本文件:${e}`);let o;try{o=await M(e)}catch{throw new l("INVALID_INPUT",`文件无法读取:${e}`)}try{n=new TextDecoder("utf-8",{fatal:!0}).decode(o)}catch{throw new l("INVALID_INPUT",`文件无法解码为 UTF-8:${e}`)}}if(!n.trim())throw new l("INVALID_INPUT","正文不能为空。");return n}function U(t,i,e,n,r={}){return[{status:"success",outcome:n,message:t,target_type:i,target:e,...r}]}export const weixinProfile={home:"https://mp.weixin.qq.com",outputFormat:"html",preprocessConfig:{removeLinks:!0,keepLinkDomains:["mp.weixin.qq.com","weixin.qq.com"],compactHtml:!0},image:{skip:["mmbiz.qpic.cn","mmbiz.qlogo.cn"],uploadFn:async(t,i)=>{const e=document.documentElement.innerHTML,n=e.match(/data:\s*\{[\s\S]*?t:\s*["']([^"']+)["']/),r=e.match(/ticket:\s*["']([^"']+)["']/),o=e.match(/user_name:\s*["']([^"']+)["']/),c=e.match(/time:\s*["'](\d+)["']/);if(!n)throw Error("微信图片上传:页面中未找到 token,请确认已登录 mp.weixin.qq.com。");const a=n[1],m=r?r[1]:"",s=o?o[1]:"",p=c?Number(c[1]):Math.floor(Date.now()/1000),u=await fetch(t,{credentials:"omit"});if(!u.ok)throw Error("图片下载失败:"+t+"(HTTP "+u.status+")");const h=await u.blob(),_=Date.now(),w=_+".jpg",d=new FormData;d.append("type",h.type||"image/jpeg");d.append("id",String(_));d.append("name",w);d.append("lastModifiedDate",new Date().toString());d.append("size",String(h.size));d.append("file",h,w);const y=Date.now(),I="https://mp.weixin.qq.com/cgi-bin/filetransfer?action=upload_material&f=json&scene=8&writetype=doublewrite&groupid=1&ticket_id="+encodeURIComponent(s)+"&ticket="+encodeURIComponent(m)+"&svr_time="+p+"&token="+encodeURIComponent(a)+"&lang=zh_CN&seq="+y+"&t="+Math.random(),g=await fetch(I,{method:"POST",credentials:"include",body:d}),f=await g.json().catch(()=>({}));if(!g.ok||f.base_resp?.err_msg!=="ok"||!f.cdn_url)throw Error("微信图片上传失败:"+t+"("+(f.base_resp?.err_msg||"HTTP "+g.status)+")");return{url:f.cdn_url}}},checkAuth:async(t)=>{const e=await(await fetch("https://mp.weixin.qq.com/",{method:"GET",credentials:"include"})).text(),n=e.match(/user_name:\s*["']([^"']+)["']/),r=e.match(/nick_name:\s*["']([^"']+)["']/);if(!n&&!r)return{isAuthenticated:!1};const o=e.match(/class="weui-desktop-account__thumb"[^>]*src="([^"]+)"/),c=e.match(/head_img:\s*['"]([^'"]+)['"]/);let a=o?o[1]:c?c[1]:"";if(a.startsWith("http://"))a=a.replace("http://","https://");return{isAuthenticated:!0,userId:n?n[1]:"",username:r?r[1]:"",avatar:a}},publish:async(t,i)=>{const n=document.documentElement.innerHTML.match(/data:\s*\{[\s\S]*?t:\s*["']([^"']+)["']/);if(!n)return{ok:!1,stage:"auth",message:"页面中未找到 token,请确认已登录 mp.weixin.qq.com。"};const r=n[1],o=t.content,c=new URLSearchParams({token:r,lang:"zh_CN",f:"json",ajax:"1",random:String(Math.random()),AppMsgId:"",count:"1",data_seq:"0",operate_from:"Chrome",isnew:"0",ad_video_transition0:"",can_reward0:"0",related_video0:"",is_video_recommend0:"-1",title0:t.title,author0:"",writerid0:"0",fileid0:"",digest0:"",auto_gen_digest0:"1",content0:o,sourceurl0:"",need_open_comment0:"1",only_fans_can_comment0:"0",cdn_url0:"",cdn_235_1_url0:"",cdn_1_1_url0:"",cdn_url_back0:"",crop_list0:"",music_id0:"",video_id0:"",voteid0:"",voteismlt0:"",supervoteid0:"",cardid0:"",cardquantity0:"",cardlimit0:"",vid_type0:"",show_cover_pic0:"0",shortvideofileid0:"",copyright_type0:"0",releasefirst0:"",platform0:"",reprint_permit_type0:"",allow_reprint0:"",allow_reprint_modify0:"",original_article_type0:"",ori_white_list0:"",free_content0:"",fee0:"0",ad_id0:"",guide_words0:"",is_share_copyright0:"0",share_copyright_url0:"",source_article_type0:"",reprint_recommend_title0:"",reprint_recommend_content0:"",share_page_type0:"0",share_imageinfo0:'{"list":[]}',share_video_id0:"",dot0:"{}",share_voice_id0:"",insert_ad_mode0:"",categories_list0:"[]"}),a=await fetch("https://mp.weixin.qq.com/cgi-bin/operate_appmsg?t=ajax-response&sub=create&type=77&token="+encodeURIComponent(r)+"&lang=zh_CN",{method:"POST",credentials:"include",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:c});var m=await a.text(),s=null;try{s=JSON.parse(m)}catch(w){}if(!a.ok||!s||!s.appMsgId){var p=s&&(s.ret!=null?s.ret:s.base_resp&&s.base_resp.ret),u={"-6":"请输入验证码","-8":"请输入验证码","-1":"系统错误,请注意备份内容后重试","-2":"参数错误,请注意备份内容后重试","-99":"内容超出字数,请调整","200003":"登录态超时,请重新登录","64507":"内容不能包含外部链接","64702":"标题超出 64 字长度限制","64705":"内容超出字数,请调整"},h=p!=null&&u[String(p)]||"发布失败(错误码:"+p+"):"+m.slice(0,200);return{ok:!1,stage:"publish",status:a.status,message:h}}const _="https://mp.weixin.qq.com/cgi-bin/appmsg?t=media/appmsg_edit&action=edit&type=77&appmsgid="+s.appMsgId+"&token="+encodeURIComponent(r)+"&lang=zh_CN";return{ok:!0,id:String(s.appMsgId),url:_,draft:!0}}},weixinAuthProfile={home:weixinProfile.home,checkAuth:weixinProfile.checkAuth};k({site:"weixin",name:"article",access:"write",description:"通过 API 把文章发布到微信公众号草稿箱。正文默认 Markdown,外链图片自动转存到微信 CDN。",domain:"mp.weixin.qq.com",strategy:b.COOKIE,browser:!0,args:[{name:"title",positional:!0,required:!0,help:"文章标题(最长 64 字)"},{name:"text",positional:!0,help:"文章正文(默认 Markdown;加 --html 则当 HTML 处理)"},{name:"file",help:"正文文件路径(UTF-8,默认 Markdown)"},{name:"html",type:"boolean",help:"把正文当 HTML 处理而不是 Markdown"},{name:"draft",type:"boolean",help:"仅保存草稿(微信公众号目前只支持草稿,此参数保留兼容性)"},{name:"execute",type:"boolean",help:"实际执行发布。不加此参数时命令拒绝写入。"}],columns:["status","outcome","message","target_type","target","created_target","created_url"],func:async(t,i)=>{if(!t)throw new x("微信公众号 article 命令需要浏览器会话。");P(i);const e=String(i.title??"").trim();if(!e)throw new l("INVALID_INPUT","文章标题不能为空。");const n=await A(i),r=!0,o=await q(t,{title:e,body:n,format:i.html?"html":"markdown",draftOnly:r,profile:weixinProfile}),c=o.images.uploaded.length|0,a=o.images.failed.length|0;let m="已保存微信公众号草稿";if(c||a)m+="·图片:"+c+" 张已转存"+(a?","+a+" 张失败":"");m+=N(o.images);return U(m,"article","","draft",{created_target:"article:"+o.id,created_url:o.url})}});
1
+ import{CliError as y,CommandExecutionError as A}from"@jackwener/opencli/errors";import{cli as U,Strategy as C}from"@jackwener/opencli/registry";import{formatImageReport as D,publishArticle as z}from"../_shared/article/publish.js";import{readFile as E,stat as R}from"node:fs/promises";import{rememberArticleFile as j}from"../_shared/article/images.js";function F(r){if(!r.execute)throw new y("INVALID_INPUT","微信公众号写操作需要 --execute 确认,避免误发。注意:本报错仅表示缺少 --execute,并未校验其余参数,不能当 dry-run 预览用")}async function O(r){const c=typeof r.text==="string"?r.text:void 0,e=typeof r.file==="string"?r.file:void 0;if(c&&e)throw new y("INVALID_INPUT","请只提供 <text> 或 --file 中的一种,不能同时使用。");let s=c??"";if(e){j(e);let n;try{n=await R(e)}catch{throw new y("INVALID_INPUT",`文件不存在:${e}`)}if(!n.isFile())throw new y("INVALID_INPUT",`路径不是可读文本文件:${e}`);let o;try{o=await E(e)}catch{throw new y("INVALID_INPUT",`文件无法读取:${e}`)}try{s=new TextDecoder("utf-8",{fatal:!0}).decode(o)}catch{throw new y("INVALID_INPUT",`文件无法解码为 UTF-8:${e}`)}}if(!s.trim())throw new y("INVALID_INPUT","正文不能为空。");return s}function H(r,c,e,s,n={}){return[{status:"success",outcome:s,message:r,target_type:c,target:e,...n}]}export const weixinProfile={home:"https://mp.weixin.qq.com",outputFormat:"html",preprocessConfig:{removeLinks:!0,keepLinkDomains:["mp.weixin.qq.com","weixin.qq.com"],compactHtml:!0},image:{skip:["mmbiz.qpic.cn","mmbiz.qlogo.cn"],uploadFn:async(r,c)=>{const e=document.documentElement.innerHTML,s=e.match(/data:\s*\{[\s\S]*?t:\s*["']([^"']+)["']/),n=e.match(/ticket:\s*["']([^"']+)["']/),o=e.match(/user_name:\s*["']([^"']+)["']/),i=e.match(/time:\s*["'](\d+)["']/);if(!s)throw Error("微信图片上传:页面中未找到 token,请确认已登录 mp.weixin.qq.com。");const u=s[1],x=n?n[1]:"",h=o?o[1]:"",I=i?Number(i[1]):Math.floor(Date.now()/1000),l=await fetch(r,{credentials:"omit"});if(!l.ok)throw Error("图片下载失败:"+r+"(HTTP "+l.status+")");const v=await l.blob(),N=Date.now(),q=N+".jpg",_=new FormData;_.append("type",v.type||"image/jpeg");_.append("id",String(N));_.append("name",q);_.append("lastModifiedDate",new Date().toString());_.append("size",String(v.size));_.append("file",v,q);const a=Date.now(),P="https://mp.weixin.qq.com/cgi-bin/filetransfer?action=upload_material&f=json&scene=8&writetype=doublewrite&groupid=1&ticket_id="+encodeURIComponent(h)+"&ticket="+encodeURIComponent(x)+"&svr_time="+I+"&token="+encodeURIComponent(u)+"&lang=zh_CN&seq="+a+"&t="+Math.random(),f=await fetch(P,{method:"POST",credentials:"include",body:_}),m=await f.json().catch(()=>({}));if(!f.ok||m.base_resp?.err_msg!=="ok"||!m.cdn_url)throw Error("微信图片上传失败:"+r+"("+(m.base_resp?.err_msg||"HTTP "+f.status)+")");return{url:m.cdn_url}}},checkAuth:async(r)=>{const e=await(await fetch("https://mp.weixin.qq.com/",{method:"GET",credentials:"include"})).text(),s=e.match(/user_name:\s*["']([^"']+)["']/),n=e.match(/nick_name:\s*["']([^"']+)["']/);if(!s&&!n)return{isAuthenticated:!1};const o=e.match(/class="weui-desktop-account__thumb"[^>]*src="([^"]+)"/),i=e.match(/head_img:\s*['"]([^'"]+)['"]/);let u=o?o[1]:i?i[1]:"";if(u.startsWith("http://"))u=u.replace("http://","https://");return{isAuthenticated:!0,userId:s?s[1]:"",username:n?n[1]:"",avatar:u}},publish:async(r,c)=>{const s=document.documentElement.innerHTML.match(/data:\s*\{[\s\S]*?t:\s*["']([^"']+)["']/);if(!s)return{ok:!1,stage:"auth",message:"页面中未找到 token,请确认已登录 mp.weixin.qq.com。"};const n=s[1],o={url:"",u235:"",u11:"",cropList:""},i=r.params&&typeof r.params.cover==="string"?r.params.cover:"";if(i){let a;try{a=await new Promise(function(t,d){const p=new Image;p.onload=function(){t({w:p.naturalWidth,h:p.naturalHeight})};p.onerror=function(){d(Error("封面图加载失败"))};p.src=i})}catch(t){return{ok:!1,stage:"cover",message:"封面图已转存但无法读取尺寸:"+i.slice(0,160)}}if(!(a.w>0&&a.h>0))return{ok:!1,stage:"cover",message:"封面图尺寸无效("+a.w+"×"+a.h+"):"+i.slice(0,160)};const f=[["2.35_1",2.35],["1_1",1]].map(function(t){const d=t[1],p=a.w/a.h;if(p>d){const g=(a.w-a.h*d)/a.w/2;return{ratio:t[0],x1:g,y1:0,x2:1-g,y2:1}}if(p<d){const g=(a.h-a.w/d)/a.h/2;return{ratio:t[0],x1:0,y1:g,x2:1,y2:1-g}}return{ratio:t[0],x1:0,y1:0,x2:1,y2:1}}),m=new URLSearchParams({imgurl:i,size_count:String(f.length)});f.forEach(function(t,d){m.set("size"+d+"_x1",String(t.x1));m.set("size"+d+"_y1",String(t.y1));m.set("size"+d+"_x2",String(t.x2));m.set("size"+d+"_y2",String(t.y2))});m.set("token",n);m.set("lang","zh_CN");m.set("f","json");m.set("ajax","1");const M=await fetch("https://mp.weixin.qq.com/cgi-bin/cropimage?action=crop_multi",{method:"POST",credentials:"include",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:m}),S=await M.text();let w=null;try{w=JSON.parse(S)}catch(t){w=null}const k=w&&Array.isArray(w.result)?w.result:[];if(!M.ok||!w||!w.base_resp||w.base_resp.ret!==0||k.length!==f.length||k.some(function(t){return!t||!t.cdnurl}))return{ok:!1,stage:"cover",status:M.status,message:"封面裁切失败(cropimage crop_multi),未生成草稿",detail:S.slice(0,500)};const T={crop_list:[],crop_list_percent:[]};f.forEach(function(t,d){const p=k[d],g=p.width>0?p.width:a.w,b=p.height>0?p.height:a.h,L=p.file_id||0;T.crop_list.push({ratio:t.ratio,x1:Math.floor(g*t.x1),y1:Math.floor(b*t.y1),x2:Math.floor(g*t.x2),y2:Math.floor(b*t.y2),file_id:L});T.crop_list_percent.push({ratio:t.ratio,x1:t.x1,y1:t.y1,x2:t.x2,y2:t.y2,file_id:L})});o.url=i;o.u235=k[0].cdnurl;o.u11=k[1].cdnurl;o.cropList=JSON.stringify(T)}const u=r.content,x=new URLSearchParams({token:n,lang:"zh_CN",f:"json",ajax:"1",random:String(Math.random()),AppMsgId:"",count:"1",data_seq:"0",operate_from:"Chrome",isnew:"0",ad_video_transition0:"",can_reward0:"0",related_video0:"",is_video_recommend0:"-1",title0:r.title,author0:"",writerid0:"0",fileid0:"",digest0:"",auto_gen_digest0:"1",content0:u,sourceurl0:"",need_open_comment0:"1",only_fans_can_comment0:"0",cdn_url0:o.url,cdn_235_1_url0:o.u235,cdn_16_9_url0:o.url,cdn_1_1_url0:o.u11,cdn_url_back0:o.url,crop_list0:o.cropList,music_id0:"",video_id0:"",voteid0:"",voteismlt0:"",supervoteid0:"",cardid0:"",cardquantity0:"",cardlimit0:"",vid_type0:"",show_cover_pic0:"0",shortvideofileid0:"",copyright_type0:"0",releasefirst0:"",platform0:"",reprint_permit_type0:"",allow_reprint0:"",allow_reprint_modify0:"",original_article_type0:"",ori_white_list0:"",free_content0:"",fee0:"0",ad_id0:"",guide_words0:"",is_share_copyright0:"0",share_copyright_url0:"",source_article_type0:"",reprint_recommend_title0:"",reprint_recommend_content0:"",share_page_type0:"0",share_imageinfo0:'{"list":[]}',share_video_id0:"",dot0:"{}",share_voice_id0:"",insert_ad_mode0:"",categories_list0:"[]"}),h=await fetch("https://mp.weixin.qq.com/cgi-bin/operate_appmsg?t=ajax-response&sub=create&type=77&token="+encodeURIComponent(n)+"&lang=zh_CN",{method:"POST",credentials:"include",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:x});var I=await h.text(),l=null;try{l=JSON.parse(I)}catch(a){}if(!h.ok||!l||!l.appMsgId){var v=l&&(l.ret!=null?l.ret:l.base_resp&&l.base_resp.ret),N={"-6":"请输入验证码","-8":"请输入验证码","-1":"系统错误,请注意备份内容后重试","-2":"参数错误,请注意备份内容后重试","-99":"内容超出字数,请调整","200003":"登录态超时,请重新登录","64507":"内容不能包含外部链接","64702":"标题超出 64 字长度限制","64705":"内容超出字数,请调整"},q=v!=null&&N[String(v)]||"发布失败(错误码:"+v+"):"+I.slice(0,200);return{ok:!1,stage:"publish",status:h.status,message:q}}const _="https://mp.weixin.qq.com/cgi-bin/appmsg?t=media/appmsg_edit&action=edit&type=77&appmsgid="+l.appMsgId+"&token="+encodeURIComponent(n)+"&lang=zh_CN";return{ok:!0,id:String(l.appMsgId),url:_,draft:!0}}},weixinAuthProfile={home:weixinProfile.home,checkAuth:weixinProfile.checkAuth};U({site:"weixin",name:"article",access:"write",description:"通过 API 把文章发布到微信公众号草稿箱。正文默认 Markdown,外链图片自动转存到微信 CDN。",domain:"mp.weixin.qq.com",strategy:C.COOKIE,browser:!0,args:[{name:"title",positional:!0,required:!0,help:"文章标题(最长 64 字)"},{name:"text",positional:!0,help:"文章正文(默认 Markdown;加 --html 则当 HTML 处理)"},{name:"file",help:"正文文件路径(UTF-8,默认 Markdown)"},{name:"html",type:"boolean",help:"把正文当 HTML 处理而不是 Markdown"},{name:"draft",type:"boolean",help:"仅保存草稿(微信公众号目前只支持草稿,此参数保留兼容性)"},{name:"cover",help:"封面图:本机图片路径(相对路径先按正文文件所在目录解析)或图片 URL。先转存到微信图床,再按 2.35:1 与 1:1 居中裁切填入封面;转存或裁切失败则报错且不生成草稿。不传则草稿没有封面,草稿箱会提示「图文内容不完整」"},{name:"execute",type:"boolean",help:"实际执行发布。不加此参数时命令拒绝写入。"}],columns:["status","outcome","message","target_type","target","created_target","created_url"],func:async(r,c)=>{if(!r)throw new A("微信公众号 article 命令需要浏览器会话。");F(c);const e=String(c.title??"").trim();if(!e)throw new y("INVALID_INPUT","文章标题不能为空。");const s=await O(c),n=typeof c.cover==="string"?c.cover.trim():"",o=!0,i=await z(r,{title:e,body:s,format:c.html?"html":"markdown",draftOnly:o,profile:weixinProfile,publishParams:n?{cover:n}:null}),u=i.images.uploaded.length|0,x=i.images.failed.length|0;let h=n?"已保存微信公众号草稿(含封面)":"已保存微信公众号草稿(未设封面,草稿箱会提示内容不完整,可加 --cover 重新生成)";if(u||x)h+="·图片:"+u+" 张已转存"+(x?","+x+" 张失败":"");h+=D(i.images);return H(h,"article","","draft",{created_target:"article:"+i.id,created_url:i.url})}});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "publishport-opencli",
3
- "version": "1.0.58",
3
+ "version": "1.0.60",
4
4
  "publishConfig": {
5
5
  "access": "public",
6
6
  "provenance": false