publishport-opencli 1.0.54 → 1.0.57
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 +8 -1
- package/clis/_shared/article/images.js +5 -5
- package/clis/_shared/article/page-runtime.js +13 -4
- package/clis/_shared/article/publish.js +11 -11
- package/clis/baijiahao/article.js +2 -2
- package/clis/bilibili/article.js +1 -1
- package/clis/bilibili/comment.js +1 -1
- package/clis/cnblogs/article.js +1 -1
- package/clis/csdn/article.js +5 -5
- package/clis/cto51/article.js +1 -1
- package/clis/douyin/publish.js +8 -8
- package/clis/eastmoney/article.js +1 -1
- package/clis/imooc/article.js +3 -3
- package/clis/infoq/article.js +2 -2
- package/clis/jianshu/article.js +1 -1
- package/clis/juejin/article.js +4 -4
- package/clis/medium/article.js +4 -4
- package/clis/oschina/article.js +1 -1
- package/clis/segmentfault/article.js +3 -3
- package/clis/sohu/article.js +1 -1
- package/clis/sohu/attributes.js +1 -1
- package/clis/sohu/categories.js +1 -1
- package/clis/sohu/channels.js +1 -1
- package/clis/sohu/columns.js +1 -1
- package/clis/sohu/mpbp.js +1 -1
- package/clis/sohu/stats.js +5 -17
- package/clis/sohu/topics.js +1 -1
- package/clis/toutiao/article.js +1 -1
- package/clis/wechat-channels/publish.js +111 -22
- package/clis/weibo/article.js +1 -1
- package/clis/weixin/article.js +1 -1
- package/clis/woshipm/article.js +1 -1
- package/clis/xianyu/im.js +1 -1
- package/clis/xiaohongshu/human.js +2 -2
- package/clis/xiaohongshu/publish.js +21 -19
- package/clis/xueqiu/article.js +2 -2
- package/clis/yuque/article.js +1 -1
- package/clis/zhihu/answer.js +1 -1
- package/clis/zhihu/article.js +1 -1
- package/clis/zhihu/write-shared.js +3 -3
- package/dist/src/execution.d.ts +9 -0
- package/dist/src/execution.js +2 -2
- package/package.json +1 -1
package/clis/weibo/article.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{CliError as
|
|
1
|
+
import{CliError as h,CommandExecutionError as x}from"@jackwener/opencli/errors";import{cli as S,Strategy as v}from"@jackwener/opencli/registry";import{formatImageReport as T,publishArticle as P}from"../_shared/article/publish.js";import{readFile as A,stat as O}from"node:fs/promises";import{rememberArticleFile as R}from"../_shared/article/images.js";function U(t){if(!t.execute)throw new h("INVALID_INPUT","微博头条文章写操作需要 --execute 确认,避免误发。注意:本报错仅表示缺少 --execute,并未校验其余参数,不能当 dry-run 预览用")}async function L(t){const c=typeof t.text==="string"?t.text:void 0,a=typeof t.file==="string"?t.file:void 0;if(c&&a)throw new h("INVALID_INPUT","请只提供 <text> 或 --file 中的一种,不能同时使用。");let i=c??"";if(a){R(a);let e;try{e=await O(a)}catch{throw new h("INVALID_INPUT",`文件不存在:${a}`)}if(!e.isFile())throw new h("INVALID_INPUT",`路径不是可读文本文件:${a}`);let u;try{u=await A(a)}catch{throw new h("INVALID_INPUT",`文件无法读取:${a}`)}try{i=new TextDecoder("utf-8",{fatal:!0}).decode(u)}catch{throw new h("INVALID_INPUT",`文件无法解码为 UTF-8:${a}`)}}if(!i.trim())throw new h("INVALID_INPUT","正文不能为空。");return i}function E(t,c,a,i,e={}){return[{status:"success",outcome:i,message:t,target_type:c,target:a,...e}]}export const weiboProfile={home:"https://card.weibo.com/article/v5/editor",outputFormat:"html",preprocessConfig:{compactHtml:!0},image:{skip:["sinaimg.cn","weibo.com"],uploadFn:async(t,c)=>{async function a(){let r=document.documentElement.innerHTML||"",n=r.match(/config:\s*JSON\.parse\('(.+?)'\)/);if(!n){r=await(await fetch("https://card.weibo.com/article/v5/editor",{credentials:"include"})).text();n=r.match(/config:\s*JSON\.parse\('(.+?)'\)/)}if(!n)return"";try{const o=JSON.parse(n[1].replace(/\\'/g,"'").replace(/\\\\/g,"\\"));return o.uid?String(o.uid):""}catch(o){return""}}function i(r){const n=btoa(r+"&"+Date.now()).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,""),o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";let s=n;while(s.length<43)s+=o.charAt(Math.floor(Math.random()*o.length));return s.slice(0,43)}const e=await a();if(!e)throw Error("未取到微博 uid,请先登录微博");if(t.indexOf("data:")===0){const r=c.dataUriToBlob(t),o="https://picupload.weibo.com/interface/pic_upload.php?app=miniblog&s=json&p=1&data=1&url=&markpos=1&logo=0&nick=&file_source=4&_rid="+i(e),l=await(await fetch(o,{method:"POST",credentials:"include",body:r})).json(),d=l&&l.data&&l.data.pics&&l.data.pics.pic_1&&l.data.pics.pic_1.pid;if(!d)throw Error("图片直传失败:"+JSON.stringify(l).slice(0,200));return{url:"https://wx3.sinaimg.cn/large/"+d+".jpg"}}const u=i(e);try{await fetch("https://card.weibo.com/article/v5/aj/editor/plugins/asyncuploadimg?uid="+e+"&_rid="+u,{method:"POST",credentials:"include",headers:{"Content-Type":"application/x-www-form-urlencoded",accept:"application/json, text/plain, */*","SN-REQID":u},body:new URLSearchParams({"urls[0]":t})})}catch(r){}for(let r=0;r<30;r++){const n=i(e),s=await(await fetch("https://card.weibo.com/article/v5/aj/editor/plugins/asyncimginfo?uid="+e+"&_rid="+n,{method:"POST",credentials:"include",headers:{"Content-Type":"application/x-www-form-urlencoded",accept:"application/json, text/plain, */*","SN-REQID":n},body:new URLSearchParams({"urls[0]":t})})).json(),l=s&&s.data&&s.data[0],d=l&&l.task_status_code;if(d===1&&l.pid)return{url:"https://wx3.sinaimg.cn/large/"+l.pid+".jpg"};if(d===2)throw Error("微博图片转存失败:"+t);await new Promise((g)=>setTimeout(g,1000))}throw Error("微博图片转存超时:"+t)}},checkAuth:async(t)=>{const i=(await(await fetch("https://card.weibo.com/article/v5/editor",{credentials:"include"})).text()).match(/config:\s*JSON\.parse\('(.+?)'\)/);if(!i)return{isAuthenticated:!1};let e=null;try{e=JSON.parse(i[1].replace(/\\'/g,"'").replace(/\\\\/g,"\\"))}catch(u){return{isAuthenticated:!1,error:"编辑器 config 解析失败"}}if(!e||!e.uid)return{isAuthenticated:!1};return{isAuthenticated:!0,userId:String(e.uid),username:e.nick||"",avatar:e.avatar_large||""}},publish:async(t,c)=>{async function a(){let m=document.documentElement.innerHTML||"",p=m.match(/config:\s*JSON\.parse\('(.+?)'\)/);if(!p){m=await(await fetch("https://card.weibo.com/article/v5/editor",{credentials:"include"})).text();p=m.match(/config:\s*JSON\.parse\('(.+?)'\)/)}if(!p)return"";try{const f=JSON.parse(p[1].replace(/\\'/g,"'").replace(/\\\\/g,"\\"));return f.uid?String(f.uid):""}catch(f){return""}}function i(m){const p=btoa(m+"&"+Date.now()).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,""),f="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";let w=p;while(w.length<43)w+=f.charAt(Math.floor(Math.random()*f.length));return w.slice(0,43)}const e=await a();if(!e)return{ok:!1,stage:"auth",message:"未取到微博 uid,请先登录微博"};let u=(t.content||"").replace(/>\s+</g,"><");const r=document.createElement("div");r.innerHTML=u;const n=r.querySelectorAll("img");for(let m=0;m<n.length;m++){const p=n[m],f=(p.getAttribute("src")||"").match(/sinaimg\.cn\/large\/([^/."]+)\.jpg/);if(!f)continue;p.setAttribute("data-pid",f[1]);if(!p.closest("figure")){const w=document.createElement("figure");w.className="image";p.parentNode.insertBefore(w,p);w.appendChild(p)}}u=r.innerHTML;const o=i(e),s=await fetch("https://card.weibo.com/article/v5/aj/editor/draft/create?uid="+e+"&_rid="+o,{method:"POST",credentials:"include",headers:{"Content-Type":"application/x-www-form-urlencoded",accept:"application/json, text/plain, */*","SN-REQID":o},body:new URLSearchParams({})}),l=await s.text();let d=null;try{d=JSON.parse(l)}catch(m){}if(!s.ok||!d||d.code!==1e5||!d.data||!d.data.id)return{ok:!1,stage:"create",status:s.status,message:d&&d.msg||"创建草稿失败:"+l.slice(0,200)};const g=String(d.data.id),N=t.params&&typeof t.params.cover==="string"?t.params.cover:"",_=i(e),b=await fetch("https://card.weibo.com/article/v5/aj/editor/draft/save?uid="+e+"&id="+g+"&_rid="+_,{method:"POST",credentials:"include",headers:{"Content-Type":"application/x-www-form-urlencoded",accept:"application/json, text/plain, */*","SN-REQID":_},body:new URLSearchParams({id:g,title:t.title,subtitle:"",type:"",status:"0",publish_at:"",error_msg:"",error_code:"0",collection:"[]",free_content:"",content:u,cover:N,summary:"",writer:"",extra:"null",is_word:"0",article_recommend:"[]",follow_to_read:"1",isreward:"1",pay_setting:'{"ispay":0,"isvclub":0}',source:"0",action:"1",content_type:"0",save:"1"})}),I=await b.text();let y=null;try{y=JSON.parse(I)}catch(m){}if(!b.ok||!y||String(y.code)!=="100000")return{ok:!1,stage:"save",status:b.status,message:y&&y.msg||"保存草稿失败:"+I.slice(0,200)};return{ok:!0,id:g,url:"https://card.weibo.com/article/v5/editor#/draft/"+g,draft:!0}}};S({site:"weibo",name:"article",access:"write",description:"把长文以微博头条文章形式保存到草稿箱(card.weibo.com)。正文默认 Markdown,外链/本机图片自动转存到微博图床,支持 --cover 题图。注意:平台接口只到草稿态,正式发布需在微博头条文章编辑器里手动操作。",domain:"weibo.com",strategy:v.COOKIE,browser:!0,args:[{name:"title",positional:!0,required:!0,help:"文章标题"},{name:"text",positional:!0,help:"文章正文(默认 Markdown;加 --html 则当 HTML 处理)"},{name:"file",help:"正文文件路径(UTF-8,默认 Markdown)"},{name:"html",type:"boolean",help:"把正文当 HTML 处理而不是 Markdown"},{name:"cover",help:"题图(本机图片路径或图片 URL,自动转存到微博图床)"},{name:"draft",type:"boolean",help:"仅保存草稿(微博头条文章目前只支持草稿,此参数保留兼容性)"},{name:"execute",type:"boolean",help:"实际执行写入。不加此参数时命令拒绝写入。"}],columns:["status","outcome","message","target_type","target","created_target","created_url"],func:async(t,c)=>{if(!t)throw new x("微博头条文章命令需要浏览器会话。");U(c);const a=String(c.title??"").trim();if(!a)throw new h("INVALID_INPUT","文章标题不能为空。");const i=await L(c),e=typeof c.cover==="string"&&c.cover.trim()?c.cover.trim():"",u=!0,r=await P(t,{title:a,body:i,format:c.html?"html":"markdown",draftOnly:u,profile:weiboProfile,publishParams:e?{cover:e}:null}),n=r.images.uploaded.length|0,o=r.images.failed.length|0;let s="已保存微博头条文章草稿(正式发布请在编辑器里手动操作)";if(n||o)s+="·图片:"+n+" 张已转存"+(o?","+o+" 张失败":"");s+=T(r.images);return E(s,"article","","draft",{created_target:"draft:"+r.id,created_url:r.url})}});
|
package/clis/weixin/article.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{CliError as
|
|
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})}});
|
package/clis/woshipm/article.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{CliError as d,CommandExecutionError as f}from"@jackwener/opencli/errors";import{cli as g,Strategy as y}from"@jackwener/opencli/registry";import{publishArticle as
|
|
1
|
+
import{CliError as d,CommandExecutionError as f}from"@jackwener/opencli/errors";import{cli as g,Strategy as y}from"@jackwener/opencli/registry";import{formatImageReport as _,publishArticle as I}from"../_shared/article/publish.js";import{checkLogin as A}from"../_shared/article/auth.js";import{readFile as T,stat as L}from"node:fs/promises";import{rememberArticleFile as R}from"../_shared/article/images.js";function N(a){if(!a.execute)throw new d("INVALID_INPUT","此写操作需要 --execute 参数确认,未传则拒绝写入。注意:本报错仅表示缺少 --execute,并未校验其余参数,不能当 dry-run 预览用")}async function P(a){const n=typeof a.text==="string"?a.text:void 0,e=typeof a.file==="string"?a.file:void 0;if(n&&e)throw new d("INVALID_INPUT","正文来源只能二选一:<text> 或 --file,不能同时指定");let r=n??"";if(e){R(e);let i;try{i=await L(e)}catch{throw new d("INVALID_INPUT",`文件不存在:${e}`)}if(!i.isFile())throw new d("INVALID_INPUT",`必须是普通文本文件:${e}`);let o;try{o=await T(e)}catch{throw new d("INVALID_INPUT",`文件无法读取:${e}`)}try{r=new TextDecoder("utf-8",{fatal:!0}).decode(o)}catch{throw new d("INVALID_INPUT",`文件无法解码为 UTF-8:${e}`)}}if(!r.trim())throw new d("INVALID_INPUT","正文不能为空或仅有空白字符");return r}function b(a,n,e,r,i={}){return[{status:"success",outcome:r,message:a,target_type:n,target:e,...i}]}export const woshipmProfile={home:"https://www.woshipm.com/writing",outputFormat:"html",preprocessConfig:{removeEmptyLines:!0},image:{skip:["woshipm.com","image.woshipm.com"],uploadFn:async(a,n)=>{const r=(document.documentElement.innerHTML||"").match(/"jltoken"\s*:\s*"([^"]+)"/),i=r?r[1]:"";let o="image.png";try{const h=new URL(a).pathname.split("/"),w=h[h.length-1];if(w)o=w}catch(p){}const s=await fetch(a,{credentials:"omit"});if(!s.ok)throw Error("下载图片失败:"+s.status+" "+a);const c=await s.blob(),t=new FormData;t.append("action","wpuf_insert_image");t.append("name",o);t.append("files",c,o);const u={};if(i)u.jlstar="Bearer "+i;const l=await(await fetch("https://www.woshipm.com/tensorflow/upyun/upload",{method:"POST",credentials:"include",headers:u,body:t})).json();if(l&&l.data&&l.data.length>0&&l.data[0].url)return{url:l.data[0].url};throw Error(l.error||"图片上传失败:接口返回无 URL")}},checkAuth:async(a)=>{const e=await(await fetch("https://www.woshipm.com/writing",{method:"GET",credentials:"include"})).text(),r=e.match(/"jltoken"\s*:\s*"([^"]+)"/),i=r?r[1]:"",o=e.match(/var\s+userSettings\s*=\s*\{[^}]*"uid"\s*:\s*"(\d+)"/);if(!o)return{isAuthenticated:!1};const s=o[1],c=await fetch("https://www.woshipm.com/api2/user/profile?uid="+s,{method:"GET",credentials:"include",headers:{"X-Requested-With":"XMLHttpRequest"}});let t=null;try{t=await c.json()}catch(u){}if(t&&t.CODE===200&&t.RESULT&&t.RESULT.userInfoVo&&t.RESULT.userInfoVo.uid){const u=t.RESULT.userInfoVo;return{isAuthenticated:!0,userId:String(u.uid),username:u.nickName||"",avatar:u.avartar||""}}return{isAuthenticated:!1,error:"接口返回未登录(CODE: "+(t&&t.CODE)+")"}},publish:async(a,n)=>{const e=a.content,r="https://www.woshipm.com/wp-admin/admin-ajax.php",i={"Content-Type":"application/x-www-form-urlencoded","X-Requested-With":"XMLHttpRequest"};if(a.draftOnly){const m=await fetch(r,{method:"POST",credentials:"include",headers:i,body:new URLSearchParams({action:"add_draft",post_title:a.title,post_content:e})}),l=await m.text();let p=null;try{p=JSON.parse(l)}catch(x){}if(!m.ok||!p||!p.post_id)return{ok:!1,stage:"create",status:m.status,message:p&&p.error||l.slice(0,300)};const h=String(p.post_id),w=p.url||"https://www.woshipm.com/writing?pid="+h;return{ok:!0,draft:!0,id:h,url:w}}const o=new URLSearchParams({action:"add_pending",post_title:a.title,post_content:e,copyright:"1",copyright_pm:"1",copyright_other:"1"}),s=await fetch(r,{method:"POST",credentials:"include",headers:i,body:o}),c=await s.text();let t=null;try{t=JSON.parse(c)}catch(m){}if(!s.ok||!t||String(t.success)!=="1")return{ok:!1,stage:"publish",status:s.status,message:t&&t.message||c.slice(0,300)};return{ok:!0,draft:!1,pending:!0,id:t&&(t.post_id||t.id)?String(t.post_id||t.id):"",url:"https://www.woshipm.com/me/posts/"}}};g({site:"woshipm",name:"article",access:"write",description:"发布文章到人人都是产品经理(woshipm.com)。默认提交审核(正式发布),加 --draft 仅存草稿。正文默认 Markdown,图片自动转存到站内图床。注意:平台为审核制,提交后稿件进入待审核(pending),运营 24h 内人工审核通过才公开。",domain:"www.woshipm.com",strategy:y.COOKIE,browser:!0,args:[{name:"title",positional:!0,required:!0,help:"文章标题(非空,长度<=200)"},{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(a,n)=>{if(!a)throw new f("woshipm article 需要浏览器会话");N(n);const e=String(n.title??"").trim();if(!e)throw new d("INVALID_INPUT","文章标题不能为空");if(e.length>200)throw new d("INVALID_INPUT","文章标题过长(最多 200 字),当前 "+e.length+" 字");const r=await P(n),i=Boolean(n.draft),o=await I(a,{title:e,body:r,format:n.html?"html":"markdown",draftOnly:i,profile:woshipmProfile}),s=o.images.uploaded.length|0,c=o.images.failed.length|0;let t=o.draft?"已保存到草稿箱":"已提交审核(稿件进入待审核 pending,运营 24h 内人工审核通过后才公开)";if(s||c)t+=`(图片:${s} 张已转存${c?`,${c} 张失败`:""})`;t+=_(o.images);return b(t,"article","",o.draft?"draft":"pending",{created_target:(o.draft?"draft:":"article:")+(o.id||""),created_url:o.url})}});
|
package/clis/xianyu/im.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{ArgumentError as s,CommandExecutionError as l}from"@jackwener/opencli/errors";export const DEFAULT_INBOX_LIMIT=20,MAX_INBOX_LIMIT=100,DEFAULT_MESSAGE_LIMIT=50,MAX_MESSAGE_LIMIT=200;export function normalizeLimit(e,t=DEFAULT_INBOX_LIMIT,r=MAX_INBOX_LIMIT,a="limit"){const o=String(e??"").trim();if(!o)return t;if(!/^\d+$/.test(o))throw new s(`xianyu ${a} must be an integer between 1 and ${r}`);const n=Number(o);if(!Number.isSafeInteger(n)||n<1||n>r)throw new s(`xianyu ${a} must be an integer between 1 and ${r}`);return n}export function normalizeRank(e){const t=String(e??"").trim();if(!t)return 0;if(!/^\d+$/.test(t))throw new s("xianyu rank must be a positive integer from xianyu inbox");const r=Number(t);if(!Number.isSafeInteger(r)||r<1)throw new s("xianyu rank must be a positive integer from xianyu inbox");return r}export function requireText(e,t){const r=String(e??"").replace(/\s+/g," ").trim();if(!r)throw new s(`${t} cannot be empty`);return r}export function requireEvaluateObject(e,t){if(!e||typeof e!=="object"||Array.isArray(e))throw new l(`Xianyu ${t} returned malformed browser payload`);return e}export function requireClickResult(e,t){const r=requireEvaluateObject(e,t);if(r.ok!==!0)throw new l(`Xianyu ${t} failed: ${r.reason||"unknown-reason"}`);return r}export function buildChatUrl(e,t){return`https://www.goofish.com/im?itemId=${encodeURIComponent(e)}&peerUserId=${encodeURIComponent(t)}`}export function buildInboxUrl(){return"https://www.goofish.com/im"}export function buildClickInboxConversationEvaluate(e){return`
|
|
1
|
+
import{ArgumentError as s,CommandExecutionError as l}from"@jackwener/opencli/errors";export const DEFAULT_INBOX_LIMIT=20,MAX_INBOX_LIMIT=100,DEFAULT_MESSAGE_LIMIT=50,MAX_MESSAGE_LIMIT=200;export function normalizeLimit(e,t=DEFAULT_INBOX_LIMIT,r=MAX_INBOX_LIMIT,a="limit"){const o=String(e??"").trim();if(!o)return t;if(!/^\d+$/.test(o))throw new s(`xianyu ${a} must be an integer between 1 and ${r}`);const n=Number(o);if(!Number.isSafeInteger(n)||n<1||n>r)throw new s(`xianyu ${a} must be an integer between 1 and ${r}`);return n}export function normalizeRank(e){const t=String(e??"").trim();if(!t||t==="0")return 0;if(!/^\d+$/.test(t))throw new s("xianyu rank must be a positive integer from xianyu inbox");const r=Number(t);if(!Number.isSafeInteger(r)||r<1)throw new s("xianyu rank must be a positive integer from xianyu inbox");return r}export function requireText(e,t){const r=String(e??"").replace(/\s+/g," ").trim();if(!r)throw new s(`${t} cannot be empty`);return r}export function requireEvaluateObject(e,t){if(!e||typeof e!=="object"||Array.isArray(e))throw new l(`Xianyu ${t} returned malformed browser payload`);return e}export function requireClickResult(e,t){const r=requireEvaluateObject(e,t);if(r.ok!==!0)throw new l(`Xianyu ${t} failed: ${r.reason||"unknown-reason"}`);return r}export function buildChatUrl(e,t){return`https://www.goofish.com/im?itemId=${encodeURIComponent(e)}&peerUserId=${encodeURIComponent(t)}`}export function buildInboxUrl(){return"https://www.goofish.com/im"}export function buildClickInboxConversationEvaluate(e){return`
|
|
2
2
|
(() => {
|
|
3
3
|
const rows = Array.from(document.querySelectorAll('#conv-list-scrollable [class*="conversation-item"], a[href*="/im"], a[href*="itemId="][href*="peerUserId="]'));
|
|
4
4
|
const row = rows[${e}];
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
function
|
|
1
|
+
function c(t,e){return t+Math.random()*(e-t)}function M(t,e=0.4,r=0.02){const n=t*e;return Math.max(r,t-n+Math.random()*n*2)}export async function humanWait(t,e,r=0.4){try{await t.wait({time:M(e,r)})}catch{}}export async function humanType(t,e){const r=String(e);if(!r)return;if(typeof t.insertText!=="function"){try{await t.insertText?.(r)}catch{}return}const n=splitGraphemes(r);let o=0;while(o<n.length){const u=Math.max(1,Math.round(c(1,4))),h=n.slice(o,o+u).join(""),y=n.slice(o).join("");o+=u;try{await t.insertText(h)}catch{try{await t.insertText(y)}catch{}return}const i=Math.random()<0.12?c(0.35,0.8):c(0.04,0.18);try{await t.wait({time:i})}catch{}}}export function splitGraphemes(t){const e=String(t);if(typeof Intl<"u"&&typeof Intl.Segmenter==="function")return Array.from(new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(e),(r)=>r.segment);return Array.from(e)}function w(t){if(!t.__xhsCursor)t.__xhsCursor={x:Math.round(c(80,520)),y:Math.round(c(120,420))};return t.__xhsCursor}function _(t,e,r){const n=e.x-t.x,o=e.y-t.y,u=Math.hypot(n,o)||1,h=-o/u,y=n/u,i=c(0.05,0.22)*u*(Math.random()<0.5?1:-1),l={x:t.x+n*c(0.2,0.4)+h*i,y:t.y+o*c(0.2,0.4)+y*i},f={x:t.x+n*c(0.6,0.8)+h*i*c(0.3,0.7),y:t.y+o*c(0.6,0.8)+y*i*c(0.3,0.7)},d=[];for(let x=1;x<=r;x++){const s=x/r,a=1-s,m=a*a*a*t.x+3*a*a*s*l.x+3*a*s*s*f.x+s*s*s*e.x,p=a*a*a*t.y+3*a*a*s*l.y+3*a*s*s*f.y+s*s*s*e.y;d.push({x:Math.round(m),y:Math.round(p)})}return d}export async function humanMoveTo(t,e,r){if(typeof t.cdp!=="function")return;const n={x:Math.round(e+c(-3,3)),y:Math.round(r+c(-3,3))},o=w(t),u=Math.hypot(n.x-o.x,n.y-o.y),h=Math.max(6,Math.min(18,Math.round(u/30))),y=_(o,n,h);for(const i of y){try{await t.cdp("Input.dispatchMouseEvent",{type:"mouseMoved",x:i.x,y:i.y})}catch{return}try{await t.wait({time:M(0.02,0.6,0.008)})}catch{}}t.__xhsCursor=n}export async function elementViewportCenter(t,e){try{const r=await t.evaluate(`
|
|
2
2
|
(sels => {
|
|
3
3
|
const __opencli_xhs_el_center = true;
|
|
4
4
|
for (const sel of sels) {
|
|
@@ -10,5 +10,5 @@ function e(t,o){return t+Math.random()*(o-t)}function M(t,o=0.4,r=0.02){const n=
|
|
|
10
10
|
}
|
|
11
11
|
}
|
|
12
12
|
return null;
|
|
13
|
-
})(${JSON.stringify(
|
|
13
|
+
})(${JSON.stringify(e)})
|
|
14
14
|
`),n=r&&typeof r==="object"&&"data"in r?r.data:r;if(n&&typeof n.x==="number"&&typeof n.y==="number")return n}catch{}return null}
|
|
@@ -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 L 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
|
|
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 L 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 H,humanWait as I,humanMoveTo as Tt,elementViewportCenter as kt}from"./human.js";import{loadNoteManagerNotes as Et}from"./_shared/note-manager.js";const $t="https://creator.xiaohongshu.com/publish/publish?from=menu_left&target=image",B=18,X=20,G=3000,Y="|||",k="基础",K=[["基础","默认兜底,万能"],["边框","金句/要点卡"],["备忘","提醒/随手记"],["清新","日常/清单贴士"],["涂写","随笔/碎碎念"],["便签","笔记/提醒"],["光影","情绪/文艺"],["涂鸦","趣味/童话"],["简约","干货/观点"],["手写","日记/情感"],["插图","生活方式/轻松话题"],["美漫","活力/趣味/故事感"],["弥散","弥散光氛围"],["柔和","柔和/温柔金句"],["印刷","印刷海报/排版"],["科技","科技/产品"],["贺卡","节日祝福"],["札记","艺术/水彩氛围"],["书摘","书摘/引用"],["手帐","手帐拼贴"],["几何","醒目/有力主张"]],ae=K.map(([t])=>t),F="文字配图",W="再写一张",Q="生成图片",Z="下一步",U=".tiptap.ProseMirror",At=["_onPublish","onPublish","_onSubmit","_handlePublish"],Ct=["_onSave","_onSaveDraft","_onDraft"],J=['[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(!L.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);
|
|
@@ -7,7 +7,7 @@ import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/to
|
|
|
7
7
|
() => !!document.querySelector(
|
|
8
8
|
'[class*="upload"][class*="progress"], [class*="uploading"], [class*="loading"][class*="image"]'
|
|
9
9
|
)
|
|
10
|
-
`))return;await t.wait({time:r/1000})}}export function describeTextMismatch(t,e){const
|
|
10
|
+
`))return;await t.wait({time:r/1000})}}export function describeTextMismatch(t,e,r){const n=String(t??""),o=String(e??""),i=(x)=>x.split(/\n\s*\n/).filter((S)=>S.trim()).length,a=r?r.expected:i(n),l=r?r.actual:i(o);let s=0;while(s<n.length&&s<o.length&&n[s]===o[s])s++;const d=(x)=>JSON.stringify(x.slice(Math.max(0,s-15),s+25)),w=`内容校验不一致:期望 ${n.length} 字符 / ${a} 段,实际 ${o.length} 字符 / ${l} 段。`,v=s>=n.length&&s>=o.length?"":` 首个差异在第 ${s+1} 个字符:期望 ${d(n)},实际 ${d(o)}。`,m=a>1&&l<=1?" 段落数塌成 1 段,通常是编辑器把换行吃掉了。":"",f=/\uFFFD/.test(o)&&!/\uFFFD/.test(n)?" 实际文本出现替换字符 �,说明 emoji 等多码元字符在写入时被拆开了。":"";return w+v+m+f}async function Pt(t,e,r){const n=()=>t.evaluate(`
|
|
11
11
|
((sel) => {
|
|
12
12
|
const el = Array.from(document.querySelectorAll(sel)).find(n => n && n.offsetParent !== null);
|
|
13
13
|
if (!el) return -1;
|
|
@@ -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 H(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();
|
|
@@ -138,10 +138,12 @@ import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/to
|
|
|
138
138
|
el.dispatchEvent(new Event('change', { bubbles: true }));
|
|
139
139
|
el.blur();
|
|
140
140
|
const actual = normalize(el.innerText || el.textContent || '');
|
|
141
|
-
|
|
141
|
+
const blocks = el.querySelectorAll('p, div[data-node-type], li').length || el.childElementCount;
|
|
142
|
+
return { ok: actual === normalize(expectedText), actual, blocks };
|
|
142
143
|
})(${JSON.stringify(o.sel)}, ${JSON.stringify(r)})
|
|
143
144
|
`)}catch(s){if(s instanceof u)throw s;if(String(r).includes(`
|
|
144
|
-
`))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
|
|
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 Rt(t){const e=await t.evaluate(`
|
|
145
147
|
() => {
|
|
146
148
|
const isVisible = (el) => {
|
|
147
149
|
if (!el || el.offsetParent === null) return false;
|
|
@@ -190,7 +192,7 @@ import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/to
|
|
|
190
192
|
}
|
|
191
193
|
return { ok: false, visibleTexts };
|
|
192
194
|
}
|
|
193
|
-
`);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 E(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(`
|
|
194
196
|
((cfg) => {
|
|
195
197
|
const __opencli_xhs_click_label = { wantLabel: ${JSON.stringify(e)} };
|
|
196
198
|
const wantLabel = ${JSON.stringify(e)};
|
|
@@ -228,7 +230,7 @@ import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/to
|
|
|
228
230
|
`));if(i?.ok)return i;await t.wait({time:n/1000})}return i}async function Dt(t){const e=await t.evaluate(`
|
|
229
231
|
(() => {
|
|
230
232
|
const __opencli_xhs_focus_card = true;
|
|
231
|
-
const sel = ${JSON.stringify(
|
|
233
|
+
const sel = ${JSON.stringify(U)};
|
|
232
234
|
const editors = Array.from(document.querySelectorAll(sel)).filter((el) => el.offsetParent !== null);
|
|
233
235
|
// Prefer the editor inside the active swiper slide if present.
|
|
234
236
|
const active = editors.find((el) => el.closest('.swiper-slide-active')) || editors[editors.length - 1];
|
|
@@ -245,7 +247,7 @@ import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/to
|
|
|
245
247
|
`);return _(e)}async function qt(t){const e=await t.evaluate(`
|
|
246
248
|
(() => {
|
|
247
249
|
const __opencli_xhs_card_text = true;
|
|
248
|
-
const sel = ${JSON.stringify(
|
|
250
|
+
const sel = ${JSON.stringify(U)};
|
|
249
251
|
const editors = Array.from(document.querySelectorAll(sel)).filter((el) => el.offsetParent !== null);
|
|
250
252
|
const active = editors.find((el) => el.closest('.swiper-slide-active')) || editors[editors.length - 1];
|
|
251
253
|
const text = active ? (active.innerText || active.textContent || '').trim() : '';
|
|
@@ -254,22 +256,22 @@ import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/to
|
|
|
254
256
|
`);return _(e)}async function it(t){const e=await t.evaluate(`
|
|
255
257
|
(() => {
|
|
256
258
|
const __opencli_xhs_card_count = true;
|
|
257
|
-
const sel = ${JSON.stringify(
|
|
259
|
+
const sel = ${JSON.stringify(U)};
|
|
258
260
|
const editors = Array.from(document.querySelectorAll(sel)).filter((el) => el.offsetParent !== null);
|
|
259
261
|
const active = editors.find((el) => el.closest('.swiper-slide-active')) || editors[editors.length - 1];
|
|
260
262
|
const activeText = active ? (active.innerText || active.textContent || '').trim() : '';
|
|
261
263
|
return { ok: true, count: editors.length, activeEmpty: !activeText };
|
|
262
264
|
})()
|
|
263
|
-
`);return _(e)}async function Ot(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 Lt(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 Bt(t,e,r=4){for(let n=0;n<r;n++){if(!(await
|
|
265
|
+
`);return _(e)}async function Ot(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 Lt(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 Bt(t,e,r=4){for(let n=0;n<r;n++){if(!(await E(t,W))?.ok)return!1;if(await Lt(t,e,2500))return!0}return!1}async function Ft(t){const e=await t.evaluate(`
|
|
264
266
|
(() => {
|
|
265
267
|
const __opencli_xhs_preview_ready = true;
|
|
266
268
|
const ready = Array.from(document.querySelectorAll('button'))
|
|
267
269
|
.some((b) => b.offsetParent !== null && (b.innerText || '').replace(/\\s+/g, '') === '下一步');
|
|
268
270
|
return { ok: ready };
|
|
269
271
|
})()
|
|
270
|
-
`);return _(e)}async function
|
|
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 E(t,Q))?.ok&&o===0)return!1;for(let a=0;a<n;a++){if((await Ft(t))?.ok)return!0;await t.wait({time:r/1000})}}return!1}async function Jt(t,e,r){e=String(e).replace(/\\n/g,`
|
|
271
273
|
`);if(!(await Dt(t))?.ok)throw new u(`文字配图: could not focus card editor #${r+1}`);if(typeof t.insertText==="function"){const i=e.split(`
|
|
272
|
-
`);for(let a=0;a<i.length;a++){if(a>0&&typeof t.pressKey==="function")await t.pressKey("Enter");if(i[a])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 H(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(`
|
|
273
275
|
(async () => {
|
|
274
276
|
const __opencli_xhs_card_styles = true;
|
|
275
277
|
const want = ${JSON.stringify(e)};
|
|
@@ -298,7 +300,7 @@ import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/to
|
|
|
298
300
|
}
|
|
299
301
|
return { ok: seen.length > 0, styles: seen, found: false };
|
|
300
302
|
})()
|
|
301
|
-
`));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 ${
|
|
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 E(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(`
|
|
302
304
|
(() => {
|
|
303
305
|
const __opencli_xhs_composer_media_count = true;
|
|
304
306
|
const visibleBox = (el) => {
|
|
@@ -330,7 +332,7 @@ import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/to
|
|
|
330
332
|
}
|
|
331
333
|
return { ok: true, count };
|
|
332
334
|
})()
|
|
333
|
-
`);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
|
|
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 E(t,F))?.ok){await t.screenshot({path:"/tmp/xhs_publish_textimage_debug.png"});throw new u(`文字配图: could not click "${F}" entry. Debug: /tmp/xhs_publish_textimage_debug.png`)}if(!await Ot(t)){await t.screenshot({path:"/tmp/xhs_publish_textimage_debug.png"});throw new u(`文字配图: 写文字 card editor did not appear after clicking "${F}". Debug: /tmp/xhs_publish_textimage_debug.png`)}for(let l=0;l<e.length;l++){if(l>0){if(!await Bt(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 "${W}". 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(`文字配图: "${Q}" did not advance to the 预览图片 step. `+"Debug: /tmp/xhs_publish_generate_debug.png")}const i=await jt(t,r);if(!(await E(t,Z))?.ok){await t.screenshot({path:"/tmp/xhs_publish_next_debug.png"});throw new u(`文字配图: could not click "${Z}". Debug: /tmp/xhs_publish_next_debug.png`)}await t.wait({time:2});return i}async function lt(t){return t.evaluate(`
|
|
334
336
|
() => {
|
|
335
337
|
const text = (document.body?.innerText || '').replace(/s+/g, ' ').trim();
|
|
336
338
|
const hasTitleInput = !!Array.from(document.querySelectorAll('input, textarea')).find((el) => {
|
|
@@ -360,7 +362,7 @@ import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/to
|
|
|
360
362
|
const state = hasTitleInput ? 'editor_ready' : hasImageInput || !hasVideoSurface ? 'image_surface' : 'video_surface';
|
|
361
363
|
return { state, hasTitleInput, hasImageInput, hasVideoSurface };
|
|
362
364
|
}
|
|
363
|
-
`)}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
|
|
365
|
+
`)}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(`
|
|
364
366
|
(() => {
|
|
365
367
|
const sels = ${JSON.stringify(J)};
|
|
366
368
|
for (const sel of sels) {
|
|
@@ -368,7 +370,7 @@ import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/to
|
|
|
368
370
|
if (el && el.offsetParent !== null) return true;
|
|
369
371
|
}
|
|
370
372
|
return false;
|
|
371
|
-
})()`))return!0;if(o<n-1)await t.wait({time:r/1000})}return!1}async function
|
|
373
|
+
})()`))return!0;if(o<n-1)await t.wait({time:r/1000})}return!1}async function Xt(t){const e=_(await t.evaluate(`
|
|
372
374
|
(() => {
|
|
373
375
|
const __opencli_xhs_restore_srcs = true;
|
|
374
376
|
return Array.from(document.querySelectorAll('.img-container img'))
|
|
@@ -406,7 +408,7 @@ import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/to
|
|
|
406
408
|
}
|
|
407
409
|
return removed;
|
|
408
410
|
})(${JSON.stringify(e)})
|
|
409
|
-
`));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),
|
|
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 Et(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:`图片路径,逗号分隔,最多${B}张 (jpg/png/gif/webp)`},{name:"card-text",required:!1,help:`文字配图卡片文字,多张卡片用 ${Y} 分隔,卡内换行用 \\n`},{name:"card-style",required:!1,help:`文字配图卡片样式,运行时按页面实际选项匹配;找不到会失败。省略时使用${k}。可选: ${K.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(!L.existsSync(c))throw new b(`--file 指向的文件不存在: ${c}`);o=L.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(Y).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>X)throw new b(`Title is ${r.length} chars — must be ≤ ${X}`);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>B)throw new b(`Too many images: ${i.length} (max ${B})`);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($t);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 Rt(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 A=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:G/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(A.length){await ct(t,A);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:G/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&&A.length){await ct(t,A);await t.wait({time:0.5})}await ot(t,J,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 R=await kt(t,["xhs-publish-btn"]);if(R){await Tt(t,R.x,R.y);await I(t,0.4)}const V=s?["暂存离开","存草稿"]:["发布","发布笔记"],h=await t.evaluate(`
|
|
410
412
|
(cfg => {
|
|
411
413
|
const { isDraftMode, publishNames, draftNames, labels } = cfg;
|
|
412
414
|
const isVisible = (el) => {
|
|
@@ -484,7 +486,7 @@ import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/to
|
|
|
484
486
|
}
|
|
485
487
|
return false;
|
|
486
488
|
}
|
|
487
|
-
`)){h.ok=!0;h.via="auto-save"}}}}if(!h?.ok){await t.screenshot({path:"/tmp/xhs_publish_submit_debug.png"});const
|
|
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(`未能触发「${V[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?["草稿已保存","暂存成功","保存成功","保存于","图文笔记("]:["发布成功","上传成功"],z=await t.evaluate(`
|
|
488
490
|
(markers => {
|
|
489
491
|
for (const el of document.querySelectorAll('*')) {
|
|
490
492
|
if (el.tagName === 'STYLE' || el.tagName === 'SCRIPT') continue;
|
|
@@ -494,4 +496,4 @@ import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/to
|
|
|
494
496
|
}
|
|
495
497
|
return '';
|
|
496
498
|
})(${JSON.stringify(ft)})
|
|
497
|
-
`),ht=!
|
|
499
|
+
`),ht=!T.includes("/publish/publish");let D=z.length>0||ht;const q=s?"暂存成功":"发布成功";let p=null,O="";if(!s){const c=await Yt(t,r,D?2:4);p=c.note;O=c.reason;if(p)D=!0}if(!D){if(s)throw new u(`${q}无法确认:未观察到成功提示或提交后跳转。`+(T?`当前 URL: ${T}。`:"当前 URL 为空。")+"先用 `xiaohongshu drafts` 查草稿箱确认是否已存上;确认没有再重新运行本命令,避免堆出重复草稿。");throw new u(`${q}无法确认:未观察到成功提示或提交后跳转,创作者后台也暂未查到同标题笔记(${O||"未回查到"})。`+(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}`:"",z||(p?"已在创作者后台确认":"")||T||"",p?.id?p.noteUrl?"链接需登录小红书后打开":"链接为创作者后台数据页,需登录":"",!s&&!p?.id?`未回查到笔记ID(${O||"未回查到"}),稍后用 creator-notes 按标题查`:""].filter(Boolean).join(" · "),url:p?.id?p.noteUrl||`https://creator.xiaohongshu.com/statistics/note-detail?noteId=${p.id}`:""}]}});
|
package/clis/xueqiu/article.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{CliError as
|
|
1
|
+
import{CliError as p,CommandExecutionError as A}from"@jackwener/opencli/errors";import{cli as O,Strategy as j}from"@jackwener/opencli/registry";import{readFile as C,stat as L}from"node:fs/promises";import{formatImageReport as F,publishArticle as D}from"../_shared/article/publish.js";import{rememberArticleFile as M}from"../_shared/article/images.js";export const xueqiuProfile={home:"https://mp.xueqiu.com/writeV2",outputFormat:"markdown",image:{spec:{url:"https://mp.xueqiu.com/xq/photo/upload.json",method:"POST",bodyType:"binary-multipart",fileField:"file",fileName:"image.jpg",responsePath:"url"},skip:["xueqiu.com","imedao.com"],uploadFn:async(o,i)=>{const e=await fetch(o,{credentials:"omit"});if(!e.ok)throw Error("图片下载失败: "+o);const l=await e.blob(),s=new FormData;s.append("file",l,"image.jpg");const a=await fetch("https://mp.xueqiu.com/xq/photo/upload.json",{method:"POST",credentials:"include",body:s}),t=await a.text();let n=null;try{n=JSON.parse(t)}catch(m){}if(!a.ok||!n||!n.url||!n.filename)throw Error("图片上传失败: "+t.slice(0,200));return{url:(n.url.startsWith("//")?"https:"+n.url:n.url)+"/"+n.filename}}},checkAuth:async(o)=>{try{const l=(await(await fetch("https://mp.xueqiu.com/writeV2",{method:"GET",credentials:"include"})).text()).match(/window\.UOM_CURRENTUSER\s*=\s*(\{[\s\S]*?\})\s*<\/script>/);if(!l)return{isAuthenticated:!1};let s=null;try{s=JSON.parse(l[1])}catch(n){}const a=s&&s.currentUser;if(!a||!a.id)return{isAuthenticated:!1};const t=a.photo_domain&&a.profile_image_url?"https:"+a.photo_domain+(a.profile_image_url.split(",")[0]||""):"";return{isAuthenticated:!0,userId:String(a.id),username:a.screen_name||"",avatar:t}}catch(i){return{isAuthenticated:!1,error:String(i&&i.message||i)}}},publish:async(o,i)=>{const e=o.params||{};let l=o.content;const s=l.split(`
|
|
2
2
|
`),a=[];let t=0;while(t<s.length){const r=s[t];if(r.startsWith("```")){let P="";t++;while(t<s.length&&!s[t].startsWith("```")){P+=(P?`
|
|
3
3
|
`:"")+s[t];t++}a.push("<pre><code>"+P.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")+"</code></pre>");t++;continue}const c=r.match(/^#{1,6}\s+(.*)/);if(c){a.push("<h4>"+c[1]+"</h4>");t++;continue}const d=r.match(/^!\[([^\]]*)\]\(([^)]+)\)/);if(d){a.push('<img src="'+d[2]+'" alt="'+d[1]+'" class="ke_img">');t++;continue}if(/^[-*_]{3,}\s*$/.test(r)){t++;continue}if(!r.trim()){a.push("");t++;continue}let k=r.replace(/\*\*([^*]+)\*\*/g,"<b>$1</b>").replace(/\*([^*]+)\*/g,"<i>$1</i>").replace(/`([^`]+)`/g,"<code>$1</code>");a.push("<p>"+k+"</p>");t++}l=a.filter((r,c,d)=>{return!(r===""&&c>0&&d[c-1]==="")}).join(`
|
|
4
|
-
`).trim();const n=typeof e.coverPic==="string"?e.coverPic.trim():"";if(n&&!/(imedao\.com|xueqiu\.com)/.test(n))return{ok:!1,stage:"cover",message:"封面图必须是雪球图床地址(含 imedao.com / xueqiu.com);外链需先上传。当前:"+n.slice(0,120)};const f=new URLSearchParams({text:l,title:o.title,cover_pic:n,flags:"false",original_event:"",status_id:"",legal_user_visible:"false",is_private:"false"}),
|
|
4
|
+
`).trim();const n=typeof e.coverPic==="string"?e.coverPic.trim():"";if(n&&!/(imedao\.com|xueqiu\.com)/.test(n))return{ok:!1,stage:"cover",message:"封面图必须是雪球图床地址(含 imedao.com / xueqiu.com);外链需先上传。当前:"+n.slice(0,120)};const f=new URLSearchParams({text:l,title:o.title,cover_pic:n,flags:"false",original_event:"",status_id:"",legal_user_visible:"false",is_private:"false"}),m=await fetch("https://mp.xueqiu.com/xq/statuses/draft/save.json",{method:"POST",credentials:"include",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:f}),I=await m.text();let h=null;try{h=JSON.parse(I)}catch(r){}if(!m.ok||!h||!h.id)return{ok:!1,stage:"save",status:m.status,message:h&&h.error_description||I.slice(0,300)};const v=String(h.id);if(o.draftOnly)return{ok:!0,id:v,url:"https://mp.xueqiu.com/write/draft/"+v,draft:!0};let w=typeof e.originalEventId==="string"?e.originalEventId.trim():"",S="",_=!0;if(w)try{const c=await(await fetch("/xq/statuses/original/original_event.json?id="+encodeURIComponent(w),{credentials:"include"})).json(),d=c&&c.originalEvent;if(!d||d.id==null)return{ok:!1,stage:"original_event",message:"原创活动事件不存在:"+w+"(用 `xueqiu events` 列举热门事件)"};if(d.disabled)return{ok:!1,stage:"original_event",message:"原创活动事件已停用,不可参与:"+w};S=String(d.tag||"")}catch(r){return{ok:!1,stage:"original_event",message:"校验原创活动事件失败:"+String(r&&r.message||r)}}else _=!1;let y="";try{const c=await(await fetch("/xq/provider/session/token.json?api_path="+encodeURIComponent("/statuses/update.json"),{credentials:"include"})).json();y=c&&c.session_token?String(c.session_token):""}catch(r){return{ok:!1,stage:"csrf",message:"获取发布 CSRF token 失败:"+String(r&&r.message||r)}}if(!y)return{ok:!1,stage:"csrf",message:"未取得发布 CSRF token(session_token 为空)"};const q=e.showCoverPic===!1?"false":"true",N=e.original===!0?"true":"false",R=e.allowReward===!0?"true":"false",U=new URLSearchParams({title:o.title,status:l,draft_id:v,session_token:y,cover_pic:n,show_cover_pic:q,original:N,industry_category_name:"",original_event_id:_?w:"",original_event_tag:_?S:"",original_event_active:_?"true":"false",legal_user_visible:"false",is_private:"false",legal_user_state:"open",allow_reward:R}),x=await fetch("https://mp.xueqiu.com/xq/statuses/update.json",{method:"POST",credentials:"include",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:U}),T=await x.text();let u=null;try{u=JSON.parse(T)}catch(r){}if(!x.ok||!u||!u.id)return{ok:!1,stage:"publish",status:x.status,message:u&&(u.error_description||u.error_code)||T.slice(0,300)};const b=String(u.id);let g="";if(u.user_id!=null)g=String(u.user_id);else if(u.user&&u.user.id!=null)g=String(u.user.id);if(!g)try{const r=(document.documentElement.outerHTML||"").match(/UOM_CURRENTUSER\s*=\s*(\{[\s\S]*?\})\s*<\/script>/);if(r){const c=JSON.parse(r[1]).currentUser;if(c&&c.id!=null)g=String(c.id)}}catch(r){}const E=g?"https://xueqiu.com/"+g+"/"+b:"https://xueqiu.com/"+b;return{ok:!0,id:b,url:E,draft:!1}}};function V(o){if(!o.execute)throw new p("INVALID_INPUT","此命令需要 --execute 参数才能实际写入,防止误操作。注意:本报错仅表示缺少 --execute,并未校验其余参数,不能当 dry-run 预览用")}async function J(o){const i=typeof o.text==="string"?o.text:void 0,e=typeof o.file==="string"?o.file:void 0;if(i&&e)throw new p("INVALID_INPUT","不能同时使用 <text> 和 --file,请选一种");let l=i??"";if(e){M(e);let s;try{s=await L(e)}catch{throw new p("INVALID_INPUT","文件不存在: "+e)}if(!s.isFile())throw new p("INVALID_INPUT","路径必须是可读文本文件: "+e);let a;try{a=await C(e)}catch{throw new p("INVALID_INPUT","文件读取失败: "+e)}try{l=new TextDecoder("utf-8",{fatal:!0}).decode(a)}catch{throw new p("INVALID_INPUT","文件不是合法 UTF-8 文本: "+e)}}if(!l.trim())throw new p("INVALID_INPUT","正文不能为空");return l}function B(o,i,e,l,s={}){return[{status:"success",outcome:l,message:o,target_type:i,target:e,...s}]}O({site:"xueqiu",name:"article",access:"write",description:"发布雪球文章(长文)。默认正式发布,加 --draft 仅存草稿。正文默认 Markdown,图片自动转存到雪球图床。",domain:"mp.xueqiu.com",strategy:j.COOKIE,browser:!0,args:[{name:"title",positional:!0,required:!0,help:"文章标题"},{name:"text",positional:!0,help:"正文(默认 Markdown;传 --html 则视为原始 HTML)"},{name:"file",help:"正文文件路径(UTF-8,默认 Markdown)"},{name:"html",type:"boolean",help:"把正文视为原始 HTML 而非 Markdown"},{name:"cover-image",help:"封面图地址(必须是雪球图床 imedao.com/xueqiu.com 的 url;外链请先上传)。可空=无封面"},{name:"no-cover",type:"boolean",help:"有封面图时不在文章头部展示封面(show_cover_pic=false)"},{name:"original",type:"boolean",help:"声明原创(需账号有原创权限,否则发布会被拒)。默认非原创"},{name:"original-event-id",help:"参与的原创活动/事件 id(精确校验,找不到/已停用报错);合法值用 `xueqiu events` 列举。可空=不参与"},{name:"allow-reward",type:"boolean",help:"允许打赏。默认不允许"},{name:"draft",type:"boolean",help:"仅保存为草稿,不正式发布"},{name:"execute",type:"boolean",help:"实际执行写入;不加此参数命令拒绝写操作"}],columns:["status","outcome","message","target_type","target","created_target","created_url"],func:async(o,i)=>{if(!o)throw new A("雪球文章发布需要浏览器会话(browser session)");V(i);const e=String(i.title??"").trim();if(!e)throw new p("INVALID_INPUT","文章标题不能为空");const l=await J(i),s=Boolean(i.draft),a={coverPic:typeof i["cover-image"]==="string"?i["cover-image"].trim():"",showCoverPic:!i["no-cover"],original:Boolean(i.original),originalEventId:typeof i["original-event-id"]==="string"?i["original-event-id"].trim():"",allowReward:Boolean(i["allow-reward"])},t=await D(o,{title:e,body:l,format:i.html?"html":"markdown",draftOnly:s,profile:xueqiuProfile,publishParams:a}),n=t.images.uploaded.length|0,f=t.images.failed.length|0;let m=t.draft?"已保存雪球文章草稿(需在写作页手动发布)":"已正式发布雪球文章";if(n||f)m+=`;图片: ${n} 张已转存${f?`,${f} 张失败`:""}`;m+=F(t.images);return B(m,"article","",t.draft?"draft":"created",{created_target:"article:"+t.id,created_url:t.url})}});
|
package/clis/yuque/article.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{CliError as c,CommandExecutionError as R}from"@jackwener/opencli/errors";import{cli as V,Strategy as j}from"@jackwener/opencli/registry";import{publishArticle as
|
|
1
|
+
import{CliError as c,CommandExecutionError as R}from"@jackwener/opencli/errors";import{cli as V,Strategy as j}from"@jackwener/opencli/registry";import{formatImageReport as C,publishArticle as E}from"../_shared/article/publish.js";import{rememberArticleFile as F}from"../_shared/article/images.js";export const yuqueProfile={home:"https://www.yuque.com/dashboard",outputFormat:"markdown",preprocessConfig:null,image:null,publish:async(l,o)=>{const f=o.cookie("yuque_ctoken");if(!f)return{ok:!1,stage:"auth",message:"未检测到语雀登录态,请先在 Chrome 中登录语雀(缺少 yuque_ctoken cookie)"};const s={"Content-Type":"application/json","x-csrf-token":f},m=await fetch("https://www.yuque.com/api/mine/common_used",{method:"GET",credentials:"include",headers:s});let t=null;try{t=await m.json()}catch(e){}if(!m.ok||!t?.data?.books?.length)return{ok:!1,stage:"auth",status:m.status,message:"无法获取语雀知识库列表,请确认已登录语雀"};const r=t.data.books[0].target_id,p=await fetch("https://www.yuque.com/api/docs",{method:"POST",credentials:"include",headers:s,body:JSON.stringify({title:l.title,type:"Doc",format:"lake",book_id:r,status:0})});let i=null;try{i=await p.json()}catch(e){}if(!p.ok||!i?.data?.id)return{ok:!1,stage:"create",status:p.status,message:i?.message||"创建语雀草稿文档失败"};const a=i.data.id,T="https://www.yuque.com/go/doc/"+a+"/edit";let h=l.content;const I=["yuque.com","cdn.nlark.com"],b=/!\[([^\]]*)\]\(\s*<?([^)\s>]+)>?\s*\)/g,w=[];let _;while((_=b.exec(h))!==null)w.push({full:_[0],alt:_[1],src:_[2]});const y=[],g=[],A="https://www.yuque.com/api/upload/attach?attachable_type=Doc&attachable_id="+a+"&type=image";for(let e=0;e<w.length;e++){const d=w[e],u=d.src;if(!u)continue;if(u.indexOf("data:")===0)continue;if(I.some(function(n){return u.indexOf(n)!==-1}))continue;try{const n=await fetch(u,{credentials:"omit"});if(!n.ok)throw Error("图片下载失败 HTTP "+n.status);const L=await n.blob(),O=new FormData;O.append("file",L,"image.jpg");const P=await fetch(A,{method:"POST",credentials:"include",headers:{"x-csrf-token":f},body:O});let k=null;try{k=await P.json()}catch(B){}if(!P.ok||!k?.data?.url)throw Error(k&&k.message||"图片上传失败 HTTP "+P.status);const v=k.data.url;h=h.split(d.full).join("");y.push({src:u.slice(0,120),url:v})}catch(n){g.push({src:u.slice(0,120),error:String(n&&n.message||n)})}}const N=await fetch("https://www.yuque.com/api/docs/convert",{method:"POST",credentials:"include",headers:s,body:JSON.stringify({from:"markdown",to:"lake",content:h})});let x=null;try{x=await N.json()}catch(e){}if(!N.ok||!x?.data?.content)return{ok:!1,stage:"convert",status:N.status,message:"内容格式转换失败(markdown→lake)",id:String(a),uploaded:y,failed:g};const S=x.data.content,U='<div class="lake-content" typography="traditional">'+S+"</div>",D=await fetch("https://www.yuque.com/api/docs/"+a+"/content",{method:"PUT",credentials:"include",headers:s,body:JSON.stringify({format:"lake",body_asl:S,body:U,body_html:U,draft_version:0,sync_dynamic_data:!1,save_type:"auto",edit_type:"Lake"})});if(!D.ok){let e="";try{e=await D.text()}catch(d){}return{ok:!1,stage:"save",status:D.status,message:"保存正文失败:"+e.slice(0,300),id:String(a),uploaded:y,failed:g}}if(!l.draftOnly){const e=await fetch("https://www.yuque.com/api/docs/"+a+"/publish",{method:"PUT",credentials:"include",headers:s,body:JSON.stringify({status:1})});if(!e.ok){let d="";try{d=await e.text()}catch(u){}return{ok:!1,stage:"publish",status:e.status,message:"发布失败:"+d.slice(0,300),id:String(a),url:T,uploaded:y,failed:g}}}return{ok:!0,id:String(a),url:T,draft:Boolean(l.draftOnly),uploaded:y,failed:g}}};V({site:"yuque",name:"article",access:"write",description:"发布语雀文章(知识库文档)。正文默认为 Markdown,外链图片自动转存到语雀图床。",domain:"www.yuque.com",strategy:j.COOKIE,browser:!0,args:[{name:"title",positional:!0,required:!0,help:"文章标题"},{name:"text",positional:!0,help:"文章正文(Markdown 格式;或用 --file 读文件)"},{name:"file",help:"正文文件路径(UTF-8,Markdown 格式)"},{name:"html",type:"boolean",help:"把正文当 HTML 输入(语雀仍转 lake 发布)"},{name:"draft",type:"boolean",help:"仅保存草稿,不发布"},{name:"execute",type:"boolean",help:"实际执行写操作。不加此参数命令拒绝写入。"}],columns:["status","outcome","message","target_type","target","created_target","created_url"],func:async(l,o)=>{if(!l)throw new R("语雀文章发布需要浏览器会话");if(!o.execute)throw new c("INVALID_INPUT","此命令需要加 --execute 才会实际写入(防误操作)");const f=String(o.title??"").trim();if(!f)throw new c("INVALID_INPUT","文章标题不能为空");let s="";const m=typeof o.text==="string"?o.text:void 0,t=typeof o.file==="string"?o.file:void 0;if(m&&t)throw new c("INVALID_INPUT","正文和 --file 不能同时使用");if(t){F(t);const{readFile:h,stat:I}=await import("node:fs/promises");let b;try{b=await I(t)}catch{throw new c("INVALID_INPUT",`文件不存在:${t}`)}if(!b.isFile())throw new c("INVALID_INPUT",`路径不是文件:${t}`);let w;try{w=await h(t)}catch{throw new c("INVALID_INPUT",`文件无法读取:${t}`)}try{s=new TextDecoder("utf-8",{fatal:!0}).decode(w)}catch{throw new c("INVALID_INPUT",`文件无法以 UTF-8 解码:${t}`)}}else s=m??"";if(!s.trim())throw new c("INVALID_INPUT","正文不能为空");const q=Boolean(o.draft),r=await E(l,{title:f,body:s,format:o.html?"html":"markdown",draftOnly:q,profile:yuqueProfile}),p=r.images.uploaded.length|0,i=r.images.failed.length|0;let a=r.draft?"已保存语雀草稿":"语雀文章发布成功";if(p||i)a+=`(图片:${p} 张已转存${i?`,${i} 张失败`:""})`;a+=C(r.images);return[{status:"success",outcome:r.draft?"draft":"created",message:a,target_type:"article",target:"",created_target:"article:"+r.id,created_url:r.url}]}});
|
package/clis/zhihu/answer.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{CommandExecutionError as m}from"@jackwener/opencli/errors";import{cli as d,Strategy as h}from"@jackwener/opencli/registry";import{publishArticle as
|
|
1
|
+
import{CommandExecutionError as m}from"@jackwener/opencli/errors";import{cli as d,Strategy as h}from"@jackwener/opencli/registry";import{formatImageReport as c,publishArticle as p}from"../_shared/article/publish.js";import{zhihuImageProfile as w}from"./image-profile.js";import{assertAllowedKinds as g,parseTarget as f}from"./target.js";import{buildResultRow as y,requireExecute as b,resolveCurrentUserIdentity as q,resolvePayload as T}from"./write-shared.js";function v(i){return{home:i,originRe:"https?://(www\\.)?zhihu\\.com",outputFormat:"html",preprocessConfig:{removeSpecialTags:!0,removeSpecialTagsWithParent:!0,processCodeBlocks:!0,convertSectionToDiv:!0,removeTrailingBr:!0,unwrapSingleChildContainers:!0,unwrapNestedFigures:!0,compactHtml:!0,removeEmptyLines:!0,removeEmptyDivs:!0,removeNestedEmptyContainers:!0},image:w,publish:async(r,l)=>{const a=r.content.replace(/<img([^>]+?)\/?>/gi,"<figure><img$1></figure>"),o=r.params&&r.params.questionId;if(!o)return{ok:!1,stage:"publish",message:"缺少 questionId"};const t=await fetch("https://www.zhihu.com/api/v4/questions/"+o+"/answers",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:a,reshipment_settings:"disallowed"})}),n=await t.text();let e=null;try{e=JSON.parse(n)}catch(u){}if(!t.ok)return{ok:!1,stage:"publish",status:t.status,message:e&&e.error&&e.error.message||n.slice(0,300),detail:e};if(!e||!e.id)return{ok:!1,stage:"publish",status:t.status,message:"回答接口没有返回回答 id:"+n.slice(0,300)};const s=String(e.id);return{ok:!0,draft:!1,id:s,url:e.url||"https://www.zhihu.com/question/"+o+"/answer/"+s}}}}d({site:"zhihu",name:"answer",access:"write",description:"Answer a Zhihu question. Body is Markdown by default (paragraphs become <p>); pass --html for raw HTML. Images (including local file paths) are auto-rehosted to Zhihu.",domain:"www.zhihu.com",strategy:h.COOKIE,browser:!0,args:[{name:"target",positional:!0,required:!0,help:"Zhihu question URL (e.g. https://www.zhihu.com/question/461491497) or typed target question:461491497; bare numeric id is rejected"},{name:"text",positional:!0,help:"Answer body (Markdown by default; pass --html for raw HTML)"},{name:"file",help:"Answer body file path (UTF-8, Markdown by default)"},{name:"html",type:"boolean",help:"Treat body as raw HTML instead of Markdown"},{name:"execute",type:"boolean",help:"Actually perform the write action"}],columns:["status","outcome","message","target_type","target","created_target","created_url","author_identity"],func:async(i,r)=>{if(!i)throw new m("Browser session required for zhihu answer");b(r);const l=String(r.target),a=g("answer",f(l)),o=await T(r),t=await p(i,{title:"",body:o,format:r.html?"html":"markdown",profile:v(a.url),publishParams:{questionId:a.id}}),n=await q(i),e=t.images.uploaded.length|0,s=t.images.failed.length|0;let u=`Answered question ${a.id}`;if(e||s)u+=` · images: ${e} rehosted${s?`, ${s} failed`:""}`;u+=c(t.images);return y(u,a.kind,l,"created",{created_target:"answer:"+a.id+":"+t.id,created_url:t.url,author_identity:n})}});
|