domma-cms 1.79.0 → 1.81.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/CHANGELOG.md +24 -0
- package/admin/css/site-settings.css +1 -1
- package/admin/js/lib/site-settings-arrange.js +3 -3
- package/admin/js/templates/docs/usage-site-settings.html +29 -3
- package/admin/js/templates/settings.html +94 -4
- package/admin/js/views/settings.js +3 -3
- package/docs/DommaFeatures.md +51 -2
- package/docs/plans/2026-11-19-brand-kit-design.md +1 -1
- package/docs/plugin-development.md +6 -0
- package/package.json +1 -1
- package/plugins/_lib/admin/mail/attach-arrange.js +132 -5
- package/plugins/_lib/admin/mail/body-menu.js +1 -1
- package/plugins/_lib/admin/mail/cms-attach.js +79 -7
- package/plugins/_lib/admin/mail/cms-host.js +1 -1
- package/plugins/_lib/admin/mail/compose-window.js +15 -5
- package/plugins/_lib/admin/mail/contacts.js +1 -1
- package/plugins/_lib/admin/mail/diagnostics-section.js +1 -1
- package/plugins/_lib/admin/mail/drag-drop.js +33 -1
- package/plugins/_lib/admin/mail/folder-tree.js +1 -1
- package/plugins/_lib/admin/mail/font-controls.js +1 -1
- package/plugins/_lib/admin/mail/fonts.js +1 -1
- package/plugins/_lib/admin/mail/host-context.js +1 -1
- package/plugins/_lib/admin/mail/identity.js +1 -1
- package/plugins/_lib/admin/mail/image-senders-section.js +1 -1
- package/plugins/_lib/admin/mail/keyboard.js +1 -1
- package/plugins/_lib/admin/mail/mail.html +1 -1
- package/plugins/_lib/admin/mail/message-actions.js +1 -1
- package/plugins/_lib/admin/mail/oauth-panel.js +1 -1
- package/plugins/_lib/admin/mail/panes.js +1 -1
- package/plugins/_lib/admin/mail/reader-kit.js +1 -1
- package/plugins/_lib/admin/mail/reader-runtime.js +119 -63
- package/plugins/_lib/admin/mail/reader-view.js +1 -1
- package/plugins/_lib/admin/mail/resizable.js +1 -1
- package/plugins/_lib/admin/mail/restore-spam.js +1 -1
- package/plugins/_lib/admin/mail/rules.js +1 -1
- package/plugins/_lib/admin/mail/scheduling.js +1 -1
- package/plugins/_lib/admin/mail/section-kit.js +1 -1
- package/plugins/_lib/admin/mail/security-note.js +1 -1
- package/plugins/_lib/admin/mail/settings-section.js +6 -3
- package/plugins/_lib/admin/mail/templates.js +1 -1
- package/plugins/_lib/admin/mail/threads.js +1 -1
- package/plugins/_lib/admin/mail/vacation.js +1 -1
- package/plugins/_lib/admin/mail/when-closed.js +1 -1
- package/plugins/_lib/admin/ui/dates.js +1 -1
- package/plugins/_lib/admin/ui/resizable.js +1 -1
- package/plugins/_lib/admin/ui/rich-field.js +1 -1
- package/plugins/_lib/domma-mail.lock.json +85 -85
- package/plugins/_lib/mail/accountFileStore.js +1 -1
- package/plugins/_lib/mail/accountRepository.js +41 -2
- package/plugins/_lib/mail/accountRoutes.js +1 -1
- package/plugins/_lib/mail/bodyTokenProvider.js +1 -1
- package/plugins/_lib/mail/bodyTokens.js +1 -1
- package/plugins/_lib/mail/compose.js +1 -1
- package/plugins/_lib/mail/defaults.js +1 -1
- package/plugins/_lib/mail/envelope.js +1 -1
- package/plugins/_lib/mail/folderActions.js +1 -1
- package/plugins/_lib/mail/folderRuntime.js +1 -1
- package/plugins/_lib/mail/folders.js +1 -1
- package/plugins/_lib/mail/imapPoolRuntime.js +1 -1
- package/plugins/_lib/mail/mbox.js +1 -1
- package/plugins/_lib/mail/message-action.js +1 -1
- package/plugins/_lib/mail/messageSecurity.js +1 -1
- package/plugins/_lib/mail/messageSecurityProvider.js +1 -1
- package/plugins/_lib/mail/networkAddresses.js +1 -1
- package/plugins/_lib/mail/networkPolicy.js +1 -1
- package/plugins/_lib/mail/oauthAccounts.js +1 -1
- package/plugins/_lib/mail/oauthRouteRuntime.js +1 -1
- package/plugins/_lib/mail/oauthRuntime.js +1 -1
- package/plugins/_lib/mail/pollSchedule.js +1 -1
- package/plugins/_lib/mail/poller.js +1 -1
- package/plugins/_lib/mail/pollerRuntime.js +1 -1
- package/plugins/_lib/mail/priority.js +1 -1
- package/plugins/_lib/mail/publicMailbox.js +1 -1
- package/plugins/_lib/mail/readRuntime.js +1 -1
- package/plugins/_lib/mail/render.js +1 -1
- package/plugins/_lib/mail/ruleRunner.js +1 -1
- package/plugins/_lib/mail/schedulerRuntime.js +1 -1
- package/plugins/_lib/mail/secretProvider.js +1 -1
- package/plugins/_lib/mail/secretbox.js +1 -1
- package/plugins/_lib/mail/senderAuth.js +1 -1
- package/plugins/_lib/mail/sieve.js +1 -1
- package/plugins/_lib/mail/smtpService.js +1 -1
- package/plugins/_lib/mail/snoozeRuntime.js +1 -1
- package/plugins/_lib/mail/store.js +1 -1
- package/plugins/_lib/mail/subscriptions.js +1 -1
- package/plugins/_lib/mail/syncPlan.js +1 -1
- package/plugins/_lib/mail/syncRuntime.js +1 -1
- package/plugins/_lib/mail/syncSelection.js +1 -1
- package/plugins/_lib/mail/unreadBadge.js +1 -1
- package/plugins/_lib/mail/unsubscribe.js +1 -1
- package/plugins/_lib/mail/vacationRuntime.js +1 -1
- package/plugins/_lib/mail/write.js +1 -1
- package/plugins/_lib/public/rich-text.mjs +1 -1
- package/plugins/_lib/rich-text.js +1 -1
- package/plugins/_lib/telegram/bot.js +120 -0
- package/plugins/free-tier.lock.json +26 -1
- package/plugins/telegram/CHANGELOG.md +5 -0
- package/plugins/telegram/CLAUDE.md +77 -0
- package/plugins/telegram/admin/css/index.css +68 -0
- package/plugins/telegram/admin/lib/arrange.js +103 -0
- package/plugins/telegram/admin/lib/kit.js +153 -0
- package/plugins/telegram/admin/templates/telegram.html +1 -0
- package/plugins/telegram/admin/views/chats.js +223 -0
- package/plugins/telegram/admin/views/connection.js +90 -0
- package/plugins/telegram/admin/views/telegram.js +89 -0
- package/plugins/telegram/admin/views/test.js +84 -0
- package/plugins/telegram/config.js +21 -0
- package/plugins/telegram/docs/guide.md +87 -0
- package/plugins/telegram/lib/messages.js +176 -0
- package/plugins/telegram/lib/queue.js +72 -0
- package/plugins/telegram/plugin.js +490 -0
- package/plugins/telegram/plugin.json +71 -0
- package/plugins/telegram/tests/api.test.js +381 -0
- package/plugins/telegram/tests/arrange.test.js +41 -0
- package/plugins/telegram/tests/messages.test.js +110 -0
- package/plugins/telegram/tests/queue.test.js +47 -0
- package/server/routes/api/brand-kit.js +55 -0
- package/server/routes/api/settings.js +17 -1
- package/server/server.js +2 -0
- package/server/services/brandKit.js +268 -0
- package/server/services/emailBrand.js +31 -13
- package/server/services/notify.js +20 -2
- package/server/services/plugins.js +3 -0
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Telegram › Connection - the site's own bot, made with @BotFather. The token is typed here once, checked
|
|
3
|
+
* with Telegram, and kept on the server; it is never sent back, and never kept as a draft.
|
|
4
|
+
*/
|
|
5
|
+
import {api, esc} from '../lib/kit.js';
|
|
6
|
+
import {connectionView} from '../lib/arrange.js';
|
|
7
|
+
|
|
8
|
+
export async function mount(root, ctx) {
|
|
9
|
+
const {kit, scope, here, status} = ctx;
|
|
10
|
+
const v = M.observable(connectionView(status.peek()));
|
|
11
|
+
const stop = M.effect(() => { v.value = connectionView(status.value); });
|
|
12
|
+
const token = M.observable('');
|
|
13
|
+
const connecting = M.observable(false);
|
|
14
|
+
|
|
15
|
+
root.innerHTML = `<div class="tg-stack">
|
|
16
|
+
<section class="tg-card">
|
|
17
|
+
<header><h3><span data-icon="send" data-icon-size="16"></span> Your bot <span data-help-title="Your own Telegram bot" data-help="The site talks to Telegram through a bot you make yourself with @BotFather, Telegram's own bot for making bots. It is free. The bot sends the team the site's alerts and form submissions, in the chats you link under Chats. Use a bot for this site alone: one bot can only deliver its messages to one place, so a bot already used by Takeaway or another site is refused."></span></h3>
|
|
18
|
+
<span class="tg-chip is-ok" data-bind-hidden="!v.value.connected" data-bind-text="v.value.botAt"></span>
|
|
19
|
+
<span class="tg-chip" data-bind-hidden="v.value.connected">Not connected</span></header>
|
|
20
|
+
|
|
21
|
+
<div class="tg-stack" data-bind-hidden="!v.value.connected">
|
|
22
|
+
<p class="tg-note is-bad" data-bind-hidden="!v.value.hookError" data-bind-text="v.value.hookError"></p>
|
|
23
|
+
<p class="tg-note">Connected as <a target="_blank" rel="noopener" data-bind-href="v.value.botLink" data-bind-text="v.value.botAt"></a>, sending to this site at <b data-bind-text="v.value.base"></b>. <span data-bind-text="v.value.chats"></span>.
|
|
24
|
+
<span data-help="Telegram delivers what people send the bot to this address (its webhook), with a secret only this site knows. If the site moves to a new address, connect the bot again so Telegram follows."></span></p>
|
|
25
|
+
<p class="tg-note" data-bind-hidden="!v.value.pending" data-bind-text="v.value.pending"></p>
|
|
26
|
+
<div class="tg-bar" data-bind-hidden="!v.value.manage">
|
|
27
|
+
<a class="btn btn-sm btn-primary" href="#/plugins/telegram/chats"><span data-icon="users" data-icon-size="13"></span> Link a chat</a>
|
|
28
|
+
<span class="tg-spacer"></span>
|
|
29
|
+
<button type="button" class="btn btn-sm btn-ghost" data-on-click="disconnect">Disconnect the bot</button>
|
|
30
|
+
<span data-help="Disconnecting tells Telegram to stop sending to this site and forgets the token and every linked chat here. The bot itself stays in your Telegram account; delete it with @BotFather if you no longer want it."></span>
|
|
31
|
+
</div>
|
|
32
|
+
</div>
|
|
33
|
+
|
|
34
|
+
<div class="tg-stack" data-bind-hidden="v.value.connected">
|
|
35
|
+
<ol class="tg-steps">
|
|
36
|
+
<li>In Telegram, open <a href="https://t.me/BotFather" target="_blank" rel="noopener">@BotFather</a> and send <code class="tg-code">/newbot</code>.</li>
|
|
37
|
+
<li>Give it a name (like "Acme Alerts") and a username ending in "bot" (like acme_alerts_bot).</li>
|
|
38
|
+
<li>Paste the token it gives you here and click Connect.</li>
|
|
39
|
+
</ol>
|
|
40
|
+
<div class="tg-token" data-bind-hidden="!v.value.manage">
|
|
41
|
+
<input class="form-input" type="password" placeholder="123456789:AAE…" autocomplete="off" aria-label="Bot token" data-model="token.value">
|
|
42
|
+
<button type="button" class="btn btn-sm btn-primary" data-bind-disabled="connecting.value || !token.value" data-on-click="connect" data-bind-text="connecting.value ? 'Connecting…' : 'Connect'"></button>
|
|
43
|
+
<span data-help-title="The bot token" data-help="The long line @BotFather gives you, like 123456789:AAE… It is a password for the bot: anyone with it can send as the bot. It stays on this server and is never shown again, not even to you. If it leaks, send /revoke to @BotFather and connect the new one."></span>
|
|
44
|
+
</div>
|
|
45
|
+
<p class="tg-note" data-bind-hidden="v.value.manage">Ask an administrator to connect the site's bot.</p>
|
|
46
|
+
<p class="tg-note">Telegram can only reach a site on https. The token stays on this server.</p>
|
|
47
|
+
</div>
|
|
48
|
+
</section>
|
|
49
|
+
|
|
50
|
+
<section class="tg-card">
|
|
51
|
+
<header><h3><span data-icon="shield" data-icon-size="16"></span> What is sent to Telegram <span data-help="Telegram keeps messages on its own servers; bot chats are not end-to-end encrypted. Send only what your team may read there."></span></h3></header>
|
|
52
|
+
<ul class="tg-steps">
|
|
53
|
+
<li><b>Alerts</b>: the notification's title, its text, how serious it is, the Tool that raised it and a link to the admin. Notifications meant for one named person (a to-do reminder, say) are never sent.</li>
|
|
54
|
+
<li><b>Form submissions</b>: the form's title and a link to its submissions, and - unless a chat is set to "title and link only" - each answer with its question. Passwords, files, images and hidden fields are never sent.</li>
|
|
55
|
+
<li><b>Nothing else</b> leaves the site, and nothing is sent to a chat that has not been linked with a code from this screen.</li>
|
|
56
|
+
</ul>
|
|
57
|
+
</section></div>`;
|
|
58
|
+
const view = root.firstElementChild;
|
|
59
|
+
scope(kit.helpPopovers(view, {position: 'bottom'}));
|
|
60
|
+
I.scan(view);
|
|
61
|
+
|
|
62
|
+
const bindings = M.applyBindings({v, token, connecting}, view, {
|
|
63
|
+
methods: {
|
|
64
|
+
async connect() {
|
|
65
|
+
if (connecting.peek()) return;
|
|
66
|
+
connecting.value = true;
|
|
67
|
+
try {
|
|
68
|
+
// Refused: the token stays in its box, so a typo is fixed rather than pasted again.
|
|
69
|
+
const next = await api.connect(token.peek().trim(), location.origin);
|
|
70
|
+
if (!here()) return;
|
|
71
|
+
token.value = '';
|
|
72
|
+
ctx.take(next);
|
|
73
|
+
E.toast(`Connected as @${next.botName}.`, {type: 'success'});
|
|
74
|
+
} catch (err) {
|
|
75
|
+
E.toast(err.message || String(err), {type: 'error'});
|
|
76
|
+
} finally {
|
|
77
|
+
connecting.value = false;
|
|
78
|
+
}
|
|
79
|
+
},
|
|
80
|
+
async disconnect() {
|
|
81
|
+
const n = (status.peek()?.chats || []).length;
|
|
82
|
+
const ok = await E.confirm(`Disconnect ${esc(v.peek().botAt)}? Telegram stops sending to this site${n ? ` and the ${n} linked chat${n === 1 ? '' : 's'} stop getting messages` : ''}.`,
|
|
83
|
+
{title: 'Disconnect the bot', confirmText: 'Disconnect', cancelText: 'Keep it'});
|
|
84
|
+
if (!ok || !here()) return;
|
|
85
|
+
try { ctx.take(await api.disconnect()); E.toast('Disconnected.', {type: 'success'}); } catch (err) { E.toast(err.message || String(err), {type: 'error'}); }
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
});
|
|
89
|
+
return () => { bindings.dispose(); stop(); };
|
|
90
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Telegram - one Tool, its screens as tabs under the banner:
|
|
3
|
+
*
|
|
4
|
+
* #/plugins/telegram Connection (the bot)
|
|
5
|
+
* #/plugins/telegram/chats Chats (linked chats and what each gets)
|
|
6
|
+
* #/plugins/telegram/test Test (send a sample, or raise a real notification)
|
|
7
|
+
*
|
|
8
|
+
* Path segments, not ?query: the admin router 404s a query on a fresh load. One GET /status feeds every tab;
|
|
9
|
+
* each tab is its own module with mount(root, ctx) -> cleanup, all on domma-reactive bindings.
|
|
10
|
+
*/
|
|
11
|
+
import {api, loadKit} from '../lib/kit.js';
|
|
12
|
+
|
|
13
|
+
const ROUTE = /^#\/plugins\/telegram(\/|$)/;
|
|
14
|
+
const TABS = [
|
|
15
|
+
{key: 'connection', label: 'Connection', icon: 'link', module: '/plugins/telegram/admin/views/connection.js'},
|
|
16
|
+
{key: 'chats', label: 'Chats', icon: 'users', module: '/plugins/telegram/admin/views/chats.js'},
|
|
17
|
+
{key: 'test', label: 'Test', icon: 'send', module: '/plugins/telegram/admin/views/test.js', manage: true}
|
|
18
|
+
];
|
|
19
|
+
|
|
20
|
+
let lifetime = null;
|
|
21
|
+
|
|
22
|
+
const tabFromHash = () => (location.hash.match(/^#\/plugins\/telegram\/([a-z-]+)/)?.[1] || 'connection');
|
|
23
|
+
|
|
24
|
+
export const telegramView = {
|
|
25
|
+
templateUrl: '/plugins/telegram/admin/templates/telegram.html',
|
|
26
|
+
|
|
27
|
+
async onMount($container) {
|
|
28
|
+
const kit = await loadKit();
|
|
29
|
+
lifetime ??= kit.viewLifetime(ROUTE);
|
|
30
|
+
if (!ROUTE.test(location.hash)) return;
|
|
31
|
+
lifetime.reset();
|
|
32
|
+
const scope = (fn) => { lifetime.add(fn); return fn; };
|
|
33
|
+
const container = $container.get(0);
|
|
34
|
+
const root = container.querySelector('[data-tg-admin]') || container;
|
|
35
|
+
const mountedFor = location.hash;
|
|
36
|
+
const here = () => location.hash === mountedFor && root.isConnected;
|
|
37
|
+
|
|
38
|
+
const status = M.observable(null);
|
|
39
|
+
const error = M.observable('');
|
|
40
|
+
const tabs = M.observable([]);
|
|
41
|
+
root.innerHTML = `
|
|
42
|
+
<div class="tg-loading" data-bind-hidden="status.value || error.value">Loading…</div>
|
|
43
|
+
<p class="tg-note is-bad" hidden data-bind-hidden="!error.value" data-bind-text="error.value"></p>
|
|
44
|
+
<nav class="tg-nav" aria-label="Telegram" hidden data-bind-hidden="!status.value" data-each="tabs.value key=key"><a data-bind-href="href" data-bind-class="on ? 'is-on' : ''" data-bind-aria-current="on ? 'page' : false"><span data-bind-text="label"></span></a></nav>
|
|
45
|
+
<div class="tg-body"></div>`;
|
|
46
|
+
const body = root.querySelector('.tg-body');
|
|
47
|
+
const bindings = M.applyBindings({status, error, tabs}, root);
|
|
48
|
+
scope(() => bindings.dispose());
|
|
49
|
+
|
|
50
|
+
let first;
|
|
51
|
+
try {
|
|
52
|
+
first = await api.status();
|
|
53
|
+
} catch (err) {
|
|
54
|
+
if (here()) error.value = `Telegram could not load: ${err.message || err}`;
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
if (!here()) return;
|
|
58
|
+
const shown = TABS.filter(t => !t.manage || first.can?.manage);
|
|
59
|
+
const current = shown.find(t => t.key === tabFromHash()) || shown[0];
|
|
60
|
+
tabs.value = shown.map(t => ({key: t.key, label: t.label, href: t.key === 'connection' ? '#/plugins/telegram' : `#/plugins/telegram/${t.key}`, on: t === current}));
|
|
61
|
+
status.value = first;
|
|
62
|
+
|
|
63
|
+
const ctx = {
|
|
64
|
+
kit, scope, here, container, $container,
|
|
65
|
+
status,
|
|
66
|
+
/** Fetch the status again (after a change) - every tab reads the same observable. */
|
|
67
|
+
async reload() {
|
|
68
|
+
const next = await api.status();
|
|
69
|
+
if (here()) status.value = next;
|
|
70
|
+
kit.sidebarCount('#/plugins/telegram');
|
|
71
|
+
return next;
|
|
72
|
+
},
|
|
73
|
+
/** Take a route's answer (every write answers with the status). */
|
|
74
|
+
take(next) {
|
|
75
|
+
if (next && here()) status.value = next;
|
|
76
|
+
kit.sidebarCount('#/plugins/telegram');
|
|
77
|
+
},
|
|
78
|
+
go(tab) { location.hash = tab === 'connection' ? '#/plugins/telegram' : `#/plugins/telegram/${tab}`; }
|
|
79
|
+
};
|
|
80
|
+
try {
|
|
81
|
+
const mod = await import(current.module);
|
|
82
|
+
if (!here()) return;
|
|
83
|
+
const cleanup = await mod.mount(body, ctx);
|
|
84
|
+
if (typeof cleanup === 'function') scope(cleanup);
|
|
85
|
+
} catch (err) {
|
|
86
|
+
if (here()) error.value = `This screen could not load: ${err.message || err}`;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
};
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Telegram › Test - try a chat before relying on it: a hello, a sample alert, a sample form entry (as that
|
|
3
|
+
* chat would get it), or a real notification raised in the bell, which then travels the whole way (the
|
|
4
|
+
* notification, each chat's routing, the queue) like any other.
|
|
5
|
+
*/
|
|
6
|
+
import {api} from '../lib/kit.js';
|
|
7
|
+
|
|
8
|
+
const KINDS = [
|
|
9
|
+
{id: 'hello', label: 'A hello', help: 'A short message naming the chat. Proves the bot can post there.'},
|
|
10
|
+
{id: 'alert', label: 'A sample alert', help: 'What a warning looks like in this chat. Sent whatever the chat\'s alert choices are.'},
|
|
11
|
+
{id: 'form', label: 'A sample form entry', help: 'What a submission of the chosen form looks like in this chat, with placeholders for the answers - or the title and link only, if the chat is set to that.'},
|
|
12
|
+
{id: 'notification', label: 'A real notification', help: 'Raises a test notification in the admin\'s bell (from "Telegram test alerts"). Every chat whose routing takes that severity gets it - the whole path, as a real alert would travel.'}
|
|
13
|
+
];
|
|
14
|
+
|
|
15
|
+
export async function mount(root, ctx) {
|
|
16
|
+
const {kit, scope, here, status} = ctx;
|
|
17
|
+
const chats = M.observable([]);
|
|
18
|
+
const forms = M.observable([]);
|
|
19
|
+
const connected = M.observable(false);
|
|
20
|
+
const chat = M.observable('');
|
|
21
|
+
const kind = M.observable('hello');
|
|
22
|
+
const form = M.observable('');
|
|
23
|
+
const severity = M.observable('warning');
|
|
24
|
+
const sending = M.observable(false);
|
|
25
|
+
const result = M.observable('');
|
|
26
|
+
const stop = M.effect(() => {
|
|
27
|
+
const st = status.value || {};
|
|
28
|
+
connected.value = Boolean(st.connected);
|
|
29
|
+
chats.value = (st.chats || []).map(c => ({id: c.id, name: c.paused ? `${c.name} (paused)` : c.name}));
|
|
30
|
+
forms.value = (st.forms || []).map(f => ({id: f.slug, name: f.title}));
|
|
31
|
+
if (!chats.peek().some(c => c.id === chat.peek())) chat.value = chats.peek()[0]?.id || '';
|
|
32
|
+
if (!forms.peek().some(f => f.id === form.peek())) form.value = forms.peek()[0]?.id || '';
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
root.innerHTML = `<div class="tg-stack">
|
|
36
|
+
<p class="tg-note is-warn" data-bind-hidden="connected.value">Connect the bot first, on the <a href="#/plugins/telegram">Connection</a> tab.</p>
|
|
37
|
+
<section class="tg-card" data-bind-hidden="!connected.value">
|
|
38
|
+
<header><h3><span data-icon="send" data-icon-size="16"></span> Send a test <span data-help-title="Testing" data-help="Send something to a linked chat to see it arrive, and how it looks. Nothing here changes a chat's settings."></span></h3></header>
|
|
39
|
+
<div class="tg-test">
|
|
40
|
+
<label class="form-label" for="tg-test-kind">What to send</label>
|
|
41
|
+
<div class="tg-stack">${KINDS.map(k => `<label class="tg-check"><input type="radio" name="tg-test-kind" value="${k.id}" data-model="kind.value"> ${k.label} <span data-help="${k.help}"></span></label>`).join('')}</div>
|
|
42
|
+
|
|
43
|
+
<label class="form-label" for="tg-test-chat" data-bind-hidden="kind.value === 'notification'">To</label>
|
|
44
|
+
<select id="tg-test-chat" class="form-select" data-bind-hidden="kind.value === 'notification'" data-model="chat.value" data-each="chats.value key=id"><option data-bind-value="id">{{name}}</option></select>
|
|
45
|
+
|
|
46
|
+
<label class="form-label" for="tg-test-form" data-bind-hidden="kind.value !== 'form'">Form</label>
|
|
47
|
+
<select id="tg-test-form" class="form-select" data-bind-hidden="kind.value !== 'form'" data-model="form.value" data-each="forms.value key=id"><option data-bind-value="id">{{name}}</option></select>
|
|
48
|
+
|
|
49
|
+
<label class="form-label" for="tg-test-sev" data-bind-hidden="kind.value !== 'notification'">How serious</label>
|
|
50
|
+
<select id="tg-test-sev" class="form-select" data-bind-hidden="kind.value !== 'notification'" data-model="severity.value">
|
|
51
|
+
<option value="info">Info</option><option value="success">Success</option><option value="warning">Warning</option><option value="critical">Critical</option></select>
|
|
52
|
+
</div>
|
|
53
|
+
<p class="tg-note" data-bind-hidden="kind.value === 'notification' || chats.value.length">No chats are linked yet - link one under <a href="#/plugins/telegram/chats">Chats</a>.</p>
|
|
54
|
+
<div class="tg-bar"><button type="button" class="btn btn-sm btn-primary" data-on-click="send" data-bind-disabled="sending.value || (kind.value !== 'notification' && !chat.value) || (kind.value === 'form' && !form.value)" data-bind-text="sending.value ? 'Sending…' : 'Send'"></button>
|
|
55
|
+
<span class="tg-note" data-bind-text="result.value"></span></div>
|
|
56
|
+
</section></div>`;
|
|
57
|
+
const view = root.firstElementChild;
|
|
58
|
+
scope(kit.helpPopovers(view, {position: 'bottom'}));
|
|
59
|
+
I.scan(view);
|
|
60
|
+
|
|
61
|
+
const bindings = M.applyBindings({chats, forms, connected, chat, kind, form, severity, sending, result}, view, {
|
|
62
|
+
methods: {
|
|
63
|
+
async send() {
|
|
64
|
+
if (sending.peek()) return;
|
|
65
|
+
sending.value = true;
|
|
66
|
+
result.value = '';
|
|
67
|
+
try {
|
|
68
|
+
const k = kind.peek();
|
|
69
|
+
const r = await api.test(k === 'notification' ? {kind: k, severity: severity.peek()} : {kind: k, chat: chat.peek(), form: form.peek()});
|
|
70
|
+
if (!here()) return;
|
|
71
|
+
result.value = r.note || 'Sent - look in that chat.';
|
|
72
|
+
E.toast(k === 'notification' ? 'Raised.' : 'Sent.', {type: 'success'});
|
|
73
|
+
kit.sidebarCount('#/plugins/telegram');
|
|
74
|
+
} catch (err) {
|
|
75
|
+
if (here()) result.value = '';
|
|
76
|
+
E.toast(err.message || String(err), {type: 'error'});
|
|
77
|
+
} finally {
|
|
78
|
+
sending.value = false;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
});
|
|
83
|
+
return () => { bindings.dispose(); stop(); };
|
|
84
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Telegram - default settings (config/plugins.json `telegram.settings`). Written only by the Tool's own
|
|
3
|
+
* routes: the token, the webhook secret and the link code never reach a browser.
|
|
4
|
+
*
|
|
5
|
+
* botToken, botName the bot made with @BotFather
|
|
6
|
+
* secret our webhook secret (Telegram's X-Telegram-Bot-Api-Secret-Token)
|
|
7
|
+
* base the site's https address, given when the bot was connected
|
|
8
|
+
* linkSecret, linkSecretUntil the one-time "/link" code
|
|
9
|
+
* chats linked chats with their routing (lib/messages.js)
|
|
10
|
+
*/
|
|
11
|
+
export default {
|
|
12
|
+
botToken: '',
|
|
13
|
+
botName: '',
|
|
14
|
+
secret: '',
|
|
15
|
+
base: '',
|
|
16
|
+
linkSecret: '',
|
|
17
|
+
linkSecretUntil: '',
|
|
18
|
+
linkOwnerId: '',
|
|
19
|
+
linkOwnerName: '',
|
|
20
|
+
chats: []
|
|
21
|
+
};
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Guide
|
|
3
|
+
order: 1
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
Telegram sends your team the site's alerts and form submissions, through a Telegram bot of your own. It is free, and so is Telegram.
|
|
7
|
+
|
|
8
|
+
## What it does
|
|
9
|
+
|
|
10
|
+
- Sends the notifications the site raises (a payment failed, the disk is filling, a Tool stopped) to a Telegram chat, as they happen.
|
|
11
|
+
- Sends each form submission to a chat, with the answers or just the form's title and a link.
|
|
12
|
+
- Works with any number of chats: your team's group, or one person's private chat with the bot. Each chat chooses what it gets.
|
|
13
|
+
|
|
14
|
+
Telegram Pro (paid) adds two-way chat with your customers. See its own guide.
|
|
15
|
+
|
|
16
|
+
## Getting started
|
|
17
|
+
|
|
18
|
+
1. In Telegram, open **@BotFather** and send `/newbot`. Give the bot a name (like "Acme Alerts") and a username ending in "bot".
|
|
19
|
+
2. BotFather answers with a token, a long line like `123456789:AAE…`. Copy it.
|
|
20
|
+
3. Open [Telegram](#/plugins/telegram) from the admin sidebar, paste the token on the **Connection** tab and click **Connect**.
|
|
21
|
+
4. On the **Chats** tab, click **Link a chat**. A one-time code appears.
|
|
22
|
+
5. In Telegram, add the bot to your team's group (or open a private chat with it) and send the line shown, `/link` and the code.
|
|
23
|
+
6. Click **Check**. The chat appears in the list, getting warning and critical alerts.
|
|
24
|
+
7. Click the chat to choose what else it gets.
|
|
25
|
+
|
|
26
|
+
Use a bot for this site alone. One bot can deliver its messages to one place only, so the Tool refuses a bot that Takeaway or another site already uses: make a second bot for it.
|
|
27
|
+
|
|
28
|
+
The site must be on https: Telegram does not deliver to plain http.
|
|
29
|
+
|
|
30
|
+
## Screens
|
|
31
|
+
|
|
32
|
+
### Connection
|
|
33
|
+
|
|
34
|
+
Shows the bot and where Telegram delivers to. **Disconnect the bot** tells Telegram to stop and forgets the token and every linked chat. A red note means Telegram reports it cannot reach the site; connect the bot again to repair it.
|
|
35
|
+
|
|
36
|
+
### Chats
|
|
37
|
+
|
|
38
|
+
Every linked chat, with what it gets. Click a chat (or press Enter) to change it; right-click, the ⋮ button or Shift+F10 opens the menu:
|
|
39
|
+
|
|
40
|
+
| Menu item | What it does |
|
|
41
|
+
|---|---|
|
|
42
|
+
| What it gets… | Opens the chat's settings |
|
|
43
|
+
| Send a test | Sends a short hello to that chat |
|
|
44
|
+
| Pause / Resume | Stops everything going to the chat until you resume it |
|
|
45
|
+
| Unlink… | Stops the chat getting anything and tells the chat so |
|
|
46
|
+
|
|
47
|
+
In a chat's settings:
|
|
48
|
+
|
|
49
|
+
- **Name in this admin**: only for you; Telegram does not see it.
|
|
50
|
+
- Saving makes you the chat's owner: from then on it gets only alerts you would see in the bell and forms whose submissions you may read.
|
|
51
|
+
- **Alerts**: how serious an alert must be (Info, Success, Warning, Critical) and from which Tools. A new chat gets Warning and Critical from every Tool.
|
|
52
|
+
- **Form submissions**: which forms (or every form, including new ones), and what the message holds:
|
|
53
|
+
- **The form's title, the answers and a link** (the default once forms are switched on), or
|
|
54
|
+
- **The form's title and a link only**: nothing the visitor typed leaves the site.
|
|
55
|
+
|
|
56
|
+
Closing the settings with changes asks first. Leaving the screen keeps the changes in this browser and offers them back next time.
|
|
57
|
+
|
|
58
|
+
### Test
|
|
59
|
+
|
|
60
|
+
Sends a hello, a sample alert or a sample form entry to a chosen chat, or raises **a real notification** in the bell, which then travels to every chat whose settings take it, like any other alert.
|
|
61
|
+
|
|
62
|
+
## What is sent to Telegram
|
|
63
|
+
|
|
64
|
+
Telegram keeps messages on its own servers, and chats with bots are not end-to-end encrypted. Send only what your team may read there.
|
|
65
|
+
|
|
66
|
+
| Message | What it holds | Who gets it |
|
|
67
|
+
|---|---|---|
|
|
68
|
+
| Alert | The notification's title and text, how serious it is, the Tool that raised it, the site's name, a link to the admin | Every linked chat whose settings take that severity and Tool |
|
|
69
|
+
| Form submission | The form's title, the site's name, a link to the form's submissions, and (unless set to title and link only) each question with its answer | Every linked chat that has that form switched on |
|
|
70
|
+
| Link and test messages | Confirmations such as "Linked as Office", the test message you chose | The chat concerned |
|
|
71
|
+
|
|
72
|
+
Never sent:
|
|
73
|
+
|
|
74
|
+
- notifications meant for one named person, such as a to-do reminder;
|
|
75
|
+
- passwords, uploaded files, images and hidden fields from a form, or any answer whose question is not on the form;
|
|
76
|
+
- anything to a chat that has not been linked with a code from the Chats tab;
|
|
77
|
+
- anything the chat's owner could not see themselves. The owner is whoever made the chat's link code, then whoever last changed what it gets (shown on the chat). An alert goes to a chat only if its owner would see it in the bell (a notification for Super Admins only never reaches a chat an admin set up), and a form only if its owner may read that form's submissions. If the owner's account is removed or switched off, the chat stops getting messages until someone else saves its settings.
|
|
78
|
+
|
|
79
|
+
Notifications pushed by Domma's own server and the sample notifications from the Notifications settings are not sent to Telegram.
|
|
80
|
+
|
|
81
|
+
## Good to know
|
|
82
|
+
|
|
83
|
+
- Messages to one chat go out about one a second, as Telegram asks. A burst waits its turn; after 50 waiting, more are dropped (the bell still has them).
|
|
84
|
+
- A message that cannot be sent never stops the form or the notification. The chat shows the reason in red, and the sidebar badge turns red.
|
|
85
|
+
- The link code works once, for 15 minutes. A chat that sends five wrong codes is ignored until you make a new one.
|
|
86
|
+
- In a linked chat, `/unlink` stops it getting anything.
|
|
87
|
+
- If a Telegram group becomes a "supergroup" (Telegram does this as groups grow), it stays linked.
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Telegram - what is sent, and to which chat. PURE: no I/O, so every rule here is tested
|
|
3
|
+
* (tests/messages.test.js).
|
|
4
|
+
*
|
|
5
|
+
* A linked chat (a person or a group, linked with "/link <code>") has its own routing:
|
|
6
|
+
*
|
|
7
|
+
* alerts {on, severities, sources} notifications the site raises (notification:raised)
|
|
8
|
+
* forms {on, all, slugs, detail} form submissions (form:submitted)
|
|
9
|
+
*
|
|
10
|
+
* What leaves the site is decided here and nowhere else:
|
|
11
|
+
* - an alert: its title, body, severity, the Tool that raised it and a link to the admin. A personal
|
|
12
|
+
* notification (one meant for named people, such as a to-do reminder) is never sent, and a chat gets only
|
|
13
|
+
* the alerts the person who set up its routing (its owner) may see in the bell.
|
|
14
|
+
* - a form submission: the form's title and a link to its submissions; with detail 'fields' (the
|
|
15
|
+
* default) also each field's label and value - never a password, file, image or hidden field. Only
|
|
16
|
+
* forms the chat's owner may read the submissions of.
|
|
17
|
+
*
|
|
18
|
+
* Messages are built from whole lines under Telegram's length limit, cut before escaping (bot.js escFit /
|
|
19
|
+
* fitLines): a cut through the HTML would make Telegram refuse the whole message.
|
|
20
|
+
*
|
|
21
|
+
* @module telegram/lib/messages
|
|
22
|
+
*/
|
|
23
|
+
import {clip, esc, escFit, fitLines} from '../../_lib/telegram/bot.js';
|
|
24
|
+
|
|
25
|
+
export const SEVERITIES = ['info', 'success', 'warning', 'critical'];
|
|
26
|
+
export const DEFAULT_SEVERITIES = ['warning', 'critical'];
|
|
27
|
+
export const DETAILS = ['fields', 'title'];
|
|
28
|
+
export const DEFAULT_DETAIL = 'fields';
|
|
29
|
+
|
|
30
|
+
/** Never sent, whatever a chat's routing says: secrets, files, and what the visitor did not type. */
|
|
31
|
+
export const NEVER_SENT = new Set(['password', 'file', 'image', 'hidden', 'spacer', 'page-break', 'html', 'section', 'heading']);
|
|
32
|
+
|
|
33
|
+
const MAX_FIELDS = 40;
|
|
34
|
+
const MAX_VALUE = 600;
|
|
35
|
+
const MAX_SOURCES = 200;
|
|
36
|
+
const MAX_FORMS = 200;
|
|
37
|
+
|
|
38
|
+
const MARK = {info: 'ℹ️', success: '✅', warning: '⚠️', critical: '🚨'};
|
|
39
|
+
|
|
40
|
+
/** A new chat's routing: warning and critical alerts from everything, no forms yet. */
|
|
41
|
+
export function defaultRouting() {
|
|
42
|
+
return {
|
|
43
|
+
alerts: {on: true, severities: [...DEFAULT_SEVERITIES], sources: []},
|
|
44
|
+
forms: {on: false, all: false, slugs: [], detail: DEFAULT_DETAIL}
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const strings = (list, max, test = () => true) => [...new Set((Array.isArray(list) ? list : [])
|
|
49
|
+
.map(s => String(s ?? '').trim()).filter(s => s && s.length <= 200 && test(s)))].slice(0, max);
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* A chat's routing as stored: whitelisted, defaulted, bounded. `patch` may hold any part; what it
|
|
53
|
+
* leaves out keeps `current`.
|
|
54
|
+
*/
|
|
55
|
+
export function cleanRouting(patch = {}, current = defaultRouting()) {
|
|
56
|
+
const cur = {...defaultRouting(), ...current};
|
|
57
|
+
const a = {...cur.alerts, ...(patch.alerts && typeof patch.alerts === 'object' ? patch.alerts : {})};
|
|
58
|
+
const f = {...cur.forms, ...(patch.forms && typeof patch.forms === 'object' ? patch.forms : {})};
|
|
59
|
+
return {
|
|
60
|
+
alerts: {
|
|
61
|
+
on: a.on !== false,
|
|
62
|
+
severities: strings(a.severities, SEVERITIES.length, s => SEVERITIES.includes(s)),
|
|
63
|
+
sources: strings(a.sources, MAX_SOURCES, s => /^[a-z0-9_.-]+(:[a-z0-9_.:-]+)?$/i.test(s))
|
|
64
|
+
},
|
|
65
|
+
forms: {
|
|
66
|
+
on: f.on === true,
|
|
67
|
+
all: f.all === true,
|
|
68
|
+
slugs: strings(f.slugs, MAX_FORMS, s => /^[a-z0-9][a-z0-9_-]*$/i.test(s)),
|
|
69
|
+
detail: DETAILS.includes(f.detail) ? f.detail : DEFAULT_DETAIL
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** A chat's name as typed in the admin: one line, 80 characters. */
|
|
75
|
+
export const cleanName = (s, fallback = 'Chat') => (String(s ?? '').replace(/\s+/g, ' ').trim().slice(0, 80) || fallback);
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Does a source id match a chat's chosen sources? Empty = every source. A chosen owner ('invoice')
|
|
79
|
+
* takes every source of that Tool ('invoice:overdue').
|
|
80
|
+
*/
|
|
81
|
+
export function sourceMatches(chosen, source) {
|
|
82
|
+
if (!chosen?.length) return true;
|
|
83
|
+
const s = String(source || '');
|
|
84
|
+
return chosen.some(c => c === s || (!c.includes(':') && s.split(':')[0] === c));
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** A notification meant for named people (a to-do, a personal reminder) - never to a chat. */
|
|
88
|
+
export const isPersonal = (data) => Array.isArray(data?.audience?.userIds);
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* The chats an alert goes to. `mayHear(chat, data)` - may this chat's owner see this notification in the bell?
|
|
92
|
+
* (The plugin checks the owner's roles against the notification's audience.) Without it, nothing is sent.
|
|
93
|
+
*/
|
|
94
|
+
export function chatsForAlert(chats, entry, {mayHear = () => false} = {}) {
|
|
95
|
+
const d = entry?.data;
|
|
96
|
+
if (!d?.title || isPersonal(d)) return [];
|
|
97
|
+
return (chats || []).filter(c => !c.paused && c.alerts?.on
|
|
98
|
+
&& (c.alerts.severities || []).includes(d.severity) && sourceMatches(c.alerts.sources, d.source) && mayHear(c, d));
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** The chats a form submission goes to. `mayRead(chat)` - may this chat's owner read this form's submissions? */
|
|
102
|
+
export function chatsForForm(chats, slug, {mayRead = () => false} = {}) {
|
|
103
|
+
if (!slug) return [];
|
|
104
|
+
return (chats || []).filter(c => !c.paused && c.forms?.on && (c.forms.all || (c.forms.slugs || []).includes(slug)) && mayRead(c));
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** An admin link for a message: an admin route under the site's address, or a web address as it is. */
|
|
108
|
+
export function adminLink(link, base) {
|
|
109
|
+
const l = String(link || '').trim();
|
|
110
|
+
if (l.length > 500 || String(base || '').length > 200) return '';
|
|
111
|
+
if (/^https?:\/\/\S+$/i.test(l)) return l;
|
|
112
|
+
if (/^#\/\S*$/.test(l) && base) return `${base}/admin/${l}`;
|
|
113
|
+
return '';
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** One alert, as Telegram HTML, under Telegram's limit. */
|
|
117
|
+
export function alertText(entry, {base = '', site = ''} = {}) {
|
|
118
|
+
const d = entry?.data || {};
|
|
119
|
+
const link = adminLink(d.link, base);
|
|
120
|
+
const from = [d.sourceLabel || '', site].filter(Boolean).map(s => escFit(s, 120)).join(' · ');
|
|
121
|
+
return fitLines([
|
|
122
|
+
`${MARK[d.severity] || MARK.info} <b>${escFit(d.title, 400)}</b>`,
|
|
123
|
+
...(d.body ? [escFit(d.body, 2500)] : []),
|
|
124
|
+
...(from ? [`<i>${from}</i>`] : [])
|
|
125
|
+
], {keep: link ? [`<a href="${esc(link)}">Open in the admin</a>`] : []});
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** A field's value as one line of text, or '' when there is nothing to show (or nothing that may be shown). */
|
|
129
|
+
export function fieldValue(v) {
|
|
130
|
+
if (v === null || v === undefined || v === '') return '';
|
|
131
|
+
if (typeof v === 'boolean') return v ? 'Yes' : 'No';
|
|
132
|
+
if (typeof v === 'number') return Number.isFinite(v) ? String(v) : '';
|
|
133
|
+
if (Array.isArray(v)) return v.map(fieldValue).filter(Boolean).join(', ');
|
|
134
|
+
// An object is a file ({url, name, …}) or something else no person typed - never sent.
|
|
135
|
+
if (typeof v === 'object') return '';
|
|
136
|
+
return String(v).trim();
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* The fields a submission may show, in the form's order: [{label, value}]. Only fields the form
|
|
141
|
+
* defines (a stray key in the posted data is not shown), never one of NEVER_SENT.
|
|
142
|
+
*/
|
|
143
|
+
export function shownFields(form, data) {
|
|
144
|
+
const out = [];
|
|
145
|
+
for (const f of Array.isArray(form?.fields) ? form.fields : []) {
|
|
146
|
+
if (!f || typeof f.name !== 'string' || NEVER_SENT.has(String(f.type || '').toLowerCase())) continue;
|
|
147
|
+
if (/pass(word)?|secret|token/i.test(f.name)) continue;
|
|
148
|
+
const value = fieldValue(data?.[f.name]);
|
|
149
|
+
if (!value) continue;
|
|
150
|
+
out.push({label: clip(String(f.label || f.name), 120), value: clip(value, MAX_VALUE)});
|
|
151
|
+
if (out.length >= MAX_FIELDS) break;
|
|
152
|
+
}
|
|
153
|
+
return out;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* One form submission, as Telegram HTML. `detail` 'title' sends the form's title and the link only. A long
|
|
158
|
+
* submission keeps its first answers whole and says the rest are in the admin.
|
|
159
|
+
*/
|
|
160
|
+
export function formText(sub, form, {base = '', site = '', detail = DEFAULT_DETAIL} = {}) {
|
|
161
|
+
const title = sub?.formTitle || form?.title || sub?.slug || 'a form';
|
|
162
|
+
const link = base && sub?.slug ? `${base}/admin/#/forms/${encodeURIComponent(sub.slug)}/submissions` : '';
|
|
163
|
+
const fields = detail === 'title' ? [] : shownFields(form, sub?.data);
|
|
164
|
+
return fitLines([
|
|
165
|
+
`📝 <b>New ${escFit(title, 200)} entry</b>${sub?.ended ? ' <i>(ended early by one of its rules)</i>' : ''}`,
|
|
166
|
+
...(site ? [`<i>${escFit(site, 120)}</i>`] : []),
|
|
167
|
+
...(fields.length ? ['', ...fields.map(f => `<b>${esc(f.label)}:</b> ${esc(f.value)}`)] : [])
|
|
168
|
+
], {keep: link ? ['', `<a href="${esc(link)}">Open the submissions</a>`] : [], more: '<i>… more answers in the admin</i>'});
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** A chat for the admin: never its Telegram id's history, just what the screens show. */
|
|
172
|
+
export function chatForAdmin(c) {
|
|
173
|
+
const r = cleanRouting(c);
|
|
174
|
+
return {id: c.id, name: c.name, type: c.type || 'private', linkedAt: c.linkedAt || null, paused: Boolean(c.paused),
|
|
175
|
+
lastError: c.lastError || '', lastSentAt: c.lastSentAt || null, ownerName: c.ownerName || '', ...r};
|
|
176
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Telegram - one queue per chat, so a burst (a form flood, a run of alerts) reaches Telegram at about one
|
|
3
|
+
* message a second per chat, as Telegram asks, instead of being refused. In memory: a restart drops what
|
|
4
|
+
* is waiting, which is the right side to fail on for alerts that are also in the admin's bell.
|
|
5
|
+
*
|
|
6
|
+
* A send never throws at the caller: each queued message resolves to Telegram's answer, or
|
|
7
|
+
* {ok: false, description} when the queue is full or the chat could not be reached. A 429 is waited out
|
|
8
|
+
* once (Telegram says how long, `parameters.retry_after`).
|
|
9
|
+
*
|
|
10
|
+
* @module telegram/lib/queue
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* @param {object} o
|
|
15
|
+
* @param {(chatId: string, text: string, extra: object, ctx: any) => Promise<object>} o.send - `ctx` is what push was given (the bot token it was queued under)
|
|
16
|
+
* @param {number} [o.gapMs=1000] - the least time between two messages to one chat
|
|
17
|
+
* @param {number} [o.max=50] - messages waiting per chat before new ones are refused
|
|
18
|
+
* @param {(ms: number) => Promise<void>} [o.sleep]
|
|
19
|
+
* @param {() => number} [o.now]
|
|
20
|
+
* @param {(chatId: string, result: object) => void} [o.onResult] - every answer, for the chat's last error
|
|
21
|
+
*/
|
|
22
|
+
export function createQueue({send, gapMs = 1000, max = 50, sleep = (ms) => new Promise(r => setTimeout(r, ms).unref?.()), now = () => Date.now(), onResult = () => {}}) {
|
|
23
|
+
const lanes = new Map(); // chatId -> {chain, waiting, last}
|
|
24
|
+
|
|
25
|
+
const lane = (chatId) => {
|
|
26
|
+
let l = lanes.get(chatId);
|
|
27
|
+
if (!l) {
|
|
28
|
+
// Customer chats (Telegram Pro) each make a lane: forget idle ones past their gap, so the map stays small.
|
|
29
|
+
if (lanes.size >= 500) for (const [k, v] of lanes) if (!v.waiting && now() - v.last > gapMs) lanes.delete(k);
|
|
30
|
+
l = {chain: Promise.resolve(), waiting: 0, last: -Infinity};
|
|
31
|
+
lanes.set(chatId, l);
|
|
32
|
+
}
|
|
33
|
+
return l;
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
async function deliver(l, chatId, text, extra, ctx) {
|
|
37
|
+
const wait = l.last + gapMs - now();
|
|
38
|
+
if (wait > 0) await sleep(wait);
|
|
39
|
+
let r;
|
|
40
|
+
try { r = await send(chatId, text, extra, ctx); } catch (err) { r = {ok: false, description: err?.message || String(err)}; }
|
|
41
|
+
if (!r?.ok && r?.error_code === 429) {
|
|
42
|
+
const after = Math.min(Number(r.parameters?.retry_after) || 1, 60);
|
|
43
|
+
await sleep(after * 1000);
|
|
44
|
+
try { r = await send(chatId, text, extra, ctx); } catch (err) { r = {ok: false, description: err?.message || String(err)}; }
|
|
45
|
+
}
|
|
46
|
+
l.last = now();
|
|
47
|
+
r = r || {ok: false, description: 'No answer.'};
|
|
48
|
+
try { onResult(chatId, r); } catch { /* a report, not part of the send */ }
|
|
49
|
+
return r;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
return {
|
|
53
|
+
/** Queue one message for a chat. Resolves to Telegram's answer; never rejects. */
|
|
54
|
+
push(chatId, text, extra = {}, ctx = undefined) {
|
|
55
|
+
const id = String(chatId);
|
|
56
|
+
const l = lane(id);
|
|
57
|
+
if (l.waiting >= max) return Promise.resolve({ok: false, description: 'Too many messages waiting for this chat - this one was dropped.'});
|
|
58
|
+
l.waiting++;
|
|
59
|
+
// A lane is kept once made (one per linked chat - a handful): its `last` spaces the next burst too.
|
|
60
|
+
const p = l.chain.then(() => deliver(l, id, text, extra, ctx)).finally(() => { l.waiting--; });
|
|
61
|
+
l.chain = p.catch(() => {});
|
|
62
|
+
return p;
|
|
63
|
+
},
|
|
64
|
+
/** How many are waiting, for one chat or all. */
|
|
65
|
+
waiting(chatId) {
|
|
66
|
+
if (chatId !== undefined) return lanes.get(String(chatId))?.waiting || 0;
|
|
67
|
+
let n = 0;
|
|
68
|
+
for (const l of lanes.values()) n += l.waiting;
|
|
69
|
+
return n;
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
}
|