@easy-cms/plugin-social 1.36.0 → 1.38.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 +30 -17
- package/dist/index.d.ts +11 -1
- package/dist/index.js +398 -4
- package/package.json +4 -4
package/dist/admin.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var x="/social/channels",
|
|
1
|
+
var x="/social/channels",f="/social/post",w="/social/ai",A="/social/share";var C=["value","path","doc","collection","id","uiLocale","readOnly","api"],$={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"}},n=o=>o.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t]);function L(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 k=new WeakMap;function O(o){let t=k.get(o);if(t)return t;let e=o("GET",x).then(s=>s).catch(()=>({channels:[],canPost:!1}));return k.set(o,e),e}var E=new WeakMap;function S(o,t=!1){let e=E.get(o);if(e&&!t)return e;let s=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 E.set(o,s),s}var P=`
|
|
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,13 +18,24 @@ var x="/social/channels",m="/social/post",w="/social/share";var S=["value","path
|
|
|
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
|
-
`,p=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 s=e.target.closest("[data-action]"),
|
|
21
|
+
`,p=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 s=e.target.closest("[data-action]"),r=s?.getAttribute("data-action");r&&s?.tagName!=="SELECT"&&this.onAction(r,s)}),t.addEventListener("change",e=>this.onChange(e.target))}static{for(let t of C)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"?$.th:$.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,O(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>${P}${this.css()}</style>${this.render()}`;if(e===this.html)return;let s=t.activeElement?.getAttribute("data-action");this.html=e,t.innerHTML=e,s&&t.querySelector(`[data-action="${s}"]`)?.focus()}))}onAction(t,e){}onChange(t){}css(){return""}},m=class extends p{render(){let t=typeof this.ctx.value=="string"?this.ctx.value:"",e=this.ctx.doc.delivery??null,s=!!t&&e?.channels?.[t]?.state==="posted";if(this.channels.length===0&&!t)return`<p class="hint">${n(this.t("none"))}</p>`;let r=this.channels.some(i=>i.id===t);return`
|
|
22
22
|
<select data-action="pick" aria-label="${n(this.t("pick"))}" ${this.ctx.readOnly||s?"disabled":""}>
|
|
23
23
|
${t?"":`<option value="">${n(this.t("pick"))}</option>`}
|
|
24
|
-
${!
|
|
25
|
-
${this.channels.map(
|
|
24
|
+
${!r&&t?`<option value="${n(t)}" selected>${n(this.t("gone",{id:t}))}</option>`:""}
|
|
25
|
+
${this.channels.map(i=>`<option value="${n(i.id)}" ${i.id===t?"selected":""}>${n(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}))}},v=class extends p{
|
|
27
|
+
`}css(){return"select { width: 100%; }"}onChange(t){t.getAttribute("data-action")==="pick"&&this.dispatchEvent(new CustomEvent("change",{detail:t.value}))}},v=class extends p{ai={ready:!1,spent:!1};aiAsked=!1;busy=!1;beforeAi=null;notice=null;css(){return`
|
|
28
|
+
.bar { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 0.25rem 0.75rem; }
|
|
29
|
+
.ai { color: var(--accent-ink); font-weight: 600; border-color: transparent; background: transparent; }
|
|
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,S(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
|
+
<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
|
+
${n(this.t(this.busy?"writingAi":this.ai.spent?"spentAi":"writeAi"))}
|
|
34
|
+
</button>`:"";return`
|
|
35
|
+
<div class="bar">${this.count()}${t}</div>
|
|
36
|
+
${this.beforeAi?`<p class="written" role="status">${n(this.t("writtenAi"))} <button type="button" data-action="undo-ai">${n(this.t("undo"))}</button></p>`:""}
|
|
37
|
+
${this.notice?`<p class="error" role="alert">${n(this.notice)}</p>`:""}
|
|
38
|
+
`}async onAction(t){let{api:e,path:s,id:r,doc:i}=this.ctx;if(!e||!s)return;let d=c=>this.dispatchEvent(new CustomEvent("set-field",{detail:{path:s,value:c}}));if(t==="undo-ai"&&this.beforeAi){d(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(s),a=Array.isArray(i.channels)?i.channels:[],l=u?a[Number(u[1])]?.connection:void 0;this.busy=!0,this.notice=null,this.update();try{let c=await e("POST",w,{post:r,doc:{title:i.title,text:i.text,source:i.source??null},...typeof l=="string"?{channel:l}:{}});this.beforeAi??={value:this.ctx.value??null},d(c.text)}catch(c){this.notice=c.message}finally{this.busy=!1,this.ai=await S(e,!0),this.update()}}count(){let t=typeof this.ctx.value=="string"?this.ctx.value:"",e=L(t.trim()),s=Array.isArray(this.ctx.doc.channels)?this.ctx.doc.channels:[],r=/^channels\.(\d+)\.text$/.exec(this.ctx.path??""),h=(r?s.filter((a,l)=>l===Number(r[1])):s.filter(a=>!(typeof a.text=="string"&&a.text.trim()))).map(a=>this.channels.find(l=>l.id===a.connection)).filter(a=>!!a?.maxLength).sort((a,l)=>(a.maxLength??0)-(l.maxLength??0))[0];if(!h)return`<span class="hint">${n(this.t("chars",{n:e}))}</span>`;let u=e>(h.maxLength??Number.POSITIVE_INFINITY);return`<span class="${u?"error":"hint"}">${n(this.t("charsMax",{n:e,max:h.maxLength??0}))}${u?` \xB7 ${n(this.t("over",{channel:h.label}))}`:""}</span>`}},y=class extends p{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`
|
|
28
39
|
.panel { display: flex; flex-direction: column; gap: 0.75rem; }
|
|
29
40
|
ul { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 0.5rem; }
|
|
30
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); }
|
|
@@ -36,16 +47,18 @@ var x="/social/channels",m="/social/post",w="/social/share";var S=["value","path
|
|
|
36
47
|
.schedule { display: flex; gap: 0.4rem; flex-wrap: wrap; }
|
|
37
48
|
.schedule input { flex: 1 1 10rem; }
|
|
38
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; }
|
|
39
|
-
`}check(){let{api:t,id:e}=this.ctx,{image:s=null,source:
|
|
40
|
-
<li class="${
|
|
41
|
-
<span class="name">${n(this.labelOf(
|
|
42
|
-
<span class="state">${n(
|
|
43
|
-
${
|
|
44
|
-
${
|
|
45
|
-
${
|
|
46
|
-
|
|
50
|
+
`}check(){let{api:t,id:e}=this.ctx,{image:s=null,source:r=null}=this.ctx.doc,i=JSON.stringify([e,s,r]);!t||e===null||i===this.checkedFor||(this.checkedFor=i,t("POST",f,{post:e,action:"check",image:s,source:r}).then(d=>{let h=d;this.problems=h.problems??[],this.notes=h.notes??{},this.update()}).catch(()=>{}))}render(){if(this.ctx.id===null)return`<p class="hint">${n(this.t("saveFirst"))}</p>`;this.check();let e=this.delivery(),s=(Array.isArray(this.ctx.doc.channels)?this.ctx.doc.channels:[]).filter(a=>typeof a.connection=="string"&&a.connection),r=a=>e.channels?.[a]??{state:"waiting",attempts:0},i=s.filter(a=>["waiting","scheduled"].includes(r(a.connection).state)),d=s.some(a=>r(a.connection).state==="scheduled"),h=s.map(a=>{let l=a.connection,c=r(l),T=c.state==="sending"&&c.attempts>0&&c.nextAttemptAt?this.t("retrying",{time:this.time(c.nextAttemptAt)}):this.t(c.state);return`
|
|
51
|
+
<li class="${c.state}" data-channel="${n(l)}">
|
|
52
|
+
<span class="name">${n(this.labelOf(l))}</span>
|
|
53
|
+
<span class="state">${n(T)}</span>
|
|
54
|
+
${c.state==="posted"&&c.url?`<a href="${n(c.url)}" target="_blank" rel="noopener">${n(this.t("view"))}</a>`:""}
|
|
55
|
+
${c.error&&c.state!=="posted"?`<p class="error">${n(c.error)}</p>`:""}
|
|
56
|
+
${c.state!=="posted"&&this.notes[l]?.info?`<p class="hint">${n(this.notes[l]?.info??"")}</p>`:""}
|
|
57
|
+
${c.state!=="posted"&&this.notes[l]?.warning?`<p class="warning">${n(this.notes[l]?.warning??"")}</p>`:""}
|
|
58
|
+
${c.state==="failed"&&this.canPost?`<div class="row"><button type="button" data-action="retry" data-channel="${n(l)}" ${this.busy?"disabled":""}>${n(this.t("retry"))}</button></div>`:""}
|
|
59
|
+
</li>`}).join(""),u=this.canPost?i.length===0?"":`
|
|
47
60
|
<div class="row"><button type="button" class="primary" data-action="now" ${this.busy?"disabled":""}>${n(this.t("postNow"))}</button></div>
|
|
48
|
-
${
|
|
61
|
+
${d&&e.postAt?`<p class="hint">${n(this.t("scheduledFor",{time:this.time(e.postAt)}))}</p>
|
|
49
62
|
<div class="row"><button type="button" data-action="cancel" ${this.busy?"disabled":""}>${n(this.t("cancel"))}</button></div>`:`<div class="schedule">
|
|
50
63
|
<input type="datetime-local" data-field="when" aria-label="${n(this.t("when"))}" />
|
|
51
64
|
<button type="button" data-action="schedule" ${this.busy?"disabled":""}>${n(this.t("schedule"))}</button>
|
|
@@ -53,14 +66,14 @@ var x="/social/channels",m="/social/post",w="/social/share";var S=["value","path
|
|
|
53
66
|
<p class="hint">${n(this.t("savedOnly"))}</p>`:`<p class="hint">${n(this.t("noRight"))}</p>`;return`
|
|
54
67
|
<div class="panel">
|
|
55
68
|
${s.length?`<ul>${h}</ul>`:`<p class="hint">${n(this.t("none"))}</p>`}
|
|
56
|
-
${this.problems.map(
|
|
69
|
+
${this.problems.map(a=>`<p class="warning">${n(a)}</p>`).join("")}
|
|
57
70
|
${s.length?u:""}
|
|
58
71
|
${this.notice?`<p class="error" role="alert">${n(this.notice)}</p>`:""}
|
|
59
72
|
</div>
|
|
60
|
-
`}async onAction(t,e){let{api:s,id:
|
|
73
|
+
`}async onAction(t,e){let{api:s,id:r}=this.ctx;if(!s||r===null||this.busy)return;let i={post:r,action:t};if(t==="retry"&&(i.channel=e.getAttribute("data-channel")),t==="schedule"){let d=this.shadowRoot?.querySelector('[data-field="when"]');if(!d?.value){d?.focus();return}i.postAt=new Date(d.value).toISOString()}if(t==="now"){let h=(this.ctx.doc.channels??[]).filter(u=>this.delivery().channels?.[String(u.connection)]?.state!=="posted").length;if(!window.confirm(this.t("confirmNow",{n:h})))return}this.busy=!0,this.notice=null,this.update();try{let d=await s("POST",f,i);this.live=d.delivery,this.watch()}catch(d){this.notice=d.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))}},b=class extends p{busy=!1;notice=null;render(){let t=this.ctx.id!==null;return`
|
|
61
74
|
<div class="row">
|
|
62
75
|
<button type="button" data-action="share" ${!t||this.busy?"disabled":""}>${n(this.t(this.busy?"sharing":"share"))}</button>
|
|
63
76
|
</div>
|
|
64
77
|
${t?"":`<p class="hint">${n(this.t("shareSave"))}</p>`}
|
|
65
78
|
${this.notice?`<p class="error" role="alert">${n(this.notice)}</p>`:""}
|
|
66
|
-
`}async onAction(t){let{api:e,id:s,collection:
|
|
79
|
+
`}async onAction(t){let{api:e,id:s,collection:r}=this.ctx;if(!(t!=="share"||!e||s===null||this.busy)){this.busy=!0,this.notice=null,this.update();try{let i=await e("POST",A,{collection:r,id:s});this.dispatchEvent(new CustomEvent("navigate",{detail:i.path}))}catch(i){this.notice=i.message}finally{this.busy=!1,this.update()}}}},g=(o,t)=>{customElements.get(o)||customElements.define(o,t)};g("ecms-social-channel",m);g("ecms-social-count",v);g("ecms-social-panel",y);g("ecms-social-share",b);
|
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: {
|
|
@@ -26,6 +28,14 @@ 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
|
+
/**
|
|
32
|
+
* What to say before posting, beside the channel in the panel, e.g. how many people a LINE
|
|
33
|
+
* broadcast reaches and the month's quota; `warning` when it may cost or fail.
|
|
34
|
+
*/
|
|
35
|
+
readonly preview?: (values: Readonly<Record<string, string>>) => Promise<{
|
|
36
|
+
readonly info?: string;
|
|
37
|
+
readonly warning?: string;
|
|
38
|
+
}>;
|
|
29
39
|
/** Posts; returns the post's URL when the channel says. Throws `ChannelError` with the reason. */
|
|
30
40
|
readonly send: (values: Readonly<Record<string, string>>, message: SocialMessage) => Promise<{
|
|
31
41
|
url?: string | null;
|
|
@@ -63,7 +73,7 @@ interface SocialPluginOptions {
|
|
|
63
73
|
doc: Doc;
|
|
64
74
|
collection: string;
|
|
65
75
|
}) => string | null | undefined;
|
|
66
|
-
/** Where posts go. Default: the webhook (Make, n8n, Zapier). */
|
|
76
|
+
/** Where posts go. Default: the webhook (Make, n8n, Zapier), Facebook Pages and LINE OA. */
|
|
67
77
|
readonly channels?: readonly SocialChannel[];
|
|
68
78
|
/** Slug of the social posts collection. Default `social-posts`. */
|
|
69
79
|
readonly slug?: string;
|
package/dist/index.js
CHANGED
|
@@ -13,17 +13,301 @@ import {
|
|
|
13
13
|
definePlugin
|
|
14
14
|
} from "@easy-cms/core";
|
|
15
15
|
|
|
16
|
+
// src/facebook.ts
|
|
17
|
+
var version = () => process.env.FACEBOOK_GRAPH_VERSION ?? "v26.0";
|
|
18
|
+
var graph = () => `${(process.env.FACEBOOK_GRAPH_URL ?? "https://graph.facebook.com").replace(/\/+$/, "")}/${version()}`;
|
|
19
|
+
var app = () => {
|
|
20
|
+
const id = process.env.META_APP_ID;
|
|
21
|
+
const secret = process.env.META_APP_SECRET;
|
|
22
|
+
if (!id || !secret)
|
|
23
|
+
throw new Error("Set META_APP_ID and META_APP_SECRET (your Meta app) to connect Facebook Pages");
|
|
24
|
+
return { id, secret };
|
|
25
|
+
};
|
|
26
|
+
async function call(path, init) {
|
|
27
|
+
const query = new URLSearchParams(init.params);
|
|
28
|
+
const method = init.method ?? "GET";
|
|
29
|
+
let response;
|
|
30
|
+
try {
|
|
31
|
+
response = await fetch(method === "GET" ? `${graph()}${path}?${query}` : `${graph()}${path}`, {
|
|
32
|
+
method,
|
|
33
|
+
...method === "GET" ? {} : { body: query, headers: { "content-type": "application/x-www-form-urlencoded" } },
|
|
34
|
+
signal: AbortSignal.timeout(3e4)
|
|
35
|
+
});
|
|
36
|
+
} catch (error) {
|
|
37
|
+
throw new ChannelError(`Facebook could not be reached: ${error.message}`);
|
|
38
|
+
}
|
|
39
|
+
const answer = await response.json().catch(() => ({}));
|
|
40
|
+
if (!response.ok || answer.error) {
|
|
41
|
+
const code = answer.error?.code;
|
|
42
|
+
const message = `Facebook: ${answer.error?.message ?? `HTTP ${response.status}`}`;
|
|
43
|
+
const retry = response.status >= 500 || [1, 2, 4, 17, 32, 341, 613].includes(code ?? -1);
|
|
44
|
+
throw new ChannelError(message, !retry);
|
|
45
|
+
}
|
|
46
|
+
return answer;
|
|
47
|
+
}
|
|
48
|
+
var facebook = {
|
|
49
|
+
integration: {
|
|
50
|
+
id: "facebook-page",
|
|
51
|
+
label: "Facebook Page",
|
|
52
|
+
category: "social",
|
|
53
|
+
description: {
|
|
54
|
+
en: "Posts to Facebook Pages you manage. Needs a Meta app: set META_APP_ID and META_APP_SECRET.",
|
|
55
|
+
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"
|
|
56
|
+
},
|
|
57
|
+
docs: "https://easycms.dev/docs/social#facebook-page",
|
|
58
|
+
plugin: "@easy-cms/plugin-social",
|
|
59
|
+
kind: "oauth",
|
|
60
|
+
oauth: {
|
|
61
|
+
authorizeUrl: ({ redirectUri, state }) => {
|
|
62
|
+
const { id } = app();
|
|
63
|
+
const dialog = (process.env.FACEBOOK_DIALOG_URL ?? "https://www.facebook.com").replace(
|
|
64
|
+
/\/+$/,
|
|
65
|
+
""
|
|
66
|
+
);
|
|
67
|
+
const query = new URLSearchParams({
|
|
68
|
+
client_id: id,
|
|
69
|
+
redirect_uri: redirectUri,
|
|
70
|
+
state,
|
|
71
|
+
scope: "pages_show_list,pages_manage_posts,pages_read_engagement",
|
|
72
|
+
response_type: "code"
|
|
73
|
+
});
|
|
74
|
+
return `${dialog}/${version()}/dialog/oauth?${query}`;
|
|
75
|
+
},
|
|
76
|
+
// The code → a user token → a long-lived one → the Pages it manages, each with a Page token
|
|
77
|
+
// that doesn't expire (until the user takes it back).
|
|
78
|
+
exchange: async ({ code, redirectUri }) => {
|
|
79
|
+
const { id, secret } = app();
|
|
80
|
+
const short = await call("/oauth/access_token", {
|
|
81
|
+
params: { client_id: id, client_secret: secret, redirect_uri: redirectUri, code }
|
|
82
|
+
});
|
|
83
|
+
const long = await call("/oauth/access_token", {
|
|
84
|
+
params: {
|
|
85
|
+
grant_type: "fb_exchange_token",
|
|
86
|
+
client_id: id,
|
|
87
|
+
client_secret: secret,
|
|
88
|
+
fb_exchange_token: String(short.access_token ?? "")
|
|
89
|
+
}
|
|
90
|
+
});
|
|
91
|
+
const pages = await call("/me/accounts", {
|
|
92
|
+
params: {
|
|
93
|
+
fields: "id,name,access_token",
|
|
94
|
+
limit: "100",
|
|
95
|
+
access_token: String(long.access_token ?? "")
|
|
96
|
+
}
|
|
97
|
+
});
|
|
98
|
+
const list = Array.isArray(pages.data) ? pages.data : [];
|
|
99
|
+
if (list.length === 0)
|
|
100
|
+
throw new Error("This Facebook account manages no Page, or none was allowed");
|
|
101
|
+
return {
|
|
102
|
+
accounts: list.map((page) => ({
|
|
103
|
+
id: page.id,
|
|
104
|
+
name: page.name,
|
|
105
|
+
values: { pageId: page.id, token: page.access_token }
|
|
106
|
+
}))
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
},
|
|
110
|
+
// Checks the Page token without posting.
|
|
111
|
+
async test(values) {
|
|
112
|
+
try {
|
|
113
|
+
const me = await call("/me", {
|
|
114
|
+
params: { fields: "name", access_token: values.token ?? "" }
|
|
115
|
+
});
|
|
116
|
+
return { ok: true, account: String(me.name ?? values.pageId ?? "") };
|
|
117
|
+
} catch (error) {
|
|
118
|
+
return { ok: false, message: error.message };
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
},
|
|
122
|
+
async send(values, message) {
|
|
123
|
+
const token = values.token ?? "";
|
|
124
|
+
const page = values.pageId ?? "";
|
|
125
|
+
if (!token || !page) throw new ChannelError("The Page is not connected", true);
|
|
126
|
+
const result = message.image ? await call(`/${page}/photos`, {
|
|
127
|
+
method: "POST",
|
|
128
|
+
params: {
|
|
129
|
+
url: message.image.url,
|
|
130
|
+
caption: message.link ? `${message.text}
|
|
131
|
+
|
|
132
|
+
${message.link}` : message.text,
|
|
133
|
+
access_token: token
|
|
134
|
+
}
|
|
135
|
+
}) : await call(`/${page}/feed`, {
|
|
136
|
+
method: "POST",
|
|
137
|
+
params: {
|
|
138
|
+
message: message.text,
|
|
139
|
+
...message.link ? { link: message.link } : {},
|
|
140
|
+
access_token: token
|
|
141
|
+
}
|
|
142
|
+
});
|
|
143
|
+
const id = String(result.post_id ?? result.id ?? "");
|
|
144
|
+
return { url: id ? `https://www.facebook.com/${id}` : null };
|
|
145
|
+
}
|
|
146
|
+
};
|
|
147
|
+
|
|
16
148
|
// src/info.ts
|
|
17
149
|
var INFO = {
|
|
18
150
|
name: "@easy-cms/plugin-social",
|
|
19
151
|
// The plugin API it is written for (`PLUGIN_API_VERSION` of @easy-cms/core).
|
|
20
152
|
apiVersion: 1,
|
|
21
|
-
...true ? { version: "1.
|
|
153
|
+
...true ? { version: "1.38.0" } : {}
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
// src/line.ts
|
|
157
|
+
var api = () => (process.env.LINE_API_URL ?? "https://api.line.me").replace(/\/+$/, "");
|
|
158
|
+
var MAX_TEXT = 300;
|
|
159
|
+
async function call2(path, token, body) {
|
|
160
|
+
if (!token) throw new ChannelError("No channel access token", true);
|
|
161
|
+
let response;
|
|
162
|
+
try {
|
|
163
|
+
response = await fetch(`${api()}${path}`, {
|
|
164
|
+
method: body === void 0 ? "GET" : "POST",
|
|
165
|
+
headers: {
|
|
166
|
+
authorization: `Bearer ${token}`,
|
|
167
|
+
...body === void 0 ? {} : { "content-type": "application/json" }
|
|
168
|
+
},
|
|
169
|
+
...body === void 0 ? {} : { body: JSON.stringify(body) },
|
|
170
|
+
signal: AbortSignal.timeout(3e4)
|
|
171
|
+
});
|
|
172
|
+
} catch (error) {
|
|
173
|
+
throw new ChannelError(`LINE could not be reached: ${error.message}`);
|
|
174
|
+
}
|
|
175
|
+
const answer = await response.json().catch(() => ({}));
|
|
176
|
+
if (!response.ok) {
|
|
177
|
+
const details = Array.isArray(answer.details) ? ` (${answer.details.map((d) => d.message).join("; ")})` : "";
|
|
178
|
+
throw new ChannelError(
|
|
179
|
+
`LINE: ${String(answer.message ?? `HTTP ${response.status}`)}${details}`,
|
|
180
|
+
response.status !== 429 && response.status < 500
|
|
181
|
+
);
|
|
182
|
+
}
|
|
183
|
+
return answer;
|
|
184
|
+
}
|
|
185
|
+
var cut = (text, max) => {
|
|
186
|
+
const chars = [...text];
|
|
187
|
+
return chars.length > max ? `${chars.slice(0, max - 1).join("").trimEnd()}\u2026` : text;
|
|
188
|
+
};
|
|
189
|
+
function flexMessage(message, readMore) {
|
|
190
|
+
if (message.image && !message.image.url.startsWith("https://"))
|
|
191
|
+
throw new ChannelError("LINE shows images only from https addresses", true);
|
|
192
|
+
const title = message.title.trim();
|
|
193
|
+
const text = cut(message.text.trim(), MAX_TEXT);
|
|
194
|
+
return {
|
|
195
|
+
type: "flex",
|
|
196
|
+
altText: cut([title, text].filter(Boolean).join(": "), 400),
|
|
197
|
+
contents: {
|
|
198
|
+
type: "bubble",
|
|
199
|
+
...message.image ? {
|
|
200
|
+
hero: {
|
|
201
|
+
type: "image",
|
|
202
|
+
url: message.image.url,
|
|
203
|
+
size: "full",
|
|
204
|
+
aspectRatio: "20:13",
|
|
205
|
+
aspectMode: "cover",
|
|
206
|
+
...message.link ? { action: { type: "uri", uri: message.link } } : {}
|
|
207
|
+
}
|
|
208
|
+
} : {},
|
|
209
|
+
body: {
|
|
210
|
+
type: "box",
|
|
211
|
+
layout: "vertical",
|
|
212
|
+
spacing: "md",
|
|
213
|
+
contents: [
|
|
214
|
+
...title ? [{ type: "text", text: cut(title, 120), weight: "bold", size: "lg", wrap: true }] : [],
|
|
215
|
+
{ type: "text", text, size: "sm", color: "#555555", wrap: true }
|
|
216
|
+
]
|
|
217
|
+
},
|
|
218
|
+
...message.link ? {
|
|
219
|
+
footer: {
|
|
220
|
+
type: "box",
|
|
221
|
+
layout: "vertical",
|
|
222
|
+
contents: [
|
|
223
|
+
{
|
|
224
|
+
type: "button",
|
|
225
|
+
style: "primary",
|
|
226
|
+
action: { type: "uri", label: readMore, uri: message.link }
|
|
227
|
+
}
|
|
228
|
+
]
|
|
229
|
+
}
|
|
230
|
+
} : {}
|
|
231
|
+
}
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
var line = {
|
|
235
|
+
maxLength: MAX_TEXT,
|
|
236
|
+
integration: {
|
|
237
|
+
id: "line-oa",
|
|
238
|
+
label: "LINE OA",
|
|
239
|
+
category: "social",
|
|
240
|
+
description: {
|
|
241
|
+
en: "Broadcasts each post as a card to your LINE Official Account\u2019s followers",
|
|
242
|
+
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"
|
|
243
|
+
},
|
|
244
|
+
docs: "https://easycms.dev/docs/social#line-oa",
|
|
245
|
+
plugin: "@easy-cms/plugin-social",
|
|
246
|
+
kind: "fields",
|
|
247
|
+
fields: [
|
|
248
|
+
{
|
|
249
|
+
name: "token",
|
|
250
|
+
label: { en: "Channel access token", th: "Channel access token" },
|
|
251
|
+
description: {
|
|
252
|
+
en: "LINE Developers \u2192 your Messaging API channel \u2192 Channel access token (long-lived).",
|
|
253
|
+
th: "LINE Developers \u2192 Messaging API channel \u0E02\u0E2D\u0E07\u0E04\u0E38\u0E13 \u2192 Channel access token (long-lived)"
|
|
254
|
+
},
|
|
255
|
+
secret: true,
|
|
256
|
+
required: true
|
|
257
|
+
},
|
|
258
|
+
{
|
|
259
|
+
name: "readMore",
|
|
260
|
+
label: { en: "Button text", th: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E1A\u0E19\u0E1B\u0E38\u0E48\u0E21" },
|
|
261
|
+
placeholder: "Read more",
|
|
262
|
+
description: { en: 'Empty: "Read more".', th: '\u0E16\u0E49\u0E32\u0E27\u0E48\u0E32\u0E07: "Read more"' }
|
|
263
|
+
}
|
|
264
|
+
],
|
|
265
|
+
env: { token: "LINE_CHANNEL_ACCESS_TOKEN" },
|
|
266
|
+
async test(values) {
|
|
267
|
+
try {
|
|
268
|
+
const bot = await call2("/v2/bot/info", values.token ?? "");
|
|
269
|
+
return { ok: true, account: [bot.displayName, bot.basicId].filter(Boolean).join(" ") };
|
|
270
|
+
} catch (error) {
|
|
271
|
+
return { ok: false, message: error.message };
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
},
|
|
275
|
+
// Followers (yesterday's count, when LINE has it) and this month's message quota.
|
|
276
|
+
async preview(values) {
|
|
277
|
+
const token = values.token ?? "";
|
|
278
|
+
const yesterday = new Date(Date.now() - 864e5).toISOString().slice(0, 10).replace(/-/g, "");
|
|
279
|
+
const [followers, quota, used] = await Promise.all([
|
|
280
|
+
call2(`/v2/bot/insight/followers?date=${yesterday}`, token).catch(() => null),
|
|
281
|
+
call2("/v2/bot/message/quota", token).catch(() => null),
|
|
282
|
+
call2("/v2/bot/message/quota/consumption", token).catch(() => null)
|
|
283
|
+
]);
|
|
284
|
+
const reach = followers?.status === "ready" ? Number(followers.targetedReaches ?? followers.followers) : null;
|
|
285
|
+
const limit = quota?.type === "limited" ? Number(quota.value) : null;
|
|
286
|
+
const spent = used ? Number(used.totalUsage ?? 0) : null;
|
|
287
|
+
const parts = [
|
|
288
|
+
reach !== null ? `Reaches about ${reach.toLocaleString("en")} followers` : null,
|
|
289
|
+
limit !== null && spent !== null ? `messages this month: ${spent.toLocaleString("en")} / ${limit.toLocaleString("en")}` : null
|
|
290
|
+
].filter(Boolean);
|
|
291
|
+
const over = reach !== null && limit !== null && spent !== null && spent + reach > limit;
|
|
292
|
+
return {
|
|
293
|
+
...parts.length ? { info: parts.join(" \xB7 ") } : {},
|
|
294
|
+
...over ? {
|
|
295
|
+
warning: "This broadcast goes over the month\u2019s free messages: LINE charges for the rest, or refuses them"
|
|
296
|
+
} : {}
|
|
297
|
+
};
|
|
298
|
+
},
|
|
299
|
+
async send(values, message) {
|
|
300
|
+
await call2("/v2/bot/message/broadcast", values.token ?? "", {
|
|
301
|
+
messages: [flexMessage(message, values.readMore?.trim() || "Read more")]
|
|
302
|
+
});
|
|
303
|
+
return { url: null };
|
|
304
|
+
}
|
|
22
305
|
};
|
|
23
306
|
|
|
24
307
|
// src/shared.ts
|
|
25
308
|
var CHANNELS_PATH = "/social/channels";
|
|
26
309
|
var ACTION_PATH = "/social/post";
|
|
310
|
+
var AI_PATH = "/social/ai";
|
|
27
311
|
var SHARE_PATH = "/social/share";
|
|
28
312
|
|
|
29
313
|
// src/webhook.ts
|
|
@@ -112,7 +396,7 @@ var nobody = () => false;
|
|
|
112
396
|
var later = (from, ms) => new Date(from.getTime() + ms).toISOString();
|
|
113
397
|
var json = (status, message) => Response.json({ errors: [{ message }] }, { status });
|
|
114
398
|
function socialPlugin(options = {}) {
|
|
115
|
-
const channels = options.channels ?? [webhook];
|
|
399
|
+
const channels = options.channels ?? [webhook, facebook, line];
|
|
116
400
|
const slug = options.slug ?? "social-posts";
|
|
117
401
|
const sources = options.collections ?? [];
|
|
118
402
|
return definePlugin((config) => {
|
|
@@ -373,6 +657,7 @@ function socialPlugin(options = {}) {
|
|
|
373
657
|
const result = await channel.send(conn.values, {
|
|
374
658
|
post: id,
|
|
375
659
|
channel: connection,
|
|
660
|
+
title: String(doc.title ?? ""),
|
|
376
661
|
text: String(row.text || doc.text || ""),
|
|
377
662
|
link: typeof doc.link === "string" && doc.link ? doc.link : null,
|
|
378
663
|
image,
|
|
@@ -446,7 +731,17 @@ function socialPlugin(options = {}) {
|
|
|
446
731
|
const ref = sourceOf(doc2);
|
|
447
732
|
if (ref && !await isLive(cms, ref))
|
|
448
733
|
problems.push("The source isn\u2019t published yet: its link may not open");
|
|
449
|
-
|
|
734
|
+
const notes = {};
|
|
735
|
+
for (const row of rowsOf(saved)) {
|
|
736
|
+
const connection = row.connection;
|
|
737
|
+
const channel = channelOf(connection);
|
|
738
|
+
if (!channel?.preview) continue;
|
|
739
|
+
const conn = await cms.integrations.get(channel.integration.id, {
|
|
740
|
+
name: nameOf(connection)
|
|
741
|
+
});
|
|
742
|
+
if (conn) notes[connection] = await channel.preview(conn.values).catch(() => ({}));
|
|
743
|
+
}
|
|
744
|
+
return { problems, notes };
|
|
450
745
|
}
|
|
451
746
|
if (!await mayPost(cms, user, id)) return json(403, "You may not post this");
|
|
452
747
|
const doc = await cms.findById(slug, id, { depth: 0 });
|
|
@@ -506,6 +801,67 @@ function socialPlugin(options = {}) {
|
|
|
506
801
|
return json(400, "action must be now, schedule, cancel or retry");
|
|
507
802
|
}
|
|
508
803
|
};
|
|
804
|
+
const aiEndpoint = {
|
|
805
|
+
path: AI_PATH,
|
|
806
|
+
method: "post",
|
|
807
|
+
handler: async ({ json: body, user, cms }) => {
|
|
808
|
+
if (!user) return json(401, "Log in to write with AI");
|
|
809
|
+
const ai = cms.ai;
|
|
810
|
+
if (!ai) return json(404, "No AI plugin");
|
|
811
|
+
const input = await body();
|
|
812
|
+
const id = typeof input.post === "string" || typeof input.post === "number" ? input.post : null;
|
|
813
|
+
const allowed = id !== null ? (await cms.documentPermissions(slug, String(id), user)).update : await cms.roles.allows(user, { collection: slug }, "create") !== false;
|
|
814
|
+
if (!allowed) return json(403, "You may not change this post");
|
|
815
|
+
const form = typeof input.doc === "object" && input.doc !== null ? input.doc : {};
|
|
816
|
+
const parts = [];
|
|
817
|
+
const ref = sourceOf(form);
|
|
818
|
+
if (ref) {
|
|
819
|
+
const config2 = cms.config.collections.find((c) => c.slug === ref.collection);
|
|
820
|
+
const source2 = await cms.findById(ref.collection, ref.id, {
|
|
821
|
+
depth: 0,
|
|
822
|
+
draft: true,
|
|
823
|
+
user,
|
|
824
|
+
overrideAccess: false
|
|
825
|
+
});
|
|
826
|
+
if (source2 && config2) parts.push(contentText(config2, source2));
|
|
827
|
+
}
|
|
828
|
+
if (parts.length === 0) {
|
|
829
|
+
for (const key of ["title", "text"])
|
|
830
|
+
if (typeof form[key] === "string" && form[key].trim())
|
|
831
|
+
parts.push(form[key]);
|
|
832
|
+
}
|
|
833
|
+
const source = parts.join("\n\n").trim();
|
|
834
|
+
if (!source) return json(400, "Nothing to write from yet: share a document or add a title");
|
|
835
|
+
const channel = typeof input.channel === "string" ? input.channel : null;
|
|
836
|
+
const adapter = channel ? channelOf(channel) : void 0;
|
|
837
|
+
const max = adapter?.maxLength ?? 500;
|
|
838
|
+
const where = channel ? `a post on ${channel.slice(0, channel.indexOf(":")) || "social media"}` : "a social media post";
|
|
839
|
+
try {
|
|
840
|
+
const result = await ai.generate(
|
|
841
|
+
{
|
|
842
|
+
feature: "social",
|
|
843
|
+
system: [
|
|
844
|
+
`You write ${where} that makes people want to read the page it shares.`,
|
|
845
|
+
`At most ${max} characters, plain text, no hashtags unless they fit, no link (it is added`,
|
|
846
|
+
`separately). Write it in ${ai.languageOf(null)}. Answer with the post only.`
|
|
847
|
+
].join(" "),
|
|
848
|
+
prompt: `The page:
|
|
849
|
+
|
|
850
|
+
${source.slice(0, 6e3)}`,
|
|
851
|
+
maxTokens: 400
|
|
852
|
+
},
|
|
853
|
+
{ user, ...id !== null ? { about: { collection: slug, id } } : {} }
|
|
854
|
+
);
|
|
855
|
+
let text = result.text.trim().replace(/^["“]+|["”]+$/g, "");
|
|
856
|
+
if ([...text].length > max)
|
|
857
|
+
text = [...text].slice(0, max - 1).join("").trimEnd() + "\u2026";
|
|
858
|
+
return { text };
|
|
859
|
+
} catch (e) {
|
|
860
|
+
const status = e.status;
|
|
861
|
+
return json(typeof status === "number" ? status : 400, e.message);
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
};
|
|
509
865
|
const shareEndpoint = {
|
|
510
866
|
path: SHARE_PATH,
|
|
511
867
|
method: "post",
|
|
@@ -575,7 +931,25 @@ function socialPlugin(options = {}) {
|
|
|
575
931
|
...config,
|
|
576
932
|
collections: [...(config.collections ?? []).map(withShare), posts],
|
|
577
933
|
integrations: [...config.integrations ?? [], ...integrations],
|
|
578
|
-
endpoints: [
|
|
934
|
+
endpoints: [
|
|
935
|
+
...config.endpoints ?? [],
|
|
936
|
+
channelsEndpoint,
|
|
937
|
+
actionEndpoint,
|
|
938
|
+
shareEndpoint,
|
|
939
|
+
aiEndpoint
|
|
940
|
+
],
|
|
941
|
+
// Used only with an AI plugin (`ai` in the config): Write with AI on a post's text.
|
|
942
|
+
aiFeatures: [
|
|
943
|
+
...config.aiFeatures ?? [],
|
|
944
|
+
{
|
|
945
|
+
id: "social",
|
|
946
|
+
label: { en: "Social posts", th: "\u0E42\u0E1E\u0E2A\u0E15\u0E4C\u0E42\u0E0B\u0E40\u0E0A\u0E35\u0E22\u0E25" },
|
|
947
|
+
description: {
|
|
948
|
+
en: "Writes a social post from the document it shares",
|
|
949
|
+
th: "\u0E40\u0E02\u0E35\u0E22\u0E19\u0E42\u0E1E\u0E2A\u0E15\u0E4C\u0E42\u0E0B\u0E40\u0E0A\u0E35\u0E22\u0E25\u0E08\u0E32\u0E01\u0E40\u0E2D\u0E01\u0E2A\u0E32\u0E23\u0E17\u0E35\u0E48\u0E41\u0E0A\u0E23\u0E4C"
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
],
|
|
579
953
|
jobs: [...config.jobs ?? [], job],
|
|
580
954
|
events: [.../* @__PURE__ */ new Set([...config.events ?? [], "social.posted", "social.failed"])],
|
|
581
955
|
admin: {
|
|
@@ -585,6 +959,26 @@ function socialPlugin(options = {}) {
|
|
|
585
959
|
};
|
|
586
960
|
}, INFO);
|
|
587
961
|
}
|
|
962
|
+
function contentText(collection, doc) {
|
|
963
|
+
const parts = [];
|
|
964
|
+
const titleField = collection.useAsTitle;
|
|
965
|
+
if (titleField && typeof doc[titleField] === "string") parts.push(doc[titleField]);
|
|
966
|
+
const words = (node) => {
|
|
967
|
+
if (!node || typeof node !== "object") return "";
|
|
968
|
+
const n = node;
|
|
969
|
+
const own = typeof n.text === "string" ? n.text : "";
|
|
970
|
+
const kids = Array.isArray(n.content) ? n.content.map(words).join(n.text === void 0 ? " " : "") : "";
|
|
971
|
+
return `${own}${kids}`;
|
|
972
|
+
};
|
|
973
|
+
for (const field of collection.fields) {
|
|
974
|
+
if (!("name" in field) || field.name === titleField) continue;
|
|
975
|
+
const value = doc[field.name];
|
|
976
|
+
if ((field.type === "text" || field.type === "textarea") && typeof value === "string")
|
|
977
|
+
parts.push(value);
|
|
978
|
+
else if (field.type === "richText") parts.push(words(value).replace(/\s+/g, " "));
|
|
979
|
+
}
|
|
980
|
+
return parts.map((p) => p.trim()).filter(Boolean).join("\n\n");
|
|
981
|
+
}
|
|
588
982
|
function defaults(collection, doc) {
|
|
589
983
|
const fields = collection?.fields ?? [];
|
|
590
984
|
const titleField = collection?.useAsTitle;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@easy-cms/plugin-social",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.38.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,12 @@
|
|
|
17
17
|
"dist"
|
|
18
18
|
],
|
|
19
19
|
"peerDependencies": {
|
|
20
|
-
"@easy-cms/core": "^1.
|
|
20
|
+
"@easy-cms/core": "^1.38.0"
|
|
21
21
|
},
|
|
22
22
|
"devDependencies": {
|
|
23
23
|
"happy-dom": "^21.0.4",
|
|
24
|
-
"@easy-cms/core": "^1.
|
|
25
|
-
"@easy-cms/db-sqlite": "^1.
|
|
24
|
+
"@easy-cms/core": "^1.38.0",
|
|
25
|
+
"@easy-cms/db-sqlite": "^1.38.0"
|
|
26
26
|
},
|
|
27
27
|
"engines": {
|
|
28
28
|
"node": ">=22.12"
|