@easy-cms/plugin-social 1.37.0 → 1.39.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/admin.js +18 -16
- package/dist/index.d.ts +23 -3
- package/dist/index.js +557 -35
- package/package.json +5 -4
package/dist/admin.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
1
|
+
var A="/social/channels",v="/social/post",$="/social/ai",k="/social/share";var O=[[0,4351],[8192,8205],[8208,8223],[8242,8247]];function S(o){let t=0;for(let e of o.split(/(https?:\/\/\S+)/)){if(/^https?:\/\//.test(e)){t+=23;continue}let n=typeof Intl.Segmenter=="function"?Array.from(new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(e),r=>r.segment):[...e];for(let r of n){if(/\p{Extended_Pictographic}/u.test(r)){t+=2;continue}for(let i of r){let l=i.codePointAt(0)??0;t+=O.some(([p,u])=>l>=p&&l<=u)?1:2}}}return t}var P=["value","path","doc","collection","id","uiLocale","readOnly","api"],E={en:{pick:"Choose a channel",gone:"{id} (not connected)",none:"No channel is connected yet: add one in Settings \u2192 Integrations.",chars:"{n} characters",charsMax:"{n} / {max} characters",over:"Too long for {channel}",saveFirst:"Save the post first, then post it.",savedOnly:"Posts what is saved: save your changes first.",postNow:"Post now",confirmNow:"Post to {n} channels now? Posts can\u2019t be taken back from here.",schedule:"Schedule",when:"Post at",scheduledFor:"Scheduled for {time}",cancel:"Cancel the schedule",retry:"Retry",waiting:"Not posted",scheduled:"Scheduled",sending:"Sending\u2026",retrying:"Trying again at {time}",posted:"Posted",view:"View post",failed:"Failed",noRight:"You may write this post; someone who may post sends it.",share:"Share on social media",shareSave:"Save first, then share.",sharing:"Creating a post\u2026",writeAi:"Write with AI",writingAi:"Writing\u2026",spentAi:"Today's AI requests are used up",replaceAi:"Replace this text with one written by AI?",writtenAi:"Written by AI: check it before posting.",undo:"Undo"},th:{pick:"\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E0A\u0E48\u0E2D\u0E07\u0E17\u0E32\u0E07",gone:"{id} (\u0E44\u0E21\u0E48\u0E44\u0E14\u0E49\u0E40\u0E0A\u0E37\u0E48\u0E2D\u0E21\u0E15\u0E48\u0E2D\u0E41\u0E25\u0E49\u0E27)",none:"\u0E22\u0E31\u0E07\u0E44\u0E21\u0E48\u0E21\u0E35\u0E0A\u0E48\u0E2D\u0E07\u0E17\u0E32\u0E07\u0E17\u0E35\u0E48\u0E40\u0E0A\u0E37\u0E48\u0E2D\u0E21\u0E15\u0E48\u0E2D: \u0E40\u0E1E\u0E34\u0E48\u0E21\u0E44\u0E14\u0E49\u0E43\u0E19 Settings \u2192 \u0E01\u0E32\u0E23\u0E40\u0E0A\u0E37\u0E48\u0E2D\u0E21\u0E15\u0E48\u0E2D",chars:"{n} \u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23",charsMax:"{n} / {max} \u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23",over:"\u0E22\u0E32\u0E27\u0E40\u0E01\u0E34\u0E19\u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A {channel}",saveFirst:"\u0E1A\u0E31\u0E19\u0E17\u0E36\u0E01\u0E42\u0E1E\u0E2A\u0E15\u0E4C\u0E01\u0E48\u0E2D\u0E19 \u0E41\u0E25\u0E49\u0E27\u0E04\u0E48\u0E2D\u0E22\u0E42\u0E1E\u0E2A\u0E15\u0E4C",savedOnly:"\u0E08\u0E30\u0E42\u0E1E\u0E2A\u0E15\u0E4C\u0E15\u0E32\u0E21\u0E17\u0E35\u0E48\u0E1A\u0E31\u0E19\u0E17\u0E36\u0E01\u0E44\u0E27\u0E49: \u0E1A\u0E31\u0E19\u0E17\u0E36\u0E01\u0E01\u0E32\u0E23\u0E41\u0E01\u0E49\u0E44\u0E02\u0E01\u0E48\u0E2D\u0E19",postNow:"\u0E42\u0E1E\u0E2A\u0E15\u0E4C\u0E40\u0E25\u0E22",confirmNow:"\u0E42\u0E1E\u0E2A\u0E15\u0E4C\u0E44\u0E1B {n} \u0E0A\u0E48\u0E2D\u0E07\u0E17\u0E32\u0E07\u0E40\u0E25\u0E22\u0E44\u0E2B\u0E21? \u0E22\u0E01\u0E40\u0E25\u0E34\u0E01\u0E42\u0E1E\u0E2A\u0E15\u0E4C\u0E08\u0E32\u0E01\u0E17\u0E35\u0E48\u0E19\u0E35\u0E48\u0E44\u0E21\u0E48\u0E44\u0E14\u0E49",schedule:"\u0E15\u0E31\u0E49\u0E07\u0E40\u0E27\u0E25\u0E32",when:"\u0E42\u0E1E\u0E2A\u0E15\u0E4C\u0E40\u0E27\u0E25\u0E32",scheduledFor:"\u0E15\u0E31\u0E49\u0E07\u0E40\u0E27\u0E25\u0E32\u0E44\u0E27\u0E49 {time}",cancel:"\u0E22\u0E01\u0E40\u0E25\u0E34\u0E01\u0E01\u0E32\u0E23\u0E15\u0E31\u0E49\u0E07\u0E40\u0E27\u0E25\u0E32",retry:"\u0E25\u0E2D\u0E07\u0E2D\u0E35\u0E01\u0E04\u0E23\u0E31\u0E49\u0E07",waiting:"\u0E22\u0E31\u0E07\u0E44\u0E21\u0E48\u0E42\u0E1E\u0E2A\u0E15\u0E4C",scheduled:"\u0E15\u0E31\u0E49\u0E07\u0E40\u0E27\u0E25\u0E32\u0E44\u0E27\u0E49",sending:"\u0E01\u0E33\u0E25\u0E31\u0E07\u0E2A\u0E48\u0E07\u2026",retrying:"\u0E08\u0E30\u0E25\u0E2D\u0E07\u0E43\u0E2B\u0E21\u0E48\u0E40\u0E27\u0E25\u0E32 {time}",posted:"\u0E42\u0E1E\u0E2A\u0E15\u0E4C\u0E41\u0E25\u0E49\u0E27",view:"\u0E14\u0E39\u0E42\u0E1E\u0E2A\u0E15\u0E4C",failed:"\u0E44\u0E21\u0E48\u0E2A\u0E33\u0E40\u0E23\u0E47\u0E08",noRight:"\u0E04\u0E38\u0E13\u0E40\u0E02\u0E35\u0E22\u0E19\u0E42\u0E1E\u0E2A\u0E15\u0E4C\u0E19\u0E35\u0E49\u0E44\u0E14\u0E49 \u0E2A\u0E48\u0E27\u0E19\u0E01\u0E32\u0E23\u0E42\u0E1E\u0E2A\u0E15\u0E4C\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E2B\u0E49\u0E1C\u0E39\u0E49\u0E17\u0E35\u0E48\u0E21\u0E35\u0E2A\u0E34\u0E17\u0E18\u0E34\u0E4C\u0E40\u0E1B\u0E47\u0E19\u0E04\u0E19\u0E01\u0E14",share:"\u0E41\u0E0A\u0E23\u0E4C\u0E44\u0E1B\u0E42\u0E0B\u0E40\u0E0A\u0E35\u0E22\u0E25",shareSave:"\u0E1A\u0E31\u0E19\u0E17\u0E36\u0E01\u0E01\u0E48\u0E2D\u0E19 \u0E41\u0E25\u0E49\u0E27\u0E04\u0E48\u0E2D\u0E22\u0E41\u0E0A\u0E23\u0E4C",sharing:"\u0E01\u0E33\u0E25\u0E31\u0E07\u0E2A\u0E23\u0E49\u0E32\u0E07\u0E42\u0E1E\u0E2A\u0E15\u0E4C\u2026",writeAi:"\u0E40\u0E02\u0E35\u0E22\u0E19\u0E14\u0E49\u0E27\u0E22 AI",writingAi:"\u0E01\u0E33\u0E25\u0E31\u0E07\u0E40\u0E02\u0E35\u0E22\u0E19\u2026",spentAi:"\u0E43\u0E0A\u0E49\u0E04\u0E33\u0E02\u0E2D AI \u0E02\u0E2D\u0E07\u0E27\u0E31\u0E19\u0E19\u0E35\u0E49\u0E04\u0E23\u0E1A\u0E41\u0E25\u0E49\u0E27",replaceAi:"\u0E41\u0E17\u0E19\u0E17\u0E35\u0E48\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E19\u0E35\u0E49\u0E14\u0E49\u0E27\u0E22\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E17\u0E35\u0E48 AI \u0E40\u0E02\u0E35\u0E22\u0E19\u0E44\u0E2B\u0E21?",writtenAi:"\u0E40\u0E02\u0E35\u0E22\u0E19\u0E42\u0E14\u0E22 AI: \u0E15\u0E23\u0E27\u0E08\u0E14\u0E39\u0E01\u0E48\u0E2D\u0E19\u0E42\u0E1E\u0E2A\u0E15\u0E4C",undo:"\u0E40\u0E25\u0E34\u0E01\u0E17\u0E33"}},s=o=>o.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t]);function I(o){if(typeof Intl.Segmenter!="function")return[...o].length;let t=0;for(let e of new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(o))t++;return t}var T=new WeakMap;function H(o){let t=T.get(o);if(t)return t;let e=o("GET",A).then(n=>n).catch(()=>({channels:[],canPost:!1}));return T.set(o,e),e}var C=new WeakMap;function L(o,t=!1){let e=C.get(o);if(e&&!t)return e;let n=o("GET","/admin/ai/status").then(r=>{let i=r;return{ready:i.connected&&i.features.includes("social"),spent:i.used>=i.limit}}).catch(()=>({ready:!1,spent:!1}));return C.set(o,n),n}var M=`
|
|
2
2
|
:host { display: block; font: inherit; color: var(--text); }
|
|
3
3
|
.row { display: flex; align-items: center; gap: 0.5rem; flex-wrap: wrap; }
|
|
4
4
|
.hint { margin: 0; font-size: 0.8rem; color: var(--text-muted); }
|
|
@@ -18,24 +18,24 @@ var x="/social/channels",f="/social/post",w="/social/ai",A="/social/share";var C
|
|
|
18
18
|
border-radius: var(--radius-sm, 8px); background: var(--surface); color: var(--text); font: inherit;
|
|
19
19
|
}
|
|
20
20
|
a { color: var(--accent-ink); }
|
|
21
|
-
`,
|
|
21
|
+
`,g=class o extends HTMLElement{ctx={value:void 0,path:void 0,doc:{},collection:void 0,id:null,uiLocale:"en",readOnly:!1,api:void 0};channels=[];canPost=!1;asked=!1;queued=!1;html="";constructor(){super();let t=this.attachShadow({mode:"open"});t.addEventListener("click",e=>{let n=e.target.closest("[data-action]"),r=n?.getAttribute("data-action");r&&n?.tagName!=="SELECT"&&this.onAction(r,n)}),t.addEventListener("change",e=>this.onChange(e.target))}static{for(let t of P)Object.defineProperty(o.prototype,t,{get(){return this.ctx[t]},set(e){this.ctx[t]=e,this.update()}})}connectedCallback(){this.update()}t(t,e={}){return(this.ctx.uiLocale==="th"?E.th:E.en)[t].replace(/\{(\w+)\}/g,(r,i)=>String(e[i]??""))}time(t){return new Date(t).toLocaleString(this.ctx.uiLocale==="th"?"th-TH":"en-GB",{dateStyle:"medium",timeStyle:"short"})}labelOf(t){return this.channels.find(e=>e.id===t)?.label??t}update(){!this.asked&&this.ctx.api&&(this.asked=!0,H(this.ctx.api).then(({channels:t,canPost:e})=>{this.channels=t,this.canPost=e,this.update()})),!this.queued&&(this.queued=!0,queueMicrotask(()=>{this.queued=!1;let t=this.shadowRoot;if(!t)return;let e=`<style>${M}${this.css()}</style>${this.render()}`;if(e===this.html)return;let n=t.activeElement?.getAttribute("data-action");this.html=e,t.innerHTML=e,n&&t.querySelector(`[data-action="${n}"]`)?.focus()}))}onAction(t,e){}onChange(t){}css(){return""}},y=class extends g{render(){let t=typeof this.ctx.value=="string"?this.ctx.value:"",e=this.ctx.doc.delivery??null,n=!!t&&e?.channels?.[t]?.state==="posted";if(this.channels.length===0&&!t)return`<p class="hint">${s(this.t("none"))}</p>`;let r=this.channels.some(i=>i.id===t);return`
|
|
22
22
|
<select data-action="pick" aria-label="${s(this.t("pick"))}" ${this.ctx.readOnly||n?"disabled":""}>
|
|
23
23
|
${t?"":`<option value="">${s(this.t("pick"))}</option>`}
|
|
24
24
|
${!r&&t?`<option value="${s(t)}" selected>${s(this.t("gone",{id:t}))}</option>`:""}
|
|
25
25
|
${this.channels.map(i=>`<option value="${s(i.id)}" ${i.id===t?"selected":""}>${s(i.label)}</option>`).join("")}
|
|
26
26
|
</select>
|
|
27
|
-
`}css(){return"select { width: 100%; }"}onChange(t){t.getAttribute("data-action")==="pick"&&this.dispatchEvent(new CustomEvent("change",{detail:t.value}))}},
|
|
27
|
+
`}css(){return"select { width: 100%; }"}onChange(t){t.getAttribute("data-action")==="pick"&&this.dispatchEvent(new CustomEvent("change",{detail:t.value}))}},b=class extends g{ai={ready:!1,spent:!1};aiAsked=!1;busy=!1;beforeAi=null;notice=null;css(){return`
|
|
28
28
|
.bar { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 0.25rem 0.75rem; }
|
|
29
29
|
.ai { color: var(--accent-ink); font-weight: 600; border-color: transparent; background: transparent; }
|
|
30
30
|
.written { display: flex; flex-wrap: wrap; align-items: center; gap: 0.5rem; margin: 0.25rem 0 0; font-size: 0.8rem; color: var(--accent-ink); }
|
|
31
|
-
`}render(){!this.aiAsked&&this.ctx.api&&(this.aiAsked=!0,
|
|
31
|
+
`}render(){!this.aiAsked&&this.ctx.api&&(this.aiAsked=!0,L(this.ctx.api).then(e=>{this.ai=e,this.update()}));let t=this.ai.ready&&!this.ctx.readOnly?`<button type="button" class="ai" data-action="ai" ${this.busy||this.ai.spent?"disabled":""}>
|
|
32
32
|
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 3l1.9 5.1L19 10l-5.1 1.9L12 17l-1.9-5.1L5 10l5.1-1.9z"/></svg>
|
|
33
33
|
${s(this.t(this.busy?"writingAi":this.ai.spent?"spentAi":"writeAi"))}
|
|
34
34
|
</button>`:"";return`
|
|
35
35
|
<div class="bar">${this.count()}${t}</div>
|
|
36
36
|
${this.beforeAi?`<p class="written" role="status">${s(this.t("writtenAi"))} <button type="button" data-action="undo-ai">${s(this.t("undo"))}</button></p>`:""}
|
|
37
37
|
${this.notice?`<p class="error" role="alert">${s(this.notice)}</p>`:""}
|
|
38
|
-
`}async onAction(t){let{api:e,path:n,id:r,doc:i}=this.ctx;if(!e||!n)return;let l=
|
|
38
|
+
`}async onAction(t){let{api:e,path:n,id:r,doc:i}=this.ctx;if(!e||!n)return;let l=a=>this.dispatchEvent(new CustomEvent("set-field",{detail:{path:n,value:a}}));if(t==="undo-ai"&&this.beforeAi){l(this.beforeAi.value),this.beforeAi=null,this.update();return}if(t!=="ai"||this.busy||(typeof this.ctx.value=="string"?this.ctx.value.trim():"")&&!window.confirm(this.t("replaceAi")))return;let u=/^channels\.(\d+)\.text$/.exec(n),c=Array.isArray(i.channels)?i.channels:[],h=u?c[Number(u[1])]?.connection:void 0;this.busy=!0,this.notice=null,this.update();try{let a=await e("POST",$,{post:r,doc:{title:i.title,text:i.text,source:i.source??null},...typeof h=="string"?{channel:h}:{}});this.beforeAi??={value:this.ctx.value??null},l(a.text)}catch(a){this.notice=a.message}finally{this.busy=!1,this.ai=await L(e,!0),this.update()}}count(){let t=typeof this.ctx.value=="string"?this.ctx.value.trim():"",e=I(t),n=d=>d.counting==="x"?S(t):e,r=Array.isArray(this.ctx.doc.channels)?this.ctx.doc.channels:[],i=/^channels\.(\d+)\.text$/.exec(this.ctx.path??""),p=(i?r.filter((d,f)=>f===Number(i[1])):r.filter(d=>!(typeof d.text=="string"&&d.text.trim()))).map(d=>this.channels.find(f=>f.id===d.connection)).filter(d=>!!d?.maxLength),u=d=>(d.maxLength??0)-n(d),c=p.sort((d,f)=>u(d)-u(f))[0];if(!c)return`<span class="hint">${s(this.t("chars",{n:e}))}</span>`;let h=n(c),a=u(c)<0;return`<span class="${a?"error":"hint"}">${s(this.t("charsMax",{n:h,max:c.maxLength??0}))}${a?` \xB7 ${s(this.t("over",{channel:c.label}))}`:""}</span>`}},x=class extends g{live=null;busy=!1;notice=null;problems=[];notes={};checkedFor=null;timer;disconnectedCallback(){clearTimeout(this.timer)}delivery(){return this.live??this.ctx.value??{channels:{}}}css(){return`
|
|
39
39
|
.panel { display: flex; flex-direction: column; gap: 0.75rem; }
|
|
40
40
|
ul { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 0.5rem; }
|
|
41
41
|
li { display: flex; flex-direction: column; gap: 0.2rem; padding: 0.55rem 0.65rem; border: 1px solid var(--border); border-radius: var(--radius-sm, 8px); background: var(--surface); }
|
|
@@ -47,13 +47,15 @@ var x="/social/channels",f="/social/post",w="/social/ai",A="/social/share";var C
|
|
|
47
47
|
.schedule { display: flex; gap: 0.4rem; flex-wrap: wrap; }
|
|
48
48
|
.schedule input { flex: 1 1 10rem; }
|
|
49
49
|
.warning { margin: 0; padding: 0.5rem 0.65rem; border-radius: var(--radius-sm, 8px); background: var(--warning-soft); color: var(--warning-text); font-size: 0.8rem; }
|
|
50
|
-
`}check(){let{api:t,id:e}=this.ctx,{image:n=null,source:r=null}=this.ctx.doc,i=JSON.stringify([e,n,r]);!t||e===null||i===this.checkedFor||(this.checkedFor=i,t("POST",
|
|
51
|
-
<li class="${
|
|
52
|
-
<span class="name">${s(this.labelOf(
|
|
53
|
-
<span class="state">${s(
|
|
54
|
-
${
|
|
55
|
-
${
|
|
56
|
-
${
|
|
50
|
+
`}check(){let{api:t,id:e}=this.ctx,{image:n=null,source:r=null}=this.ctx.doc,i=JSON.stringify([e,n,r]);!t||e===null||i===this.checkedFor||(this.checkedFor=i,t("POST",v,{post:e,action:"check",image:n,source:r}).then(l=>{let p=l;this.problems=p.problems??[],this.notes=p.notes??{},this.update()}).catch(()=>{}))}render(){if(this.ctx.id===null)return`<p class="hint">${s(this.t("saveFirst"))}</p>`;this.check();let e=this.delivery(),n=(Array.isArray(this.ctx.doc.channels)?this.ctx.doc.channels:[]).filter(c=>typeof c.connection=="string"&&c.connection),r=c=>e.channels?.[c]??{state:"waiting",attempts:0},i=n.filter(c=>["waiting","scheduled"].includes(r(c.connection).state)),l=n.some(c=>r(c.connection).state==="scheduled"),p=n.map(c=>{let h=c.connection,a=r(h),d=a.state==="sending"&&a.attempts>0&&a.nextAttemptAt?this.t("retrying",{time:this.time(a.nextAttemptAt)}):this.t(a.state);return`
|
|
51
|
+
<li class="${a.state}" data-channel="${s(h)}">
|
|
52
|
+
<span class="name">${s(this.labelOf(h))}</span>
|
|
53
|
+
<span class="state">${s(d)}</span>
|
|
54
|
+
${a.state==="posted"&&a.url?`<a href="${s(a.url)}" target="_blank" rel="noopener">${s(this.t("view"))}</a>`:""}
|
|
55
|
+
${a.error&&a.state!=="posted"?`<p class="error">${s(a.error)}</p>`:""}
|
|
56
|
+
${a.state!=="posted"&&this.notes[h]?.info?`<p class="hint">${s(this.notes[h]?.info??"")}</p>`:""}
|
|
57
|
+
${a.state!=="posted"&&this.notes[h]?.warning?`<p class="warning">${s(this.notes[h]?.warning??"")}</p>`:""}
|
|
58
|
+
${a.state==="failed"&&this.canPost?`<div class="row"><button type="button" data-action="retry" data-channel="${s(h)}" ${this.busy?"disabled":""}>${s(this.t("retry"))}</button></div>`:""}
|
|
57
59
|
</li>`}).join(""),u=this.canPost?i.length===0?"":`
|
|
58
60
|
<div class="row"><button type="button" class="primary" data-action="now" ${this.busy?"disabled":""}>${s(this.t("postNow"))}</button></div>
|
|
59
61
|
${l&&e.postAt?`<p class="hint">${s(this.t("scheduledFor",{time:this.time(e.postAt)}))}</p>
|
|
@@ -63,15 +65,15 @@ var x="/social/channels",f="/social/post",w="/social/ai",A="/social/share";var C
|
|
|
63
65
|
</div>`}
|
|
64
66
|
<p class="hint">${s(this.t("savedOnly"))}</p>`:`<p class="hint">${s(this.t("noRight"))}</p>`;return`
|
|
65
67
|
<div class="panel">
|
|
66
|
-
${n.length?`<ul>${
|
|
67
|
-
${this.problems.map(
|
|
68
|
+
${n.length?`<ul>${p}</ul>`:`<p class="hint">${s(this.t("none"))}</p>`}
|
|
69
|
+
${this.problems.map(c=>`<p class="warning">${s(c)}</p>`).join("")}
|
|
68
70
|
${n.length?u:""}
|
|
69
71
|
${this.notice?`<p class="error" role="alert">${s(this.notice)}</p>`:""}
|
|
70
72
|
</div>
|
|
71
|
-
`}async onAction(t,e){let{api:n,id:r}=this.ctx;if(!n||r===null||this.busy)return;let i={post:r,action:t};if(t==="retry"&&(i.channel=e.getAttribute("data-channel")),t==="schedule"){let l=this.shadowRoot?.querySelector('[data-field="when"]');if(!l?.value){l?.focus();return}i.postAt=new Date(l.value).toISOString()}if(t==="now"){let
|
|
73
|
+
`}async onAction(t,e){let{api:n,id:r}=this.ctx;if(!n||r===null||this.busy)return;let i={post:r,action:t};if(t==="retry"&&(i.channel=e.getAttribute("data-channel")),t==="schedule"){let l=this.shadowRoot?.querySelector('[data-field="when"]');if(!l?.value){l?.focus();return}i.postAt=new Date(l.value).toISOString()}if(t==="now"){let p=(this.ctx.doc.channels??[]).filter(u=>this.delivery().channels?.[String(u.connection)]?.state!=="posted").length;if(!window.confirm(this.t("confirmNow",{n:p})))return}this.busy=!0,this.notice=null,this.update();try{let l=await n("POST",v,i);this.live=l.delivery,this.watch()}catch(l){this.notice=l.message}finally{this.busy=!1,this.update()}}watch(){clearTimeout(this.timer),!(!Object.values(this.delivery().channels??{}).some(e=>e.state==="sending")||!this.ctx.api||!this.ctx.collection||this.ctx.id===null)&&(this.timer=setTimeout(async()=>{try{let e=await this.ctx.api?.("GET",`/${this.ctx.collection}/${encodeURIComponent(String(this.ctx.id))}?depth=0`);this.live=e.delivery??null,this.update()}catch{}this.watch()},5e3))}},w=class extends g{busy=!1;notice=null;render(){let t=this.ctx.id!==null;return`
|
|
72
74
|
<div class="row">
|
|
73
75
|
<button type="button" data-action="share" ${!t||this.busy?"disabled":""}>${s(this.t(this.busy?"sharing":"share"))}</button>
|
|
74
76
|
</div>
|
|
75
77
|
${t?"":`<p class="hint">${s(this.t("shareSave"))}</p>`}
|
|
76
78
|
${this.notice?`<p class="error" role="alert">${s(this.notice)}</p>`:""}
|
|
77
|
-
`}async onAction(t){let{api:e,id:n,collection:r}=this.ctx;if(!(t!=="share"||!e||n===null||this.busy)){this.busy=!0,this.notice=null,this.update();try{let i=await e("POST",
|
|
79
|
+
`}async onAction(t){let{api:e,id:n,collection:r}=this.ctx;if(!(t!=="share"||!e||n===null||this.busy)){this.busy=!0,this.notice=null,this.update();try{let i=await e("POST",k,{collection:r,id:n});this.dispatchEvent(new CustomEvent("navigate",{detail:i.path}))}catch(i){this.notice=i.message}finally{this.busy=!1,this.update()}}}},m=(o,t)=>{customElements.get(o)||customElements.define(o,t)};m("ecms-social-channel",y);m("ecms-social-count",b);m("ecms-social-panel",x);m("ecms-social-share",w);
|
package/dist/index.d.ts
CHANGED
|
@@ -7,6 +7,8 @@ interface SocialMessage {
|
|
|
7
7
|
readonly post: string | number;
|
|
8
8
|
/** `<integration>:<connection name>`. */
|
|
9
9
|
readonly channel: string;
|
|
10
|
+
/** The post's title, e.g. a LINE card's heading. */
|
|
11
|
+
readonly title: string;
|
|
10
12
|
readonly text: string;
|
|
11
13
|
readonly link: string | null;
|
|
12
14
|
readonly image: {
|
|
@@ -20,12 +22,24 @@ interface SocialMessage {
|
|
|
20
22
|
}
|
|
21
23
|
/**
|
|
22
24
|
* A place social posts go (#312): an integration admins connect accounts to, and how it posts.
|
|
23
|
-
*
|
|
25
|
+
* Built in: the webhook, Facebook Pages and LINE (#313), and X (#380).
|
|
24
26
|
*/
|
|
25
27
|
interface SocialChannel {
|
|
26
28
|
readonly integration: IntegrationConfig;
|
|
27
29
|
/** Characters a post may have there, for the admin's counter. */
|
|
28
30
|
readonly maxLength?: number;
|
|
31
|
+
/** How `maxLength` counts: `x` is X's weighted length (a link 23, an emoji 2). */
|
|
32
|
+
readonly counting?: 'x';
|
|
33
|
+
/**
|
|
34
|
+
* What to say before posting, beside the channel in the panel, e.g. how many people a LINE
|
|
35
|
+
* broadcast reaches and the month's quota; `warning` when it may cost or fail.
|
|
36
|
+
*/
|
|
37
|
+
readonly preview?: (values: Readonly<Record<string, string>>, draft: {
|
|
38
|
+
readonly link: string | null;
|
|
39
|
+
}) => Promise<{
|
|
40
|
+
readonly info?: string;
|
|
41
|
+
readonly warning?: string;
|
|
42
|
+
}>;
|
|
29
43
|
/** Posts; returns the post's URL when the channel says. Throws `ChannelError` with the reason. */
|
|
30
44
|
readonly send: (values: Readonly<Record<string, string>>, message: SocialMessage) => Promise<{
|
|
31
45
|
url?: string | null;
|
|
@@ -37,6 +51,10 @@ declare class ChannelError extends Error {
|
|
|
37
51
|
constructor(message: string, permanent?: boolean);
|
|
38
52
|
}
|
|
39
53
|
|
|
54
|
+
declare const facebook: SocialChannel;
|
|
55
|
+
|
|
56
|
+
declare const line: SocialChannel;
|
|
57
|
+
|
|
40
58
|
type Doc = Record<string, unknown>;
|
|
41
59
|
/** What a social post starts with when shared from a document. */
|
|
42
60
|
interface ShareValues {
|
|
@@ -63,7 +81,7 @@ interface SocialPluginOptions {
|
|
|
63
81
|
doc: Doc;
|
|
64
82
|
collection: string;
|
|
65
83
|
}) => string | null | undefined;
|
|
66
|
-
/** Where posts go. Default: the webhook (Make, n8n, Zapier). */
|
|
84
|
+
/** Where posts go. Default: the webhook (Make, n8n, Zapier), Facebook Pages and LINE OA. */
|
|
67
85
|
readonly channels?: readonly SocialChannel[];
|
|
68
86
|
/** Slug of the social posts collection. Default `social-posts`. */
|
|
69
87
|
readonly slug?: string;
|
|
@@ -97,5 +115,7 @@ interface Delivery {
|
|
|
97
115
|
|
|
98
116
|
declare const webhook: SocialChannel;
|
|
99
117
|
|
|
100
|
-
|
|
118
|
+
declare const x: SocialChannel;
|
|
119
|
+
|
|
120
|
+
export { ChannelError, facebook, line, socialPlugin, webhook, x };
|
|
101
121
|
export type { ChannelDelivery, ChannelState, Delivery, ShareValues, SocialChannel, SocialMessage, SocialPluginOptions };
|
package/dist/index.js
CHANGED
|
@@ -8,6 +8,314 @@ var ChannelError = class extends Error {
|
|
|
8
8
|
}
|
|
9
9
|
};
|
|
10
10
|
|
|
11
|
+
// ../../node_modules/.pnpm/simple-icons@16.36.0/node_modules/simple-icons/index.mjs
|
|
12
|
+
var c = '<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>';
|
|
13
|
+
var t = '</title><path d="';
|
|
14
|
+
var a = '"/></svg>';
|
|
15
|
+
var siFacebook = { title: "Facebook", slug: "facebook", get svg() {
|
|
16
|
+
return c + "Facebook" + t + this.path + a;
|
|
17
|
+
}, path: "M9.101 23.691v-7.98H6.627v-3.667h2.474v-1.58c0-4.085 1.848-5.978 5.858-5.978.401 0 .955.042 1.468.103a8.68 8.68 0 0 1 1.141.195v3.325a8.623 8.623 0 0 0-.653-.036 26.805 26.805 0 0 0-.733-.009c-.707 0-1.259.096-1.675.309a1.686 1.686 0 0 0-.679.622c-.258.42-.374.995-.374 1.752v1.297h3.919l-.386 2.103-.287 1.564h-3.246v8.245C19.396 23.238 24 18.179 24 12.044c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.628 3.874 10.35 9.101 11.647Z", source: "https://about.meta.com/brand/resources/facebook/logo", hex: "0866FF", guidelines: "https://about.meta.com/brand/resources/facebook/logo" };
|
|
18
|
+
var siLine = { title: "LINE", slug: "line", get svg() {
|
|
19
|
+
return c + "LINE" + t + this.path + a;
|
|
20
|
+
}, path: "M19.365 9.863c.349 0 .63.285.63.631 0 .345-.281.63-.63.63H17.61v1.125h1.755c.349 0 .63.283.63.63 0 .344-.281.629-.63.629h-2.386c-.345 0-.627-.285-.627-.629V8.108c0-.345.282-.63.63-.63h2.386c.346 0 .627.285.627.63 0 .349-.281.63-.63.63H17.61v1.125h1.755zm-3.855 3.016c0 .27-.174.51-.432.596-.064.021-.133.031-.199.031-.211 0-.391-.09-.51-.25l-2.443-3.317v2.94c0 .344-.279.629-.631.629-.346 0-.626-.285-.626-.629V8.108c0-.27.173-.51.43-.595.06-.023.136-.033.194-.033.195 0 .375.104.495.254l2.462 3.33V8.108c0-.345.282-.63.63-.63.345 0 .63.285.63.63v4.771zm-5.741 0c0 .344-.282.629-.631.629-.345 0-.627-.285-.627-.629V8.108c0-.345.282-.63.63-.63.346 0 .628.285.628.63v4.771zm-2.466.629H4.917c-.345 0-.63-.285-.63-.629V8.108c0-.345.285-.63.63-.63.348 0 .63.285.63.63v4.141h1.756c.348 0 .629.283.629.63 0 .344-.282.629-.629.629M24 10.314C24 4.943 18.615.572 12 .572S0 4.943 0 10.314c0 4.811 4.27 8.842 10.035 9.608.391.082.923.258 1.058.59.12.301.079.766.038 1.08l-.164 1.02c-.045.301-.24 1.186 1.049.645 1.291-.539 6.916-4.078 9.436-6.975C23.176 14.393 24 12.458 24 10.314", source: "https://line.me/en/logo", hex: "00C300", guidelines: "https://line.me/en/logo" };
|
|
21
|
+
var siX = { title: "X", slug: "x", get svg() {
|
|
22
|
+
return c + "X" + t + this.path + a;
|
|
23
|
+
}, path: "M14.234 10.162 22.977 0h-2.072l-7.591 8.824L7.251 0H.258l9.168 13.343L.258 24H2.33l8.016-9.318L16.749 24h6.993zm-2.837 3.299-.929-1.329L3.076 1.56h3.182l5.965 8.532.929 1.329 7.754 11.09h-3.182z", source: "https://x.com", hex: "000000", guidelines: "https://about.x.com/en/who-we-are/brand-toolkit" };
|
|
24
|
+
|
|
25
|
+
// src/logos.ts
|
|
26
|
+
var logo = (icon) => ({
|
|
27
|
+
paths: [{ d: icon.path }],
|
|
28
|
+
color: `#${icon.hex}`
|
|
29
|
+
});
|
|
30
|
+
var FACEBOOK = logo(siFacebook);
|
|
31
|
+
var LINE = logo(siLine);
|
|
32
|
+
var X = logo(siX);
|
|
33
|
+
|
|
34
|
+
// src/facebook.ts
|
|
35
|
+
var version = () => process.env.FACEBOOK_GRAPH_VERSION ?? "v26.0";
|
|
36
|
+
var graph = () => `${(process.env.FACEBOOK_GRAPH_URL ?? "https://graph.facebook.com").replace(/\/+$/, "")}/${version()}`;
|
|
37
|
+
var app = () => {
|
|
38
|
+
const id = process.env.META_APP_ID;
|
|
39
|
+
const secret = process.env.META_APP_SECRET;
|
|
40
|
+
if (!id || !secret)
|
|
41
|
+
throw new Error("Set META_APP_ID and META_APP_SECRET (your Meta app) to connect Facebook Pages");
|
|
42
|
+
return { id, secret };
|
|
43
|
+
};
|
|
44
|
+
async function call(path, init) {
|
|
45
|
+
const query = new URLSearchParams(init.params);
|
|
46
|
+
const method = init.method ?? "GET";
|
|
47
|
+
let response;
|
|
48
|
+
try {
|
|
49
|
+
response = await fetch(method === "GET" ? `${graph()}${path}?${query}` : `${graph()}${path}`, {
|
|
50
|
+
method,
|
|
51
|
+
...method === "GET" ? {} : { body: query, headers: { "content-type": "application/x-www-form-urlencoded" } },
|
|
52
|
+
signal: AbortSignal.timeout(3e4)
|
|
53
|
+
});
|
|
54
|
+
} catch (error) {
|
|
55
|
+
throw new ChannelError(`Facebook could not be reached: ${error.message}`);
|
|
56
|
+
}
|
|
57
|
+
const answer = await response.json().catch(() => ({}));
|
|
58
|
+
if (!response.ok || answer.error) {
|
|
59
|
+
const code = answer.error?.code;
|
|
60
|
+
const message = `Facebook: ${answer.error?.message ?? `HTTP ${response.status}`}`;
|
|
61
|
+
const retry = response.status >= 500 || [1, 2, 4, 17, 32, 341, 613].includes(code ?? -1);
|
|
62
|
+
throw new ChannelError(message, !retry);
|
|
63
|
+
}
|
|
64
|
+
return answer;
|
|
65
|
+
}
|
|
66
|
+
var facebook = {
|
|
67
|
+
integration: {
|
|
68
|
+
id: "facebook-page",
|
|
69
|
+
label: "Facebook Page",
|
|
70
|
+
category: "social",
|
|
71
|
+
icon: FACEBOOK,
|
|
72
|
+
description: {
|
|
73
|
+
en: "Posts to Facebook Pages you manage. Needs a Meta app: set META_APP_ID and META_APP_SECRET.",
|
|
74
|
+
th: "\u0E42\u0E1E\u0E2A\u0E15\u0E4C\u0E44\u0E1B\u0E22\u0E31\u0E07\u0E40\u0E1E\u0E08 Facebook \u0E17\u0E35\u0E48\u0E04\u0E38\u0E13\u0E14\u0E39\u0E41\u0E25 \u0E15\u0E49\u0E2D\u0E07\u0E21\u0E35 Meta app: \u0E15\u0E31\u0E49\u0E07 META_APP_ID \u0E41\u0E25\u0E30 META_APP_SECRET"
|
|
75
|
+
},
|
|
76
|
+
docs: "https://easycms.dev/docs/social#facebook-page",
|
|
77
|
+
plugin: "@easy-cms/plugin-social",
|
|
78
|
+
kind: "oauth",
|
|
79
|
+
oauth: {
|
|
80
|
+
authorizeUrl: ({ redirectUri, state }) => {
|
|
81
|
+
const { id } = app();
|
|
82
|
+
const dialog = (process.env.FACEBOOK_DIALOG_URL ?? "https://www.facebook.com").replace(
|
|
83
|
+
/\/+$/,
|
|
84
|
+
""
|
|
85
|
+
);
|
|
86
|
+
const query = new URLSearchParams({
|
|
87
|
+
client_id: id,
|
|
88
|
+
redirect_uri: redirectUri,
|
|
89
|
+
state,
|
|
90
|
+
scope: "pages_show_list,pages_manage_posts,pages_read_engagement",
|
|
91
|
+
response_type: "code"
|
|
92
|
+
});
|
|
93
|
+
return `${dialog}/${version()}/dialog/oauth?${query}`;
|
|
94
|
+
},
|
|
95
|
+
// The code → a user token → a long-lived one → the Pages it manages, each with a Page token
|
|
96
|
+
// that doesn't expire (until the user takes it back).
|
|
97
|
+
exchange: async ({ code, redirectUri }) => {
|
|
98
|
+
const { id, secret } = app();
|
|
99
|
+
const short = await call("/oauth/access_token", {
|
|
100
|
+
params: { client_id: id, client_secret: secret, redirect_uri: redirectUri, code }
|
|
101
|
+
});
|
|
102
|
+
const long = await call("/oauth/access_token", {
|
|
103
|
+
params: {
|
|
104
|
+
grant_type: "fb_exchange_token",
|
|
105
|
+
client_id: id,
|
|
106
|
+
client_secret: secret,
|
|
107
|
+
fb_exchange_token: String(short.access_token ?? "")
|
|
108
|
+
}
|
|
109
|
+
});
|
|
110
|
+
const pages = await call("/me/accounts", {
|
|
111
|
+
params: {
|
|
112
|
+
fields: "id,name,access_token",
|
|
113
|
+
limit: "100",
|
|
114
|
+
access_token: String(long.access_token ?? "")
|
|
115
|
+
}
|
|
116
|
+
});
|
|
117
|
+
const list = Array.isArray(pages.data) ? pages.data : [];
|
|
118
|
+
if (list.length === 0)
|
|
119
|
+
throw new Error("This Facebook account manages no Page, or none was allowed");
|
|
120
|
+
return {
|
|
121
|
+
accounts: list.map((page) => ({
|
|
122
|
+
id: page.id,
|
|
123
|
+
name: page.name,
|
|
124
|
+
values: { pageId: page.id, token: page.access_token }
|
|
125
|
+
}))
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
},
|
|
129
|
+
// Checks the Page token without posting.
|
|
130
|
+
async test(values) {
|
|
131
|
+
try {
|
|
132
|
+
const me = await call("/me", {
|
|
133
|
+
params: { fields: "name", access_token: values.token ?? "" }
|
|
134
|
+
});
|
|
135
|
+
return { ok: true, account: String(me.name ?? values.pageId ?? "") };
|
|
136
|
+
} catch (error) {
|
|
137
|
+
return { ok: false, message: error.message };
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
},
|
|
141
|
+
async send(values, message) {
|
|
142
|
+
const token = values.token ?? "";
|
|
143
|
+
const page = values.pageId ?? "";
|
|
144
|
+
if (!token || !page) throw new ChannelError("The Page is not connected", true);
|
|
145
|
+
const result = message.image ? await call(`/${page}/photos`, {
|
|
146
|
+
method: "POST",
|
|
147
|
+
params: {
|
|
148
|
+
url: message.image.url,
|
|
149
|
+
caption: message.link ? `${message.text}
|
|
150
|
+
|
|
151
|
+
${message.link}` : message.text,
|
|
152
|
+
access_token: token
|
|
153
|
+
}
|
|
154
|
+
}) : await call(`/${page}/feed`, {
|
|
155
|
+
method: "POST",
|
|
156
|
+
params: {
|
|
157
|
+
message: message.text,
|
|
158
|
+
...message.link ? { link: message.link } : {},
|
|
159
|
+
access_token: token
|
|
160
|
+
}
|
|
161
|
+
});
|
|
162
|
+
const id = String(result.post_id ?? result.id ?? "");
|
|
163
|
+
return { url: id ? `https://www.facebook.com/${id}` : null };
|
|
164
|
+
}
|
|
165
|
+
};
|
|
166
|
+
|
|
167
|
+
// src/line.ts
|
|
168
|
+
var api = () => (process.env.LINE_API_URL ?? "https://api.line.me").replace(/\/+$/, "");
|
|
169
|
+
var MAX_TEXT = 300;
|
|
170
|
+
async function call2(path, token, body) {
|
|
171
|
+
if (!token) throw new ChannelError("No channel access token", true);
|
|
172
|
+
let response;
|
|
173
|
+
try {
|
|
174
|
+
response = await fetch(`${api()}${path}`, {
|
|
175
|
+
method: body === void 0 ? "GET" : "POST",
|
|
176
|
+
headers: {
|
|
177
|
+
authorization: `Bearer ${token}`,
|
|
178
|
+
...body === void 0 ? {} : { "content-type": "application/json" }
|
|
179
|
+
},
|
|
180
|
+
...body === void 0 ? {} : { body: JSON.stringify(body) },
|
|
181
|
+
signal: AbortSignal.timeout(3e4)
|
|
182
|
+
});
|
|
183
|
+
} catch (error) {
|
|
184
|
+
throw new ChannelError(`LINE could not be reached: ${error.message}`);
|
|
185
|
+
}
|
|
186
|
+
const answer = await response.json().catch(() => ({}));
|
|
187
|
+
if (!response.ok) {
|
|
188
|
+
const details = Array.isArray(answer.details) ? ` (${answer.details.map((d) => d.message).join("; ")})` : "";
|
|
189
|
+
throw new ChannelError(
|
|
190
|
+
`LINE: ${String(answer.message ?? `HTTP ${response.status}`)}${details}`,
|
|
191
|
+
response.status !== 429 && response.status < 500
|
|
192
|
+
);
|
|
193
|
+
}
|
|
194
|
+
return answer;
|
|
195
|
+
}
|
|
196
|
+
var cut = (text, max) => {
|
|
197
|
+
const chars = [...text];
|
|
198
|
+
return chars.length > max ? `${chars.slice(0, max - 1).join("").trimEnd()}\u2026` : text;
|
|
199
|
+
};
|
|
200
|
+
function flexMessage(message, readMore) {
|
|
201
|
+
if (message.image && !message.image.url.startsWith("https://"))
|
|
202
|
+
throw new ChannelError("LINE shows images only from https addresses", true);
|
|
203
|
+
const title = message.title.trim();
|
|
204
|
+
const text = cut(message.text.trim(), MAX_TEXT);
|
|
205
|
+
return {
|
|
206
|
+
type: "flex",
|
|
207
|
+
altText: cut([title, text].filter(Boolean).join(": "), 400),
|
|
208
|
+
contents: {
|
|
209
|
+
type: "bubble",
|
|
210
|
+
...message.image ? {
|
|
211
|
+
hero: {
|
|
212
|
+
type: "image",
|
|
213
|
+
url: message.image.url,
|
|
214
|
+
size: "full",
|
|
215
|
+
aspectRatio: "20:13",
|
|
216
|
+
aspectMode: "cover",
|
|
217
|
+
...message.link ? { action: { type: "uri", uri: message.link } } : {}
|
|
218
|
+
}
|
|
219
|
+
} : {},
|
|
220
|
+
body: {
|
|
221
|
+
type: "box",
|
|
222
|
+
layout: "vertical",
|
|
223
|
+
spacing: "md",
|
|
224
|
+
contents: [
|
|
225
|
+
...title ? [{ type: "text", text: cut(title, 120), weight: "bold", size: "lg", wrap: true }] : [],
|
|
226
|
+
{ type: "text", text, size: "sm", color: "#555555", wrap: true }
|
|
227
|
+
]
|
|
228
|
+
},
|
|
229
|
+
...message.link ? {
|
|
230
|
+
footer: {
|
|
231
|
+
type: "box",
|
|
232
|
+
layout: "vertical",
|
|
233
|
+
contents: [
|
|
234
|
+
{
|
|
235
|
+
type: "button",
|
|
236
|
+
style: "primary",
|
|
237
|
+
action: { type: "uri", label: readMore, uri: message.link }
|
|
238
|
+
}
|
|
239
|
+
]
|
|
240
|
+
}
|
|
241
|
+
} : {}
|
|
242
|
+
}
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
var line = {
|
|
246
|
+
maxLength: MAX_TEXT,
|
|
247
|
+
integration: {
|
|
248
|
+
id: "line-oa",
|
|
249
|
+
label: "LINE OA",
|
|
250
|
+
category: "social",
|
|
251
|
+
icon: LINE,
|
|
252
|
+
description: {
|
|
253
|
+
en: "Broadcasts each post as a card to your LINE Official Account\u2019s followers",
|
|
254
|
+
th: "broadcast \u0E41\u0E15\u0E48\u0E25\u0E30\u0E42\u0E1E\u0E2A\u0E15\u0E4C\u0E40\u0E1B\u0E47\u0E19\u0E01\u0E32\u0E23\u0E4C\u0E14\u0E16\u0E36\u0E07\u0E1C\u0E39\u0E49\u0E15\u0E34\u0E14\u0E15\u0E32\u0E21 LINE Official Account \u0E02\u0E2D\u0E07\u0E04\u0E38\u0E13"
|
|
255
|
+
},
|
|
256
|
+
docs: "https://easycms.dev/docs/social#line-oa",
|
|
257
|
+
plugin: "@easy-cms/plugin-social",
|
|
258
|
+
kind: "fields",
|
|
259
|
+
fields: [
|
|
260
|
+
{
|
|
261
|
+
name: "token",
|
|
262
|
+
label: { en: "Channel access token", th: "Channel access token" },
|
|
263
|
+
description: {
|
|
264
|
+
en: "LINE Developers \u2192 your Messaging API channel \u2192 Channel access token (long-lived).",
|
|
265
|
+
th: "LINE Developers \u2192 Messaging API channel \u0E02\u0E2D\u0E07\u0E04\u0E38\u0E13 \u2192 Channel access token (long-lived)"
|
|
266
|
+
},
|
|
267
|
+
secret: true,
|
|
268
|
+
required: true
|
|
269
|
+
},
|
|
270
|
+
{
|
|
271
|
+
name: "readMore",
|
|
272
|
+
label: { en: "Button text", th: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E1A\u0E19\u0E1B\u0E38\u0E48\u0E21" },
|
|
273
|
+
placeholder: "Read more",
|
|
274
|
+
description: { en: 'Empty: "Read more".', th: '\u0E16\u0E49\u0E32\u0E27\u0E48\u0E32\u0E07: "Read more"' }
|
|
275
|
+
}
|
|
276
|
+
],
|
|
277
|
+
env: { token: "LINE_CHANNEL_ACCESS_TOKEN" },
|
|
278
|
+
async test(values) {
|
|
279
|
+
try {
|
|
280
|
+
const bot = await call2("/v2/bot/info", values.token ?? "");
|
|
281
|
+
return { ok: true, account: [bot.displayName, bot.basicId].filter(Boolean).join(" ") };
|
|
282
|
+
} catch (error) {
|
|
283
|
+
return { ok: false, message: error.message };
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
},
|
|
287
|
+
// Followers (yesterday's count, when LINE has it) and this month's message quota.
|
|
288
|
+
async preview(values) {
|
|
289
|
+
const token = values.token ?? "";
|
|
290
|
+
const yesterday = new Date(Date.now() - 864e5).toISOString().slice(0, 10).replace(/-/g, "");
|
|
291
|
+
const [followers, quota, used] = await Promise.all([
|
|
292
|
+
call2(`/v2/bot/insight/followers?date=${yesterday}`, token).catch(() => null),
|
|
293
|
+
call2("/v2/bot/message/quota", token).catch(() => null),
|
|
294
|
+
call2("/v2/bot/message/quota/consumption", token).catch(() => null)
|
|
295
|
+
]);
|
|
296
|
+
const reach = followers?.status === "ready" ? Number(followers.targetedReaches ?? followers.followers) : null;
|
|
297
|
+
const limit = quota?.type === "limited" ? Number(quota.value) : null;
|
|
298
|
+
const spent = used ? Number(used.totalUsage ?? 0) : null;
|
|
299
|
+
const parts = [
|
|
300
|
+
reach !== null ? `Reaches about ${reach.toLocaleString("en")} followers` : null,
|
|
301
|
+
limit !== null && spent !== null ? `messages this month: ${spent.toLocaleString("en")} / ${limit.toLocaleString("en")}` : null
|
|
302
|
+
].filter(Boolean);
|
|
303
|
+
const over = reach !== null && limit !== null && spent !== null && spent + reach > limit;
|
|
304
|
+
return {
|
|
305
|
+
...parts.length ? { info: parts.join(" \xB7 ") } : {},
|
|
306
|
+
...over ? {
|
|
307
|
+
warning: "This broadcast goes over the month\u2019s free messages: LINE charges for the rest, or refuses them"
|
|
308
|
+
} : {}
|
|
309
|
+
};
|
|
310
|
+
},
|
|
311
|
+
async send(values, message) {
|
|
312
|
+
await call2("/v2/bot/message/broadcast", values.token ?? "", {
|
|
313
|
+
messages: [flexMessage(message, values.readMore?.trim() || "Read more")]
|
|
314
|
+
});
|
|
315
|
+
return { url: null };
|
|
316
|
+
}
|
|
317
|
+
};
|
|
318
|
+
|
|
11
319
|
// src/plugin.ts
|
|
12
320
|
import {
|
|
13
321
|
definePlugin
|
|
@@ -18,7 +326,7 @@ var INFO = {
|
|
|
18
326
|
name: "@easy-cms/plugin-social",
|
|
19
327
|
// The plugin API it is written for (`PLUGIN_API_VERSION` of @easy-cms/core).
|
|
20
328
|
apiVersion: 1,
|
|
21
|
-
...true ? { version: "1.
|
|
329
|
+
...true ? { version: "1.39.0" } : {}
|
|
22
330
|
};
|
|
23
331
|
|
|
24
332
|
// src/shared.ts
|
|
@@ -26,6 +334,37 @@ var CHANNELS_PATH = "/social/channels";
|
|
|
26
334
|
var ACTION_PATH = "/social/post";
|
|
27
335
|
var AI_PATH = "/social/ai";
|
|
28
336
|
var SHARE_PATH = "/social/share";
|
|
337
|
+
var X_MAX = 280;
|
|
338
|
+
var LIGHT = [
|
|
339
|
+
[0, 4351],
|
|
340
|
+
[8192, 8205],
|
|
341
|
+
[8208, 8223],
|
|
342
|
+
[8242, 8247]
|
|
343
|
+
];
|
|
344
|
+
function xLength(text) {
|
|
345
|
+
let total = 0;
|
|
346
|
+
for (const part of text.split(/(https?:\/\/\S+)/)) {
|
|
347
|
+
if (/^https?:\/\//.test(part)) {
|
|
348
|
+
total += 23;
|
|
349
|
+
continue;
|
|
350
|
+
}
|
|
351
|
+
const graphemes = typeof Intl.Segmenter === "function" ? Array.from(
|
|
352
|
+
new Intl.Segmenter(void 0, { granularity: "grapheme" }).segment(part),
|
|
353
|
+
(g) => g.segment
|
|
354
|
+
) : [...part];
|
|
355
|
+
for (const grapheme of graphemes) {
|
|
356
|
+
if (/\p{Extended_Pictographic}/u.test(grapheme)) {
|
|
357
|
+
total += 2;
|
|
358
|
+
continue;
|
|
359
|
+
}
|
|
360
|
+
for (const char of grapheme) {
|
|
361
|
+
const code = char.codePointAt(0) ?? 0;
|
|
362
|
+
total += LIGHT.some(([from, to]) => code >= from && code <= to) ? 1 : 2;
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
return total;
|
|
367
|
+
}
|
|
29
368
|
|
|
30
369
|
// src/webhook.ts
|
|
31
370
|
import { createHmac, randomUUID } from "crypto";
|
|
@@ -73,8 +412,8 @@ var webhook = {
|
|
|
73
412
|
label: { en: "Webhook (social)", th: "Webhook (\u0E42\u0E0B\u0E40\u0E0A\u0E35\u0E22\u0E25)" },
|
|
74
413
|
category: "social",
|
|
75
414
|
description: {
|
|
76
|
-
en: "Posts go to a URL as signed JSON: a Make, n8n or Zapier scenario that posts to
|
|
77
|
-
th: "\u0E2A\u0E48\u0E07\u0E42\u0E1E\u0E2A\u0E15\u0E4C\u0E40\u0E1B\u0E47\u0E19 JSON \u0E17\u0E35\u0E48\u0E25\u0E07\u0E25\u0E32\u0E22\u0E40\u0E0B\u0E47\u0E19\u0E44\u0E1B\u0E22\u0E31\u0E07 URL \u0E40\u0E0A\u0E48\u0E19 scenario \u0E02\u0E2D\u0E07 Make, n8n \u0E2B\u0E23\u0E37\u0E2D Zapier \u0E17\u0E35\u0E48\u0E42\u0E1E\u0E2A\u0E15\u0E4C\u0E15\u0E48\u0E2D\u0E44\u0E1B\u0E22\u0E31\u0E07
|
|
415
|
+
en: "Posts go to a URL as signed JSON: a Make, n8n or Zapier scenario that posts to LinkedIn, Threads, Discord or anywhere else",
|
|
416
|
+
th: "\u0E2A\u0E48\u0E07\u0E42\u0E1E\u0E2A\u0E15\u0E4C\u0E40\u0E1B\u0E47\u0E19 JSON \u0E17\u0E35\u0E48\u0E25\u0E07\u0E25\u0E32\u0E22\u0E40\u0E0B\u0E47\u0E19\u0E44\u0E1B\u0E22\u0E31\u0E07 URL \u0E40\u0E0A\u0E48\u0E19 scenario \u0E02\u0E2D\u0E07 Make, n8n \u0E2B\u0E23\u0E37\u0E2D Zapier \u0E17\u0E35\u0E48\u0E42\u0E1E\u0E2A\u0E15\u0E4C\u0E15\u0E48\u0E2D\u0E44\u0E1B\u0E22\u0E31\u0E07 LinkedIn, Threads, Discord \u0E2B\u0E23\u0E37\u0E2D\u0E17\u0E35\u0E48\u0E2D\u0E37\u0E48\u0E19"
|
|
78
417
|
},
|
|
79
418
|
icon: "link",
|
|
80
419
|
docs: "https://easycms.dev/docs/social",
|
|
@@ -105,6 +444,168 @@ var webhook = {
|
|
|
105
444
|
send: (values, message) => post(values, { ...message })
|
|
106
445
|
};
|
|
107
446
|
|
|
447
|
+
// src/x.ts
|
|
448
|
+
import { createHmac as createHmac2, randomBytes } from "crypto";
|
|
449
|
+
var api2 = () => (process.env.X_API_URL ?? "https://api.x.com").replace(/\/+$/, "");
|
|
450
|
+
var COST = { post: "$0.015", withLink: "$0.20" };
|
|
451
|
+
var enc = (value) => encodeURIComponent(value).replace(
|
|
452
|
+
/[!'()*]/g,
|
|
453
|
+
(c2) => `%${c2.charCodeAt(0).toString(16).toUpperCase()}`
|
|
454
|
+
);
|
|
455
|
+
function oauthHeader(method, url, keys, now = Math.floor(Date.now() / 1e3), nonce = randomBytes(16).toString("hex")) {
|
|
456
|
+
const target = new URL(url);
|
|
457
|
+
const oauth = {
|
|
458
|
+
oauth_consumer_key: keys.apiKey ?? "",
|
|
459
|
+
oauth_nonce: nonce,
|
|
460
|
+
oauth_signature_method: "HMAC-SHA1",
|
|
461
|
+
oauth_timestamp: String(now),
|
|
462
|
+
oauth_token: keys.accessToken ?? "",
|
|
463
|
+
oauth_version: "1.0"
|
|
464
|
+
};
|
|
465
|
+
const params = [...Object.entries(oauth), ...target.searchParams.entries()].map(([k, v]) => [enc(k), enc(v)]).sort(([a2, x2], [b, y]) => a2 === b ? x2 < y ? -1 : 1 : a2 < b ? -1 : 1).map(([k, v]) => `${k}=${v}`).join("&");
|
|
466
|
+
const base = [method.toUpperCase(), enc(`${target.origin}${target.pathname}`), enc(params)].join(
|
|
467
|
+
"&"
|
|
468
|
+
);
|
|
469
|
+
const signature = createHmac2(
|
|
470
|
+
"sha1",
|
|
471
|
+
`${enc(keys.apiSecret ?? "")}&${enc(keys.accessTokenSecret ?? "")}`
|
|
472
|
+
).update(base).digest("base64");
|
|
473
|
+
return `OAuth ${Object.entries({ ...oauth, oauth_signature: signature }).map(([k, v]) => `${enc(k)}="${enc(v)}"`).join(", ")}`;
|
|
474
|
+
}
|
|
475
|
+
function hint(status, message) {
|
|
476
|
+
if (status === 401)
|
|
477
|
+
return " (check the four keys: making new ones in the X console replaces the old ones)";
|
|
478
|
+
if (status === 402) return " (add credits in console.x.com)";
|
|
479
|
+
if (status === 403 && !/duplicate/i.test(message))
|
|
480
|
+
return " (the app needs Read and Write permission: set it, then make the access token again)";
|
|
481
|
+
return "";
|
|
482
|
+
}
|
|
483
|
+
async function call3(path, keys, body) {
|
|
484
|
+
for (const key of ["apiKey", "apiSecret", "accessToken", "accessTokenSecret"])
|
|
485
|
+
if (!keys[key]) throw new ChannelError(`X: ${key} is missing`, true);
|
|
486
|
+
const url = `${api2()}${path}`;
|
|
487
|
+
const method = body === void 0 ? "GET" : "POST";
|
|
488
|
+
let response;
|
|
489
|
+
try {
|
|
490
|
+
response = await fetch(url, {
|
|
491
|
+
method,
|
|
492
|
+
headers: {
|
|
493
|
+
authorization: oauthHeader(method, url, keys),
|
|
494
|
+
...body === void 0 ? {} : { "content-type": "application/json" }
|
|
495
|
+
},
|
|
496
|
+
...body === void 0 ? {} : { body: JSON.stringify(body) },
|
|
497
|
+
signal: AbortSignal.timeout(3e4)
|
|
498
|
+
});
|
|
499
|
+
} catch (error) {
|
|
500
|
+
throw new ChannelError(`X could not be reached: ${error.message}`);
|
|
501
|
+
}
|
|
502
|
+
const answer = await response.json().catch(() => ({}));
|
|
503
|
+
if (!response.ok || !answer.data && answer.errors?.length) {
|
|
504
|
+
const said = answer.detail ?? answer.errors?.[0]?.detail ?? answer.errors?.[0]?.message ?? answer.title ?? `HTTP ${response.status}`;
|
|
505
|
+
throw new ChannelError(
|
|
506
|
+
`X: ${said}${hint(response.status, said)}`,
|
|
507
|
+
response.status !== 429 && response.status < 500
|
|
508
|
+
);
|
|
509
|
+
}
|
|
510
|
+
return answer.data ?? {};
|
|
511
|
+
}
|
|
512
|
+
var usernames = /* @__PURE__ */ new Map();
|
|
513
|
+
async function username(keys) {
|
|
514
|
+
const known = usernames.get(keys.accessToken ?? "");
|
|
515
|
+
if (known) return known;
|
|
516
|
+
const me = await call3("/2/users/me", keys);
|
|
517
|
+
if (me.username) usernames.set(keys.accessToken ?? "", me.username);
|
|
518
|
+
return me.username ?? null;
|
|
519
|
+
}
|
|
520
|
+
function postText(message) {
|
|
521
|
+
const text = message.text.trim();
|
|
522
|
+
const full = [text, message.link].filter(Boolean).join("\n\n");
|
|
523
|
+
if (xLength(full) > X_MAX)
|
|
524
|
+
throw new ChannelError(
|
|
525
|
+
`X: the post is ${xLength(full)} of ${X_MAX} characters (a link counts 23): shorten X\u2019s text`,
|
|
526
|
+
true
|
|
527
|
+
);
|
|
528
|
+
return full;
|
|
529
|
+
}
|
|
530
|
+
var x = {
|
|
531
|
+
// The text beside a link: 280, less the link (23) and the blank line before it.
|
|
532
|
+
maxLength: X_MAX - 25,
|
|
533
|
+
counting: "x",
|
|
534
|
+
integration: {
|
|
535
|
+
id: "x",
|
|
536
|
+
label: "X",
|
|
537
|
+
category: "social",
|
|
538
|
+
icon: X,
|
|
539
|
+
description: {
|
|
540
|
+
en: "Posts to your X account through your own X app. X charges for each post.",
|
|
541
|
+
th: "\u0E42\u0E1E\u0E2A\u0E15\u0E4C\u0E44\u0E1B\u0E22\u0E31\u0E07\u0E1A\u0E31\u0E0D\u0E0A\u0E35 X \u0E02\u0E2D\u0E07\u0E04\u0E38\u0E13\u0E1C\u0E48\u0E32\u0E19\u0E41\u0E2D\u0E1B X \u0E02\u0E2D\u0E07\u0E04\u0E38\u0E13\u0E40\u0E2D\u0E07 X \u0E04\u0E34\u0E14\u0E40\u0E07\u0E34\u0E19\u0E15\u0E48\u0E2D\u0E42\u0E1E\u0E2A\u0E15\u0E4C"
|
|
542
|
+
},
|
|
543
|
+
docs: "https://easycms.dev/docs/social#x",
|
|
544
|
+
plugin: "@easy-cms/plugin-social",
|
|
545
|
+
kind: "fields",
|
|
546
|
+
fields: [
|
|
547
|
+
{
|
|
548
|
+
name: "apiKey",
|
|
549
|
+
label: { en: "API key", th: "API key" },
|
|
550
|
+
description: {
|
|
551
|
+
en: "console.x.com \u2192 your app \u2192 Keys and tokens \u2192 OAuth 1.0 keys: Consumer key.",
|
|
552
|
+
th: "console.x.com \u2192 \u0E41\u0E2D\u0E1B\u0E02\u0E2D\u0E07\u0E04\u0E38\u0E13 \u2192 Keys and tokens \u2192 OAuth 1.0 keys: Consumer key"
|
|
553
|
+
},
|
|
554
|
+
required: true
|
|
555
|
+
},
|
|
556
|
+
{
|
|
557
|
+
name: "apiSecret",
|
|
558
|
+
label: { en: "API secret", th: "API secret" },
|
|
559
|
+
secret: true,
|
|
560
|
+
required: true
|
|
561
|
+
},
|
|
562
|
+
{
|
|
563
|
+
name: "accessToken",
|
|
564
|
+
label: { en: "Access token", th: "Access token" },
|
|
565
|
+
description: {
|
|
566
|
+
en: "Same page \u2192 Access token: made after the app has Read and Write permission.",
|
|
567
|
+
th: "\u0E2B\u0E19\u0E49\u0E32\u0E40\u0E14\u0E35\u0E22\u0E27\u0E01\u0E31\u0E19 \u2192 Access token: \u0E2A\u0E23\u0E49\u0E32\u0E07\u0E2B\u0E25\u0E31\u0E07\u0E15\u0E31\u0E49\u0E07\u0E41\u0E2D\u0E1B\u0E40\u0E1B\u0E47\u0E19 Read and Write \u0E41\u0E25\u0E49\u0E27"
|
|
568
|
+
},
|
|
569
|
+
secret: true,
|
|
570
|
+
required: true
|
|
571
|
+
},
|
|
572
|
+
{
|
|
573
|
+
name: "accessTokenSecret",
|
|
574
|
+
label: { en: "Access token secret", th: "Access token secret" },
|
|
575
|
+
secret: true,
|
|
576
|
+
required: true
|
|
577
|
+
}
|
|
578
|
+
],
|
|
579
|
+
env: {
|
|
580
|
+
apiKey: "X_API_KEY",
|
|
581
|
+
apiSecret: "X_API_SECRET",
|
|
582
|
+
accessToken: "X_ACCESS_TOKEN",
|
|
583
|
+
accessTokenSecret: "X_ACCESS_TOKEN_SECRET"
|
|
584
|
+
},
|
|
585
|
+
async test(values) {
|
|
586
|
+
try {
|
|
587
|
+
const me = await call3("/2/users/me", values);
|
|
588
|
+
if (me.username) usernames.set(values.accessToken ?? "", me.username);
|
|
589
|
+
return { ok: true, account: me.username ? `@${me.username}` : me.name ?? "X" };
|
|
590
|
+
} catch (error) {
|
|
591
|
+
return { ok: false, message: error.message };
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
},
|
|
595
|
+
// X's API has no balance to read: what this post costs.
|
|
596
|
+
async preview(_values, draft) {
|
|
597
|
+
return {
|
|
598
|
+
info: draft?.link ? `X API: about ${COST.withLink} for a post with a link` : `X API: about ${COST.post} a post`
|
|
599
|
+
};
|
|
600
|
+
},
|
|
601
|
+
async send(values, message) {
|
|
602
|
+
const post2 = await call3("/2/tweets", values, { text: postText(message) });
|
|
603
|
+
if (!post2.id) return { url: null };
|
|
604
|
+
const name = await username(values).catch(() => null);
|
|
605
|
+
return { url: `https://x.com/${name ?? "i/web"}/status/${post2.id}` };
|
|
606
|
+
}
|
|
607
|
+
};
|
|
608
|
+
|
|
108
609
|
// src/plugin.ts
|
|
109
610
|
var RETRIES = [6e4, 5 * 6e4, 30 * 6e4];
|
|
110
611
|
var LEASE = 2 * 6e4;
|
|
@@ -113,16 +614,16 @@ var nobody = () => false;
|
|
|
113
614
|
var later = (from, ms) => new Date(from.getTime() + ms).toISOString();
|
|
114
615
|
var json = (status, message) => Response.json({ errors: [{ message }] }, { status });
|
|
115
616
|
function socialPlugin(options = {}) {
|
|
116
|
-
const channels = options.channels ?? [webhook];
|
|
617
|
+
const channels = options.channels ?? [webhook, facebook, line, x];
|
|
117
618
|
const slug = options.slug ?? "social-posts";
|
|
118
619
|
const sources = options.collections ?? [];
|
|
119
620
|
return definePlugin((config) => {
|
|
120
|
-
if (config.collections?.some((
|
|
621
|
+
if (config.collections?.some((c2) => c2.slug === slug))
|
|
121
622
|
throw new Error(`socialPlugin: there is already a collection "${slug}"; set \`slug\``);
|
|
122
|
-
const missing = sources.filter((s) => !config.collections?.some((
|
|
623
|
+
const missing = sources.filter((s) => !config.collections?.some((c2) => c2.slug === s));
|
|
123
624
|
if (missing.length > 0)
|
|
124
625
|
throw new Error(`socialPlugin: unknown collection ${missing.map((s) => `"${s}"`).join(", ")}`);
|
|
125
|
-
const channelOf = (connection) => channels.find((
|
|
626
|
+
const channelOf = (connection) => channels.find((c2) => connection.startsWith(`${c2.integration.id}:`));
|
|
126
627
|
const nameOf = (connection) => connection.slice(connection.indexOf(":") + 1);
|
|
127
628
|
const fields = [
|
|
128
629
|
{ name: "title", type: "text", required: true, label: { en: "Title", th: "\u0E0A\u0E37\u0E48\u0E2D" } },
|
|
@@ -263,9 +764,9 @@ function socialPlugin(options = {}) {
|
|
|
263
764
|
(r) => typeof r.connection === "string" && r.connection
|
|
264
765
|
);
|
|
265
766
|
const nextAtOf = (delivery) => {
|
|
266
|
-
const times = Object.values(delivery.channels).filter((
|
|
267
|
-
(
|
|
268
|
-
).filter((
|
|
767
|
+
const times = Object.values(delivery.channels).filter((c2) => c2.state === "sending" || c2.state === "scheduled").map(
|
|
768
|
+
(c2) => c2.state === "scheduled" ? delivery.postAt ?? null : c2.nextAttemptAt ?? null
|
|
769
|
+
).filter((t2) => !!t2).sort();
|
|
269
770
|
return times[0] ?? null;
|
|
270
771
|
};
|
|
271
772
|
const save = (cms, id, delivery, where) => {
|
|
@@ -289,7 +790,7 @@ function socialPlugin(options = {}) {
|
|
|
289
790
|
return null;
|
|
290
791
|
};
|
|
291
792
|
const isLive = async (cms, ref) => {
|
|
292
|
-
const config2 = cms.config.collections.find((
|
|
793
|
+
const config2 = cms.config.collections.find((c2) => c2.slug === ref.collection);
|
|
293
794
|
if (!config2?.drafts) return true;
|
|
294
795
|
const live = await cms.findById(ref.collection, ref.id, { depth: 0 });
|
|
295
796
|
return !!live && live.status === "published";
|
|
@@ -374,6 +875,7 @@ function socialPlugin(options = {}) {
|
|
|
374
875
|
const result = await channel.send(conn.values, {
|
|
375
876
|
post: id,
|
|
376
877
|
channel: connection,
|
|
878
|
+
title: String(doc.title ?? ""),
|
|
377
879
|
text: String(row.text || doc.text || ""),
|
|
378
880
|
link: typeof doc.link === "string" && doc.link ? doc.link : null,
|
|
379
881
|
image,
|
|
@@ -414,7 +916,8 @@ function socialPlugin(options = {}) {
|
|
|
414
916
|
id: `${id}:${conn.name}`,
|
|
415
917
|
label: `${name} \xB7 ${conn.name}`,
|
|
416
918
|
...icon ? { icon } : {},
|
|
417
|
-
...channel.maxLength ? { maxLength: channel.maxLength } : {}
|
|
919
|
+
...channel.maxLength ? { maxLength: channel.maxLength } : {},
|
|
920
|
+
...channel.counting ? { counting: channel.counting } : {}
|
|
418
921
|
});
|
|
419
922
|
}
|
|
420
923
|
}
|
|
@@ -447,7 +950,19 @@ function socialPlugin(options = {}) {
|
|
|
447
950
|
const ref = sourceOf(doc2);
|
|
448
951
|
if (ref && !await isLive(cms, ref))
|
|
449
952
|
problems.push("The source isn\u2019t published yet: its link may not open");
|
|
450
|
-
|
|
953
|
+
const notes = {};
|
|
954
|
+
for (const row of rowsOf(saved)) {
|
|
955
|
+
const connection = row.connection;
|
|
956
|
+
const channel = channelOf(connection);
|
|
957
|
+
if (!channel?.preview) continue;
|
|
958
|
+
const conn = await cms.integrations.get(channel.integration.id, {
|
|
959
|
+
name: nameOf(connection)
|
|
960
|
+
});
|
|
961
|
+
const link = typeof doc2.link === "string" && doc2.link ? doc2.link : null;
|
|
962
|
+
if (conn)
|
|
963
|
+
notes[connection] = await channel.preview(conn.values, { link }).catch(() => ({}));
|
|
964
|
+
}
|
|
965
|
+
return { problems, notes };
|
|
451
966
|
}
|
|
452
967
|
if (!await mayPost(cms, user, id)) return json(403, "You may not post this");
|
|
453
968
|
const doc = await cms.findById(slug, id, { depth: 0 });
|
|
@@ -456,20 +971,20 @@ function socialPlugin(options = {}) {
|
|
|
456
971
|
const delivery = deliveryOf(doc);
|
|
457
972
|
const now = /* @__PURE__ */ new Date();
|
|
458
973
|
const action = input.action;
|
|
459
|
-
const open = rows.map((r) => r.connection).filter((
|
|
974
|
+
const open = rows.map((r) => r.connection).filter((c2) => delivery.channels[c2]?.state !== "posted");
|
|
460
975
|
if (action === "now" || action === "schedule" || action === "retry") {
|
|
461
976
|
if (rows.length === 0) return json(400, "Add a channel first");
|
|
462
977
|
const image = await imageOf(cms, doc.image);
|
|
463
978
|
if ("error" in image) return json(400, image.error);
|
|
464
|
-
for (const
|
|
465
|
-
if (!channelOf(
|
|
979
|
+
for (const c2 of open)
|
|
980
|
+
if (!channelOf(c2)) return json(400, `"${c2}" is not a channel this site has`);
|
|
466
981
|
}
|
|
467
982
|
if (action === "now" || action === "retry") {
|
|
468
|
-
const targets = action === "retry" ? open.filter((
|
|
983
|
+
const targets = action === "retry" ? open.filter((c2) => c2 === input.channel && delivery.channels[c2]?.state === "failed") : open.filter((c2) => delivery.channels[c2]?.state !== "sending");
|
|
469
984
|
if (targets.length === 0)
|
|
470
985
|
return json(400, action === "retry" ? "Nothing to retry" : "Nothing left to post");
|
|
471
|
-
for (const
|
|
472
|
-
delivery.channels[
|
|
986
|
+
for (const c2 of targets)
|
|
987
|
+
delivery.channels[c2] = {
|
|
473
988
|
state: "sending",
|
|
474
989
|
attempts: 0,
|
|
475
990
|
error: null,
|
|
@@ -486,8 +1001,8 @@ function socialPlugin(options = {}) {
|
|
|
486
1001
|
if (!postAt || Number.isNaN(postAt.getTime()) || postAt <= now)
|
|
487
1002
|
return json(400, "postAt must be a time in the future");
|
|
488
1003
|
delivery.postAt = postAt.toISOString();
|
|
489
|
-
for (const
|
|
490
|
-
delivery.channels[
|
|
1004
|
+
for (const c2 of open)
|
|
1005
|
+
delivery.channels[c2] = {
|
|
491
1006
|
state: "scheduled",
|
|
492
1007
|
attempts: 0,
|
|
493
1008
|
error: null,
|
|
@@ -498,9 +1013,9 @@ function socialPlugin(options = {}) {
|
|
|
498
1013
|
}
|
|
499
1014
|
if (action === "cancel") {
|
|
500
1015
|
delivery.postAt = null;
|
|
501
|
-
for (const [
|
|
1016
|
+
for (const [c2, state] of Object.entries(delivery.channels))
|
|
502
1017
|
if (state.state === "scheduled")
|
|
503
|
-
delivery.channels[
|
|
1018
|
+
delivery.channels[c2] = { state: "waiting", attempts: 0 };
|
|
504
1019
|
await save(cms, id, delivery);
|
|
505
1020
|
return { delivery };
|
|
506
1021
|
}
|
|
@@ -522,7 +1037,7 @@ function socialPlugin(options = {}) {
|
|
|
522
1037
|
const parts = [];
|
|
523
1038
|
const ref = sourceOf(form);
|
|
524
1039
|
if (ref) {
|
|
525
|
-
const config2 = cms.config.collections.find((
|
|
1040
|
+
const config2 = cms.config.collections.find((c2) => c2.slug === ref.collection);
|
|
526
1041
|
const source2 = await cms.findById(ref.collection, ref.id, {
|
|
527
1042
|
depth: 0,
|
|
528
1043
|
draft: true,
|
|
@@ -541,6 +1056,7 @@ function socialPlugin(options = {}) {
|
|
|
541
1056
|
const channel = typeof input.channel === "string" ? input.channel : null;
|
|
542
1057
|
const adapter = channel ? channelOf(channel) : void 0;
|
|
543
1058
|
const max = adapter?.maxLength ?? 500;
|
|
1059
|
+
const measure = adapter?.counting === "x" ? xLength : (value) => [...value].length;
|
|
544
1060
|
const where = channel ? `a post on ${channel.slice(0, channel.indexOf(":")) || "social media"}` : "a social media post";
|
|
545
1061
|
try {
|
|
546
1062
|
const result = await ai.generate(
|
|
@@ -548,7 +1064,7 @@ function socialPlugin(options = {}) {
|
|
|
548
1064
|
feature: "social",
|
|
549
1065
|
system: [
|
|
550
1066
|
`You write ${where} that makes people want to read the page it shares.`,
|
|
551
|
-
`At most ${max} characters, plain text, no hashtags unless they fit, no link (it is added`,
|
|
1067
|
+
`At most ${max} characters${adapter?.counting === "x" ? " (an emoji counts as two)" : ""}, plain text, no hashtags unless they fit, no link (it is added`,
|
|
552
1068
|
`separately). Write it in ${ai.languageOf(null)}. Answer with the post only.`
|
|
553
1069
|
].join(" "),
|
|
554
1070
|
prompt: `The page:
|
|
@@ -559,8 +1075,11 @@ ${source.slice(0, 6e3)}`,
|
|
|
559
1075
|
{ user, ...id !== null ? { about: { collection: slug, id } } : {} }
|
|
560
1076
|
);
|
|
561
1077
|
let text = result.text.trim().replace(/^["“]+|["”]+$/g, "");
|
|
562
|
-
if (
|
|
563
|
-
|
|
1078
|
+
if (measure(text) > max) {
|
|
1079
|
+
const chars = [...text];
|
|
1080
|
+
while (chars.length && measure(`${chars.join("").trimEnd()}\u2026`) > max) chars.pop();
|
|
1081
|
+
text = `${chars.join("").trimEnd()}\u2026`;
|
|
1082
|
+
}
|
|
564
1083
|
return { text };
|
|
565
1084
|
} catch (e) {
|
|
566
1085
|
const status = e.status;
|
|
@@ -588,7 +1107,7 @@ ${source.slice(0, 6e3)}`,
|
|
|
588
1107
|
});
|
|
589
1108
|
if (!doc) return json(404, "No such document");
|
|
590
1109
|
const values = options.share ? await options.share({ doc, collection, cms }) : defaults(
|
|
591
|
-
cms.config.collections.find((
|
|
1110
|
+
cms.config.collections.find((c2) => c2.slug === collection),
|
|
592
1111
|
doc
|
|
593
1112
|
);
|
|
594
1113
|
const link = values.link ?? options.url?.({ doc, collection }) ?? null;
|
|
@@ -625,14 +1144,14 @@ ${source.slice(0, 6e3)}`,
|
|
|
625
1144
|
for (const doc of due.docs) await sendDue(cms, doc, now);
|
|
626
1145
|
}
|
|
627
1146
|
};
|
|
628
|
-
const withShare = (
|
|
629
|
-
...
|
|
1147
|
+
const withShare = (c2) => sources.includes(c2.slug) ? {
|
|
1148
|
+
...c2,
|
|
630
1149
|
admin: {
|
|
631
|
-
...
|
|
632
|
-
sidebar: [...
|
|
1150
|
+
...c2.admin,
|
|
1151
|
+
sidebar: [...c2.admin?.sidebar ?? [], { tag: "ecms-social-share" }]
|
|
633
1152
|
}
|
|
634
|
-
} :
|
|
635
|
-
const integrations = channels.map((
|
|
1153
|
+
} : c2;
|
|
1154
|
+
const integrations = channels.map((c2) => c2.integration);
|
|
636
1155
|
return {
|
|
637
1156
|
...config,
|
|
638
1157
|
collections: [...(config.collections ?? []).map(withShare), posts],
|
|
@@ -703,6 +1222,9 @@ function defaults(collection, doc) {
|
|
|
703
1222
|
}
|
|
704
1223
|
export {
|
|
705
1224
|
ChannelError,
|
|
1225
|
+
facebook,
|
|
1226
|
+
line,
|
|
706
1227
|
socialPlugin,
|
|
707
|
-
webhook
|
|
1228
|
+
webhook,
|
|
1229
|
+
x
|
|
708
1230
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@easy-cms/plugin-social",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.39.0",
|
|
4
4
|
"description": "Social posts for Easy CMS: write a post once and send it to several channels (webhooks to Make, n8n or Zapier first), with schedules, retries and a status per channel",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -17,12 +17,13 @@
|
|
|
17
17
|
"dist"
|
|
18
18
|
],
|
|
19
19
|
"peerDependencies": {
|
|
20
|
-
"@easy-cms/core": "^1.
|
|
20
|
+
"@easy-cms/core": "^1.39.0"
|
|
21
21
|
},
|
|
22
22
|
"devDependencies": {
|
|
23
23
|
"happy-dom": "^21.0.4",
|
|
24
|
-
"
|
|
25
|
-
"@easy-cms/
|
|
24
|
+
"simple-icons": "16.36.0",
|
|
25
|
+
"@easy-cms/core": "^1.39.0",
|
|
26
|
+
"@easy-cms/db-sqlite": "^1.39.0"
|
|
26
27
|
},
|
|
27
28
|
"engines": {
|
|
28
29
|
"node": ">=22.12"
|