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,77 @@
|
|
|
1
|
+
# Telegram - AI Assistant Guide
|
|
2
|
+
|
|
3
|
+
Free Tool. Maintained in `dcms-marketplace/plugins/telegram`; the copy in domma-cms is made by `make sync-free-tier`
|
|
4
|
+
(never edit it there). Telegram Pro (`plugins/telegram-pro`, paid) builds on it through the registry below.
|
|
5
|
+
|
|
6
|
+
## What it does
|
|
7
|
+
|
|
8
|
+
The site's own bot (made with @BotFather) sends the team alerts (`notification:raised`, CMS core) and form
|
|
9
|
+
submissions (`form:submitted`) to linked chats, each with its own routing. Bot API helpers are the engine's
|
|
10
|
+
`plugins/_lib/telegram/bot.js` (shared with Telegram Pro; Takeaway still has its own copy).
|
|
11
|
+
|
|
12
|
+
## Files
|
|
13
|
+
|
|
14
|
+
- `plugin.js` - routes, the webhook, the listeners, the registry.
|
|
15
|
+
- `lib/messages.js` - PURE: routing (`cleanRouting`, `chatsForAlert`, `chatsForForm`), message text (`alertText`,
|
|
16
|
+
`formText`) and what is never sent (`NEVER_SENT`, `isPersonal`). Every privacy rule lives here.
|
|
17
|
+
- `lib/queue.js` - per-chat queue, ~1 message/s, 429 waited out once, 50 waiting max, never throws. Each message
|
|
18
|
+
carries the token it was queued under (a bot change never sends old messages with the new bot).
|
|
19
|
+
- Message text is built from whole lines with `escFit`/`fitLines` (bot.js): never cut after escaping.
|
|
20
|
+
- `admin/views/telegram.js` - tab shell (Connection, Chats, Test) over one `status` observable.
|
|
21
|
+
- `admin/views/{connection,chats,test}.js` - each `mount(root, ctx)`, domma-reactive throughout.
|
|
22
|
+
- `admin/lib/kit.js` - run-time admin helpers, API, `openPanel` (dirty guard), `wireRows` (menu, Shift+F10, Enter,
|
|
23
|
+
arrows), drafts. Telegram Pro imports it from `/plugins/telegram/admin/lib/kit.js`.
|
|
24
|
+
- `admin/lib/arrange.js` - PURE display strings and the routing panel's draft/body.
|
|
25
|
+
- `docs/guide.md` - the user guide (Documentation > Plugins). Update with behaviour.
|
|
26
|
+
|
|
27
|
+
## Storage
|
|
28
|
+
|
|
29
|
+
`config/plugins.json` `telegram.settings` (defaults in `config.js`): `botToken`, `botName`, `secret` (webhook),
|
|
30
|
+
`base` (the https origin given at Connect), `linkSecret`/`linkSecretUntil` (named to match the core's secret mask),
|
|
31
|
+
`linkOwnerId`/`linkOwnerName` (who made the live code: the new chat's owner; a Manager staff session never owns),
|
|
32
|
+
`chats: [{id, chatId, name, type, linkedAt, paused, lastError, lastSentAt, alerts, forms}]`. Written only by this
|
|
33
|
+
Tool's routes. The token, secret and link code are never in a reply; the link code only to `manage`.
|
|
34
|
+
|
|
35
|
+
## Routes (/api/plugins/telegram; permission `telegram`: read / manage)
|
|
36
|
+
|
|
37
|
+
| Method | Path | Who | Purpose |
|
|
38
|
+
|---|---|---|---|
|
|
39
|
+
| GET | /status | read | bot, webhook health, chats, forms, sources; link code to manage only |
|
|
40
|
+
| GET | /count | read | badge: linked chats (inventory), red on a webhook problem or a failed send |
|
|
41
|
+
| POST | /connect | manage | `{token, base}`: getMe, getWebhookInfo (refuses a bot whose webhook points elsewhere), setWebhook with a secret |
|
|
42
|
+
| DELETE | /connection | manage | deleteWebhook, forget token, secret and chats |
|
|
43
|
+
| POST | /link-code | manage | one-time code: 16 chars, 15 min, burnt after 5 wrong tries |
|
|
44
|
+
| PUT | /chats/:id | manage | `{name, paused, alerts, forms}` through `cleanRouting` |
|
|
45
|
+
| DELETE | /chats/:id | manage | unlink (the chat is told) |
|
|
46
|
+
| POST | /test | manage | `{kind: hello|alert|form|notification, chat, form, severity}` |
|
|
47
|
+
| POST | /webhook | Telegram | `X-Telegram-Bot-Api-Secret-Token` checked timing-safe, else 401 |
|
|
48
|
+
|
|
49
|
+
The webhook answers 200 at once and handles updates one at a time per chat on a promise chain (100 waiting max per chat) (`awaitUpdates: true` in
|
|
50
|
+
tests makes the route wait); `update_id`s are remembered (last 500), so Telegram's resends do nothing.
|
|
51
|
+
Webhook commands: `/link <code>`, `/unlink` (in a linked chat); without Pro also `/start` (private) and `/help`.
|
|
52
|
+
Wrong link codes: 5 per chat (then that chat is ignored for that code), 50 in all burn it.
|
|
53
|
+
`migrate_to_chat_id` moves a linked group to its supergroup id. Everything else goes to the registry handlers.
|
|
54
|
+
|
|
55
|
+
## Registry (Telegram Pro)
|
|
56
|
+
|
|
57
|
+
`globalThis[Symbol.for('domma.telegram')]` = `{version: 1, handlers, register(name, {onMessage}), unregister(name),
|
|
58
|
+
services}`. `onMessage(msg, {command, linked})` resolves true when it took the update. `services`: `ready()`,
|
|
59
|
+
`botName()`, `base()`, `siteName()`, `chats()` (no token), `send(chatId, html, extra)` (queued, resolves to
|
|
60
|
+
Telegram's answer, never rejects), `esc`.
|
|
61
|
+
|
|
62
|
+
## Gotchas
|
|
63
|
+
|
|
64
|
+
- The core bus has no `off`: the listeners are added once per process (`listening`) and call the live instance.
|
|
65
|
+
- Owners: a chat has `ownerId`/`ownerName` - who made its link code, then who last changed its alerts or forms.
|
|
66
|
+
Alerts go only if `inAudience(data.audience, owner)` (core notify.js); forms only if the owner holds
|
|
67
|
+
`collections.read` and `canSeeArtefact(owner, form)` (projects). Owners are read fresh (`getUserById`, 60 s cache);
|
|
68
|
+
a deleted or inactive owner stops the chat. `PUT /chats/:id` with forms on needs `collections.read` and keeps only
|
|
69
|
+
slugs the caller can see; `GET /status` lists only those forms.
|
|
70
|
+
- Manager-pushed and sample notifications are written straight to the store, not through `notify()`, so they never
|
|
71
|
+
reach `notification:raised`.
|
|
72
|
+
- A notification with `audience.userIds` is personal and never sent. Form fields: only those the form defines;
|
|
73
|
+
never `password`, `file`, `image`, `hidden`, layout types, or a name like password/secret/token; an object value
|
|
74
|
+
(a file ref) is never sent. A deleted form sends title and link only.
|
|
75
|
+
- `notification:raised` arrives with CMS core's emit (domma-cms PR, notify.js). On an older CMS alerts simply
|
|
76
|
+
do not arrive; forms still do. `_lib/telegram/bot.js` must be in the CMS for the Tool to load at all.
|
|
77
|
+
- Tests: `tests/*.test.js`, Telegram swapped by `setTelegram`; never a real call.
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/* Telegram (and Telegram Pro) admin. Theme tokens only, so light, dark and Theme Roller themes all read right. */
|
|
2
|
+
|
|
3
|
+
.tg [hidden], .tg-panel [hidden] { display: none !important; }
|
|
4
|
+
.tg { max-width: 64rem; display: flex; flex-direction: column; gap: 1rem; }
|
|
5
|
+
.tg-stack { display: flex; flex-direction: column; gap: 1rem; }
|
|
6
|
+
|
|
7
|
+
/* Tabs under the banner */
|
|
8
|
+
.tg-nav { display: flex; flex-wrap: wrap; gap: .15rem; border-bottom: 1px solid var(--dm-border); }
|
|
9
|
+
.tg-nav a { display: inline-flex; align-items: center; gap: .4rem; padding: .5rem .85rem; color: var(--dm-text-secondary); text-decoration: none;
|
|
10
|
+
font-size: var(--dm-font-size-sm); font-weight: 500; border-bottom: 2px solid transparent; margin-bottom: -1px; }
|
|
11
|
+
.tg-nav a:hover { color: var(--dm-text); background: var(--dm-hover-bg); }
|
|
12
|
+
.tg-nav a.is-on { color: var(--dm-primary); border-bottom-color: var(--dm-primary); font-weight: 600; }
|
|
13
|
+
|
|
14
|
+
/* Cards */
|
|
15
|
+
.tg-card { background: var(--dm-surface); border: 1px solid var(--dm-border); border-radius: var(--dm-radius-lg); padding: 1rem 1.1rem;
|
|
16
|
+
display: flex; flex-direction: column; gap: .7rem; min-width: 0; }
|
|
17
|
+
.tg-card > header { display: flex; align-items: center; justify-content: space-between; gap: .5rem; flex-wrap: wrap; }
|
|
18
|
+
.tg-card h3 { margin: 0; font-size: 1.05rem; display: inline-flex; align-items: center; gap: .45rem; }
|
|
19
|
+
.tg-card h4 { margin: .4rem 0 0; font-size: .95rem; display: inline-flex; align-items: center; gap: .4rem; }
|
|
20
|
+
.tg-bar { display: flex; align-items: center; gap: .5rem; flex-wrap: wrap; }
|
|
21
|
+
.tg-spacer { flex: 1; }
|
|
22
|
+
|
|
23
|
+
.tg-note { margin: 0; color: var(--dm-text-secondary); font-size: var(--dm-font-size-sm); }
|
|
24
|
+
.tg-note.is-bad { color: var(--dm-danger); }
|
|
25
|
+
.tg-note.is-warn { color: var(--dm-text); background: color-mix(in srgb, var(--dm-warning) 14%, transparent); border-radius: var(--dm-radius-md); padding: .45rem .7rem; }
|
|
26
|
+
.tg-loading { color: var(--dm-text-secondary); font-size: var(--dm-font-size-sm); padding: .5rem 0; }
|
|
27
|
+
.tg-steps { margin: 0; padding-left: 1.3rem; display: flex; flex-direction: column; gap: .4rem; }
|
|
28
|
+
.tg-code { font-family: var(--dm-font-mono, monospace); padding: .1rem .4rem; border-radius: var(--dm-radius-md);
|
|
29
|
+
background: color-mix(in srgb, var(--dm-text-secondary) 14%, transparent); user-select: all; }
|
|
30
|
+
.tg-token { display: flex; gap: .5rem; flex-wrap: wrap; }
|
|
31
|
+
.tg-token input { flex: 1; min-width: 16rem; font-family: var(--dm-font-mono, monospace); }
|
|
32
|
+
|
|
33
|
+
.tg-chip { font-size: var(--dm-font-size-xs); font-weight: 600; padding: .12rem .55rem; border-radius: var(--dm-radius-full); white-space: nowrap;
|
|
34
|
+
background: color-mix(in srgb, var(--dm-text-secondary) 14%, transparent); color: var(--dm-text); }
|
|
35
|
+
.tg-chip.is-ok { background: color-mix(in srgb, var(--dm-success) 20%, transparent); }
|
|
36
|
+
.tg-chip.is-warn { background: color-mix(in srgb, var(--dm-warning) 22%, transparent); }
|
|
37
|
+
.tg-chip.is-bad { background: color-mix(in srgb, var(--dm-danger) 20%, transparent); }
|
|
38
|
+
|
|
39
|
+
/* Rows (chats; Pro's conversations) */
|
|
40
|
+
.tg-list { display: flex; flex-direction: column; }
|
|
41
|
+
.tg-row { display: flex; align-items: center; gap: .75rem; padding: .6rem .5rem; border-top: 1px solid var(--dm-border); cursor: pointer; border-radius: var(--dm-radius-md); }
|
|
42
|
+
.tg-row:first-child { border-top: 0; }
|
|
43
|
+
.tg-row:hover, .tg-row:focus-visible { background: var(--dm-hover-bg); outline: none; }
|
|
44
|
+
.tg-row.is-on { background: var(--dm-primary-light); }
|
|
45
|
+
.tg-main { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: .1rem; }
|
|
46
|
+
.tg-main strong { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
47
|
+
.tg-main small { color: var(--dm-text-secondary); font-size: var(--dm-font-size-xs); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
48
|
+
.tg-main small.is-bad { color: var(--dm-danger); }
|
|
49
|
+
.tg-kebab { border: 0; background: none; color: var(--dm-text-secondary); cursor: pointer; font-size: 1.1rem; padding: 0 .35rem; border-radius: var(--dm-radius-md); }
|
|
50
|
+
.tg-kebab:hover { background: var(--dm-hover-bg); color: var(--dm-text); }
|
|
51
|
+
.tg-dot { width: .55rem; height: .55rem; border-radius: 50%; background: var(--dm-primary); flex: none; }
|
|
52
|
+
.tg-empty { text-align: center; padding: 2rem 1rem; color: var(--dm-text-secondary); }
|
|
53
|
+
.tg-empty h3 { justify-content: center; margin-bottom: .4rem; color: var(--dm-text); }
|
|
54
|
+
|
|
55
|
+
/* Panels */
|
|
56
|
+
.tg-panel { display: flex; flex-direction: column; gap: .55rem; padding: .25rem 0; }
|
|
57
|
+
.tg-panel fieldset { border: 1px solid var(--dm-border); border-radius: var(--dm-radius-md); padding: .6rem .8rem; margin: 0; display: flex; flex-direction: column; gap: .4rem; }
|
|
58
|
+
.tg-panel legend { font-weight: 600; padding: 0 .3rem; display: inline-flex; align-items: center; gap: .35rem; }
|
|
59
|
+
.tg-check { display: flex; align-items: center; gap: .45rem; font-size: var(--dm-font-size-sm); }
|
|
60
|
+
.tg-checks { display: grid; grid-template-columns: repeat(auto-fill, minmax(12rem, 1fr)); gap: .25rem .8rem; max-height: 14rem; overflow: auto; }
|
|
61
|
+
.tg-checks small { color: var(--dm-text-secondary); }
|
|
62
|
+
.tg-actions { display: flex; gap: .5rem; align-items: center; margin-top: .6rem; }
|
|
63
|
+
|
|
64
|
+
/* Test */
|
|
65
|
+
.tg-test { display: grid; grid-template-columns: minmax(10rem, 16rem) 1fr; gap: .6rem 1rem; align-items: center; }
|
|
66
|
+
@media (max-width: 640px) { .tg-test { grid-template-columns: 1fr; } }
|
|
67
|
+
|
|
68
|
+
.tg .btn { display: inline-flex; align-items: center; gap: .35rem; }
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Telegram admin - display strings and row shapes. PURE (no DOM, no globals), so the views hold observables,
|
|
3
|
+
* bindings and API calls only, and this is tested (tests/arrange.test.js).
|
|
4
|
+
*
|
|
5
|
+
* @module telegram/admin/lib/arrange
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
const SEV_LABEL = {info: 'Info', success: 'Success', warning: 'Warning', critical: 'Critical'};
|
|
9
|
+
const TYPE_LABEL = {private: 'Person', group: 'Group', supergroup: 'Group', channel: 'Channel'};
|
|
10
|
+
|
|
11
|
+
export const severityLabel = (s) => SEV_LABEL[s] || s;
|
|
12
|
+
export const typeLabel = (t) => TYPE_LABEL[t] || 'Chat';
|
|
13
|
+
|
|
14
|
+
const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
|
|
15
|
+
|
|
16
|
+
/** "Warning and critical alerts from every Tool" / "No alerts". */
|
|
17
|
+
export function alertsSummary(alerts, sources = []) {
|
|
18
|
+
if (!alerts?.on || !alerts.severities?.length) return 'No alerts';
|
|
19
|
+
const sev = alerts.severities.map(severityLabel);
|
|
20
|
+
const list = sev.length === 4 ? 'All alerts' : `${sev.length > 1 ? `${sev.slice(0, -1).join(', ')} and ${sev.at(-1).toLowerCase()}` : sev[0]} alerts`;
|
|
21
|
+
if (!alerts.sources?.length) return `${list} from every Tool`;
|
|
22
|
+
const names = alerts.sources.map(id => sources.find(s => s.id === id)?.label || sources.find(s => s.owner === id)?.ownerLabel || id);
|
|
23
|
+
return `${list} from ${names.length <= 2 ? names.join(' and ') : plural(names.length, 'source')}`;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** "Every form, with the answers" / "2 forms, title and link only" / "No forms". */
|
|
27
|
+
export function formsSummary(forms, all = []) {
|
|
28
|
+
if (!forms?.on || (!forms.all && !forms.slugs?.length)) return 'No forms';
|
|
29
|
+
const how = forms.detail === 'title' ? 'title and link only' : 'with the answers';
|
|
30
|
+
if (forms.all) return `Every form, ${how}`;
|
|
31
|
+
const names = forms.slugs.map(s => all.find(f => f.slug === s)?.title || s);
|
|
32
|
+
return `${names.length <= 2 ? names.join(' and ') : plural(names.length, 'form')}, ${how}`;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** One row of the Chats list. */
|
|
36
|
+
export function chatRow(c, {sources = [], forms = []} = {}) {
|
|
37
|
+
return {
|
|
38
|
+
id: c.id,
|
|
39
|
+
name: c.name,
|
|
40
|
+
type: typeLabel(c.type),
|
|
41
|
+
alerts: alertsSummary(c.alerts, sources),
|
|
42
|
+
forms: formsSummary(c.forms, forms),
|
|
43
|
+
paused: Boolean(c.paused),
|
|
44
|
+
problem: c.lastError ? `Last message not sent: ${c.lastError}` : '',
|
|
45
|
+
owner: c.ownerName ? `Gets what ${c.ownerName} may see` : 'No owner - open it and save to choose what it gets',
|
|
46
|
+
title: `${c.name} - ${typeLabel(c.type)}`
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** The Connection tab's state, from GET /status. */
|
|
51
|
+
export function connectionView(st = {}) {
|
|
52
|
+
const w = st.webhook || null;
|
|
53
|
+
let hook = '';
|
|
54
|
+
if (st.connected && w) {
|
|
55
|
+
if (w.error) hook = `Telegram did not answer: ${w.error}`;
|
|
56
|
+
else if (!w.ours) hook = w.url ? 'The bot now sends its messages somewhere else - another Tool or site took it over. Connect it again, or use a second bot.' : 'The bot has no webhook - connect it again.';
|
|
57
|
+
else if (w.lastError && w.lastErrorAt && Date.now() - Date.parse(w.lastErrorAt) < 3600_000) hook = `Telegram could not reach this site: ${w.lastError}`;
|
|
58
|
+
}
|
|
59
|
+
return {
|
|
60
|
+
connected: Boolean(st.connected),
|
|
61
|
+
botAt: st.botName ? `@${st.botName}` : '',
|
|
62
|
+
botLink: st.botName ? `https://t.me/${st.botName}` : '',
|
|
63
|
+
base: st.base || '',
|
|
64
|
+
hookError: hook,
|
|
65
|
+
pending: w?.pending ? plural(w.pending, 'update') + ' waiting' : '',
|
|
66
|
+
chats: plural((st.chats || []).length, 'linked chat'),
|
|
67
|
+
manage: Boolean(st.can?.manage)
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** The "Link a chat" steps. */
|
|
72
|
+
export function linkView(st = {}) {
|
|
73
|
+
const code = st.linkCode || '';
|
|
74
|
+
return {code, line: code ? `/link ${code}` : '', until: st.linkCodeUntil || ''};
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** The routing panel's starting values, as strings and booleans the bindings can hold. */
|
|
78
|
+
export function routingDraft(c, {sources = [], forms = []} = {}) {
|
|
79
|
+
return {
|
|
80
|
+
name: c.name || '',
|
|
81
|
+
alertsOn: Boolean(c.alerts?.on),
|
|
82
|
+
severities: Object.fromEntries(Object.keys(SEV_LABEL).map(s => [s, (c.alerts?.severities || []).includes(s)])),
|
|
83
|
+
allSources: !(c.alerts?.sources || []).length,
|
|
84
|
+
sources: Object.fromEntries(sources.map(s => [s.id, (c.alerts?.sources || []).includes(s.id)])),
|
|
85
|
+
formsOn: Boolean(c.forms?.on),
|
|
86
|
+
allForms: Boolean(c.forms?.all),
|
|
87
|
+
forms: Object.fromEntries(forms.map(f => [f.slug, (c.forms?.slugs || []).includes(f.slug)])),
|
|
88
|
+
detail: c.forms?.detail === 'title' ? 'title' : 'fields'
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** The routing panel's values -> the PUT /chats/:id body. */
|
|
93
|
+
export function routingBody(d) {
|
|
94
|
+
const picked = (o) => Object.entries(o || {}).filter(([, v]) => v).map(([k]) => k);
|
|
95
|
+
return {
|
|
96
|
+
name: String(d.name || '').trim(),
|
|
97
|
+
alerts: {on: Boolean(d.alertsOn), severities: picked(d.severities), sources: d.allSources ? [] : picked(d.sources)},
|
|
98
|
+
forms: {on: Boolean(d.formsOn), all: Boolean(d.allForms), slugs: d.allForms ? [] : picked(d.forms), detail: d.detail === 'title' ? 'title' : 'fields'}
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** A fingerprint of routing values, to tell a changed panel from an untouched one. */
|
|
103
|
+
export const routingPrint = (d) => JSON.stringify(routingBody(d));
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Telegram admin - what the screens share (Telegram Pro's too): the admin's helpers loaded at run time (a
|
|
3
|
+
* plugin never imports admin/ statically - the updater replaces it), the API, escaping, slideovers with an
|
|
4
|
+
* unsaved-changes guard, keyboard-friendly rows with a context menu, and per-browser drafts.
|
|
5
|
+
*
|
|
6
|
+
* @module telegram/admin/lib/kit
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
export const BASE = '/api/plugins/telegram';
|
|
10
|
+
const seg = (id) => encodeURIComponent(String(id));
|
|
11
|
+
|
|
12
|
+
let kit = null;
|
|
13
|
+
|
|
14
|
+
/** tool-kit, plugin-chrome, help-popover and loading, once, with stand-ins for an older admin. */
|
|
15
|
+
export function loadKit() {
|
|
16
|
+
if (!kit) {
|
|
17
|
+
kit = Promise.all([
|
|
18
|
+
import('/admin/js/lib/tool-kit.js').catch(() => ({})),
|
|
19
|
+
import('/admin/js/lib/plugin-chrome.js').catch(() => ({})),
|
|
20
|
+
import('/admin/js/lib/help-popover.js').catch(() => ({})),
|
|
21
|
+
import('/admin/js/lib/loading.js').catch(() => ({}))
|
|
22
|
+
]).then(([tk, chrome, help, loading]) => ({
|
|
23
|
+
onceClosed: tk.onceClosed || ((so, fn) => { const c = so.close.bind(so); so.close = (...a) => { const r = c(...a); fn?.(); return r; }; }),
|
|
24
|
+
openMenuAt: tk.openMenuAt || ((el) => {
|
|
25
|
+
const r = el.getBoundingClientRect();
|
|
26
|
+
el.dispatchEvent(new MouseEvent('contextmenu', {bubbles: true, cancelable: true, clientX: r.left, clientY: r.bottom, view: window}));
|
|
27
|
+
}),
|
|
28
|
+
viewLifetime: tk.viewLifetime || (() => ({add() {}, reset() {}, leaving: false})),
|
|
29
|
+
sidebarCount: tk.sidebarCount || ((url) => { try { window.dispatchEvent(new CustomEvent('dm:sidebar-count', {detail: {url}})); } catch { /* none */ } }),
|
|
30
|
+
addBannerAction: chrome.addBannerAction || (() => null),
|
|
31
|
+
helpPopovers: help.helpPopovers || (() => () => {}),
|
|
32
|
+
whileLoading: loading.whileLoading || ((slot, promise) => promise),
|
|
33
|
+
SHAPES: loading.SHAPES || {}
|
|
34
|
+
}));
|
|
35
|
+
}
|
|
36
|
+
return kit;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export const api = {
|
|
40
|
+
status: () => H.get(`${BASE}/status`),
|
|
41
|
+
connect: (token, base) => H.post(`${BASE}/connect`, {token, base}),
|
|
42
|
+
disconnect: () => H.delete(`${BASE}/connection`),
|
|
43
|
+
linkCode: () => H.post(`${BASE}/link-code`, {}),
|
|
44
|
+
saveChat: (id, body) => H.put(`${BASE}/chats/${seg(id)}`, body),
|
|
45
|
+
unlink: (id) => H.delete(`${BASE}/chats/${seg(id)}`),
|
|
46
|
+
test: (body) => H.post(`${BASE}/test`, body)
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
/** For E.confirm / E.prompt / panel HTML. Not for E.toast (it sets textContent). */
|
|
50
|
+
export const esc = (s) => String(s ?? '').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''');
|
|
51
|
+
|
|
52
|
+
/** Markup we wrote ourselves into one element (values reach it only through bindings). */
|
|
53
|
+
export function fragment(html) {
|
|
54
|
+
const t = document.createElement('template');
|
|
55
|
+
t.innerHTML = html.trim();
|
|
56
|
+
return t.content.firstElementChild;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Copy text, and say so. */
|
|
60
|
+
export function copy(text, what = 'Copied') {
|
|
61
|
+
navigator.clipboard?.writeText(text).then(() => E.toast(`${what}.`, {type: 'success'}), () => E.toast(text));
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Run on the next task: a menu item picked with Enter that asks something must not hand it that Enter. */
|
|
65
|
+
const soon = (fn) => (...a) => setTimeout(() => fn(...a), 0);
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* A bound slideover. `dirty()` true makes closing ask first ("Discard your changes?"); `busy()` true holds it
|
|
69
|
+
* open while a save runs. `close(true)` closes without asking (after a save, or when the screen goes).
|
|
70
|
+
*/
|
|
71
|
+
export async function openPanel({title, size = 'md', html, model = {}, methods = {}, dirty, busy, cleanup = () => {}}) {
|
|
72
|
+
const {onceClosed, helpPopovers} = await loadKit();
|
|
73
|
+
const so = E.slideover({title: esc(title), size, position: 'right'});
|
|
74
|
+
const panel = fragment(html);
|
|
75
|
+
so.element.appendChild(panel);
|
|
76
|
+
// Help markers and icons before the bindings: data-bind-hidden keeps them in place, data-if would not.
|
|
77
|
+
const disposeHelp = helpPopovers(panel, {position: 'bottom'});
|
|
78
|
+
I.scan(panel);
|
|
79
|
+
const handle = M.applyBindings(model, panel, {methods});
|
|
80
|
+
const onUnload = (e) => { if (dirty?.()) { e.preventDefault(); e.returnValue = ''; } };
|
|
81
|
+
window.addEventListener('beforeunload', onUnload);
|
|
82
|
+
onceClosed(so, () => { window.removeEventListener('beforeunload', onUnload); cleanup(); handle.dispose(); disposeHelp(); });
|
|
83
|
+
const close = so.close.bind(so);
|
|
84
|
+
let closed = false;
|
|
85
|
+
let asking = false;
|
|
86
|
+
so.close = async (force) => {
|
|
87
|
+
if (closed) return undefined;
|
|
88
|
+
if (force !== true) {
|
|
89
|
+
if (busy?.() || asking) return undefined;
|
|
90
|
+
if (dirty?.()) {
|
|
91
|
+
asking = true;
|
|
92
|
+
await new Promise(r => setTimeout(r, 0));
|
|
93
|
+
const ok = await E.confirm('Discard your changes?', {title: 'Unsaved changes', confirmText: 'Discard', cancelText: 'Keep editing'});
|
|
94
|
+
asking = false;
|
|
95
|
+
if (!ok || closed) return undefined;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
closed = true;
|
|
99
|
+
return close();
|
|
100
|
+
};
|
|
101
|
+
panel.addEventListener('keydown', (e) => {
|
|
102
|
+
if ((e.ctrlKey || e.metaKey) && (e.key === 'Enter' || e.key === 's') && methods.save) { e.preventDefault(); e.stopPropagation(); methods.save(); }
|
|
103
|
+
});
|
|
104
|
+
so.open();
|
|
105
|
+
return {so, panel, close: (force) => so.close(force)};
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const FIELDS = 'input, textarea, select';
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Rows: click (or Enter) = the main action; right-click, the kebab or Shift+F10 = the menu; arrow keys move.
|
|
112
|
+
* `items(id)` builds the menu for a row; `scope` receives the teardown.
|
|
113
|
+
*/
|
|
114
|
+
export function wireRows(list, {items, main, openMenuAt, scope, match = '.tg-row', kebab = '.tg-kebab'}) {
|
|
115
|
+
const deferred = (xs) => (xs || []).map(x => ({...x, ...(typeof x.action === 'function' ? {action: soon(x.action)} : {})}));
|
|
116
|
+
const menu = E.contextMenu(list, {cursor: 'glyph', match, exclude: FIELDS, inherit: false, density: 'compact', keyboardTrigger: false,
|
|
117
|
+
items: (row) => deferred(items(row.dataset.id))});
|
|
118
|
+
const onClick = (e) => {
|
|
119
|
+
const row = e.target.closest(match);
|
|
120
|
+
if (!row || !list.contains(row) || e.target.closest(FIELDS)) return;
|
|
121
|
+
const k = e.target.closest(kebab);
|
|
122
|
+
if (k) { openMenuAt(k); return; }
|
|
123
|
+
main(row.dataset.id);
|
|
124
|
+
};
|
|
125
|
+
const onKey = (e) => {
|
|
126
|
+
const row = e.target.closest(match);
|
|
127
|
+
if (!row || !list.contains(row)) return;
|
|
128
|
+
if (e.key === 'F10' && e.shiftKey) {
|
|
129
|
+
e.preventDefault();
|
|
130
|
+
e.stopPropagation();
|
|
131
|
+
openMenuAt(row.querySelector(kebab) || row);
|
|
132
|
+
} else if (e.key === 'Enter' && e.target === row) {
|
|
133
|
+
e.preventDefault();
|
|
134
|
+
e.stopPropagation();
|
|
135
|
+
const id = row.dataset.id;
|
|
136
|
+
setTimeout(() => main(id), 0);
|
|
137
|
+
} else if ((e.key === 'ArrowDown' || e.key === 'ArrowUp') && e.target === row) {
|
|
138
|
+
e.preventDefault();
|
|
139
|
+
const rows = [...list.querySelectorAll(match)].filter(r => r.offsetParent);
|
|
140
|
+
rows[rows.indexOf(row) + (e.key === 'ArrowDown' ? 1 : -1)]?.focus();
|
|
141
|
+
}
|
|
142
|
+
};
|
|
143
|
+
list.addEventListener('click', onClick);
|
|
144
|
+
list.addEventListener('keydown', onKey);
|
|
145
|
+
scope(() => { list.removeEventListener('click', onClick); list.removeEventListener('keydown', onKey); menu?.destroy?.(); });
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** Per-browser drafts (S): unsaved work kept when the screen is left, offered back on return. Never secrets. */
|
|
149
|
+
export const drafts = {
|
|
150
|
+
get(key) { try { return S.get(key) || null; } catch { return null; } },
|
|
151
|
+
set(key, value) { try { S.set(key, value); } catch { /* a convenience */ } },
|
|
152
|
+
drop(key) { try { S.remove ? S.remove(key) : S.set(key, null); } catch { /* none */ } }
|
|
153
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
<div class="tg" data-tg-admin></div>
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Telegram › Chats - the linked chats and what each gets.
|
|
3
|
+
*
|
|
4
|
+
* A chat is linked from Telegram itself: the admin makes a one-time code here, someone sends "/link <code>" in
|
|
5
|
+
* the chat (a group with the bot added, or a private chat with the bot), and the chat appears in the list.
|
|
6
|
+
* Click a row (or Enter) for its routing; right-click, the kebab or Shift+F10 for the rest (test, pause, unlink).
|
|
7
|
+
*
|
|
8
|
+
* The routing panel is a bound slideover: closing it with changes asks first, and leaving the screen keeps the
|
|
9
|
+
* changes as a draft (per browser), offered back when that chat is opened again.
|
|
10
|
+
*/
|
|
11
|
+
import {api, copy, drafts, esc, openPanel, wireRows} from '../lib/kit.js';
|
|
12
|
+
import {chatRow, linkView, routingBody, routingDraft, routingPrint, severityLabel} from '../lib/arrange.js';
|
|
13
|
+
|
|
14
|
+
const ROW = `
|
|
15
|
+
<div class="tg-row" data-id="{{id}}" tabindex="0" role="button" data-bind-title="title">
|
|
16
|
+
<span class="tg-chip">{{type}}</span>
|
|
17
|
+
<span class="tg-main"><strong>{{name}}</strong><small>{{alerts}} · {{forms}}</small><small>{{owner}}</small><small class="is-bad" data-bind-hidden="!problem">{{problem}}</small></span>
|
|
18
|
+
<span class="tg-chip is-warn" data-bind-hidden="!paused">Paused</span>
|
|
19
|
+
<button type="button" class="tg-kebab" aria-label="Chat actions" title="Actions">⋮</button>
|
|
20
|
+
</div>`;
|
|
21
|
+
|
|
22
|
+
const DRAFT = (id) => `telegram.draft.chat.${id}`;
|
|
23
|
+
|
|
24
|
+
export async function mount(root, ctx) {
|
|
25
|
+
const {kit, scope, here, status} = ctx;
|
|
26
|
+
const rows = M.observable([]);
|
|
27
|
+
const link = M.observable(linkView(status.peek()));
|
|
28
|
+
const s = () => status.peek() || {};
|
|
29
|
+
const manage = Boolean(s().can?.manage);
|
|
30
|
+
const connected = M.observable(Boolean(s().connected));
|
|
31
|
+
const botAt = M.observable('');
|
|
32
|
+
const making = M.observable(false);
|
|
33
|
+
const stop = M.effect(() => {
|
|
34
|
+
const st = status.value || {};
|
|
35
|
+
rows.value = (st.chats || []).map(c => chatRow(c, st));
|
|
36
|
+
link.value = linkView(st);
|
|
37
|
+
connected.value = Boolean(st.connected);
|
|
38
|
+
botAt.value = st.botName ? `@${st.botName}` : '';
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
root.innerHTML = `<div class="tg-stack">
|
|
42
|
+
<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>
|
|
43
|
+
<section class="tg-card" data-bind-hidden="!connected.value">
|
|
44
|
+
<header><h3><span data-icon="users" data-icon-size="16"></span> Linked chats <span data-help-title="Linked chats" data-help="Each chat linked here gets messages from the site: a group (your team's) or a private chat with the bot (one person's). Each has its own choice of alerts and forms - click a chat to change it. Only a chat linked with a code from this screen ever gets anything."></span></h3>
|
|
45
|
+
${manage ? '<button type="button" class="btn btn-sm btn-primary" data-on-click="code" data-bind-disabled="making.value"><span data-icon="plus" data-icon-size="13"></span> Link a chat</button>' : ''}</header>
|
|
46
|
+
|
|
47
|
+
<div class="tg-note is-warn" data-bind-hidden="!link.value.code">
|
|
48
|
+
<ol class="tg-steps">
|
|
49
|
+
<li>In Telegram, add <b data-bind-text="botAt.value"></b> to the group (or open a private chat with it).</li>
|
|
50
|
+
<li>Send this in that chat: <code class="tg-code" data-bind-text="link.value.line"></code> <button type="button" class="btn btn-xs btn-ghost" data-on-click="copyCode">Copy</button></li>
|
|
51
|
+
<li>Click <b>Check</b>. The code works once, for 15 minutes.</li>
|
|
52
|
+
</ol>
|
|
53
|
+
<div class="tg-bar"><button type="button" class="btn btn-sm btn-primary" data-on-click="check">Check</button>
|
|
54
|
+
<span data-help="Anyone in a chat linked with this code reads what is routed to it, so send it only in a chat your team trusts. A few wrong codes in a row cancel it; make another one here."></span></div>
|
|
55
|
+
</div>
|
|
56
|
+
|
|
57
|
+
<div class="tg-empty" data-bind-hidden="rows.value.length"><h3><span data-icon="message-circle" data-icon-size="18"></span> No chats yet</h3>
|
|
58
|
+
<p>Link your team's Telegram group, or your own chat with the bot, and the site's warnings and form submissions arrive there.</p></div>
|
|
59
|
+
<div class="tg-list" data-bind-hidden="!rows.value.length" data-each="rows.value key=id"></div>
|
|
60
|
+
</section></div>`;
|
|
61
|
+
const view = root.firstElementChild;
|
|
62
|
+
const list = view.querySelector('.tg-list');
|
|
63
|
+
list.innerHTML = ROW;
|
|
64
|
+
scope(kit.helpPopovers(view, {position: 'bottom'}));
|
|
65
|
+
I.scan(view);
|
|
66
|
+
|
|
67
|
+
const panels = new Map();
|
|
68
|
+
scope(() => { for (const p of panels.values()) p.leave(); panels.clear(); });
|
|
69
|
+
|
|
70
|
+
const run = async (fn, said) => {
|
|
71
|
+
try {
|
|
72
|
+
const next = await fn();
|
|
73
|
+
ctx.take(next);
|
|
74
|
+
if (said && here()) E.toast(said, {type: 'success'});
|
|
75
|
+
return next;
|
|
76
|
+
} catch (err) { E.toast(err.message || String(err), {type: 'error'}); return null; }
|
|
77
|
+
};
|
|
78
|
+
const chat = (id) => (s().chats || []).find(c => c.id === id);
|
|
79
|
+
|
|
80
|
+
async function test(id) {
|
|
81
|
+
try { await api.test({chat: id, kind: 'hello'}); E.toast('Sent - look in that chat.', {type: 'success'}); } catch (err) { E.toast(err.message || String(err), {type: 'error'}); }
|
|
82
|
+
}
|
|
83
|
+
async function unlink(id) {
|
|
84
|
+
const c = chat(id);
|
|
85
|
+
if (!c) return;
|
|
86
|
+
const ok = await E.confirm(`Unlink <b>${esc(c.name)}</b>? It stops getting messages from the site, and the chat is told so.`,
|
|
87
|
+
{title: 'Unlink the chat', confirmText: 'Unlink', cancelText: 'Keep it'});
|
|
88
|
+
if (ok && here()) await run(() => api.unlink(id), 'Unlinked.');
|
|
89
|
+
}
|
|
90
|
+
const pause = (id) => { const c = chat(id); if (c) run(() => api.saveChat(id, {paused: !c.paused}), c.paused ? 'Resumed.' : 'Paused - nothing is sent there until you resume it.'); };
|
|
91
|
+
|
|
92
|
+
async function edit(id) {
|
|
93
|
+
const c = chat(id);
|
|
94
|
+
if (!c || panels.has(id)) return;
|
|
95
|
+
if (!manage) { E.toast('Only an administrator can change what a chat gets.', {type: 'info'}); return; }
|
|
96
|
+
const st = s();
|
|
97
|
+
const loaded = routingDraft(c, st);
|
|
98
|
+
let start = loaded;
|
|
99
|
+
const kept = drafts.get(DRAFT(id));
|
|
100
|
+
if (kept?.values && routingPrint(kept.values) !== routingPrint(loaded)) {
|
|
101
|
+
const use = await E.confirm(`You left changes to <b>${esc(c.name)}</b> unsaved. Use them?`, {title: 'Unsaved changes', confirmText: 'Use them', cancelText: 'Throw them away'});
|
|
102
|
+
if (!here()) return;
|
|
103
|
+
if (use) start = {...loaded, ...kept.values};
|
|
104
|
+
}
|
|
105
|
+
drafts.drop(DRAFT(id));
|
|
106
|
+
|
|
107
|
+
const name = M.observable(start.name);
|
|
108
|
+
const alertsOn = M.observable(start.alertsOn);
|
|
109
|
+
const sev = Object.fromEntries(Object.entries(start.severities).map(([k, v]) => [k, M.observable(v)]));
|
|
110
|
+
const allSources = M.observable(start.allSources);
|
|
111
|
+
const sources = (st.sources || []).map(x => ({id: x.id, label: x.label, group: x.ownerLabel, on: M.observable(Boolean(start.sources[x.id]))}));
|
|
112
|
+
const formsOn = M.observable(start.formsOn);
|
|
113
|
+
const allForms = M.observable(start.allForms);
|
|
114
|
+
const forms = (st.forms || []).map(f => ({id: f.slug, label: f.title, on: M.observable(Boolean(start.forms[f.slug]))}));
|
|
115
|
+
const detail = M.observable(start.detail);
|
|
116
|
+
const saving = M.observable(false);
|
|
117
|
+
const values = () => ({
|
|
118
|
+
name: name.peek(), alertsOn: alertsOn.peek(),
|
|
119
|
+
severities: Object.fromEntries(Object.entries(sev).map(([k, o]) => [k, o.peek()])),
|
|
120
|
+
allSources: allSources.peek(), sources: Object.fromEntries(sources.map(x => [x.id, x.on.peek()])),
|
|
121
|
+
formsOn: formsOn.peek(), allForms: allForms.peek(), forms: Object.fromEntries(forms.map(f => [f.id, f.on.peek()])),
|
|
122
|
+
detail: detail.peek()
|
|
123
|
+
});
|
|
124
|
+
const was = routingPrint(loaded);
|
|
125
|
+
const dirty = () => routingPrint(values()) !== was;
|
|
126
|
+
|
|
127
|
+
const html = `<div class="tg-panel">
|
|
128
|
+
<label class="form-label" for="tg-chat-name">Name in this admin <span data-help="Only for you: how this chat is listed here. Telegram does not see it."></span></label>
|
|
129
|
+
<input id="tg-chat-name" class="form-input" maxlength="80" data-model="name.value">
|
|
130
|
+
|
|
131
|
+
<fieldset><legend><label class="tg-check"><input type="checkbox" class="form-checkbox" data-model="alertsOn.value"> Alerts</label>
|
|
132
|
+
<span data-help-title="Alerts" data-help="The notifications the site raises in the bell - a payment failed, the disk is filling, a Tool stopped. Choose how serious they must be, and from which Tools. Notifications meant for one named person (a to-do reminder) are never sent to a chat."></span></legend>
|
|
133
|
+
<div data-bind-hidden="!alertsOn.value" class="tg-stack">
|
|
134
|
+
<div class="tg-bar">${Object.keys(sev).map(k => `<label class="tg-check"><input type="checkbox" class="form-checkbox" data-model="sev.${k}.value"> ${severityLabel(k)}</label>`).join('')}</div>
|
|
135
|
+
<label class="tg-check"><input type="checkbox" class="form-checkbox" data-model="allSources.value"> From every Tool</label>
|
|
136
|
+
<div class="tg-checks" data-bind-hidden="allSources.value" data-each="sourceList.value key=id"><label class="tg-check"><input type="checkbox" class="form-checkbox" data-model="on.value"> <span>{{label}} <small>{{group}}</small></span></label></div>
|
|
137
|
+
</div>
|
|
138
|
+
</fieldset>
|
|
139
|
+
|
|
140
|
+
<fieldset><legend><label class="tg-check"><input type="checkbox" class="form-checkbox" data-model="formsOn.value"> Form submissions</label>
|
|
141
|
+
<span data-help-title="Form submissions" data-help="Each time a visitor sends one of the chosen forms, this chat gets a message with the form's title and a link to its submissions. Passwords, files, images and hidden fields are never sent."></span></legend>
|
|
142
|
+
<div data-bind-hidden="!formsOn.value" class="tg-stack">
|
|
143
|
+
<label class="tg-check"><input type="checkbox" class="form-checkbox" data-model="allForms.value"> Every form, including new ones</label>
|
|
144
|
+
<div class="tg-checks" data-bind-hidden="allForms.value" data-each="formList.value key=id"><label class="tg-check"><input type="checkbox" class="form-checkbox" data-model="on.value"> <span>{{label}}</span></label></div>
|
|
145
|
+
<p class="tg-note" data-bind-hidden="allForms.value || formList.value.length">There are no forms on this site yet.</p>
|
|
146
|
+
<label class="form-label">What the message holds <span data-help="With the answers: each question and what the visitor typed, so the team can act from Telegram. Title and link only: just which form was sent, with a link to read it in the admin - nothing the visitor typed leaves the site."></span></label>
|
|
147
|
+
<label class="tg-check"><input type="radio" name="tg-detail" value="fields" data-model="detail.value"> The form's title, the answers and a link</label>
|
|
148
|
+
<label class="tg-check"><input type="radio" name="tg-detail" value="title" data-model="detail.value"> The form's title and a link only</label>
|
|
149
|
+
</div>
|
|
150
|
+
</fieldset>
|
|
151
|
+
|
|
152
|
+
<div class="tg-actions">
|
|
153
|
+
<span class="tg-spacer"></span>
|
|
154
|
+
<button type="button" class="btn btn-sm btn-ghost" data-on-click="cancel">Cancel</button>
|
|
155
|
+
<button type="button" class="btn btn-sm btn-primary" data-on-click="save" data-bind-disabled="saving.value">Save</button>
|
|
156
|
+
</div>
|
|
157
|
+
</div>`;
|
|
158
|
+
let panel = null;
|
|
159
|
+
const entry = {
|
|
160
|
+
/** The screen has gone: keep the changes as a draft, close without asking. */
|
|
161
|
+
leave() { if (dirty()) drafts.set(DRAFT(id), {values: values(), at: Date.now()}); panel?.close(true); }
|
|
162
|
+
};
|
|
163
|
+
panels.set(id, entry);
|
|
164
|
+
const methods = {
|
|
165
|
+
cancel: () => panel?.close(),
|
|
166
|
+
async save() {
|
|
167
|
+
if (saving.peek()) return;
|
|
168
|
+
saving.value = true;
|
|
169
|
+
try {
|
|
170
|
+
const next = await api.saveChat(id, routingBody(values()));
|
|
171
|
+
ctx.take(next);
|
|
172
|
+
E.toast('Saved.', {type: 'success'});
|
|
173
|
+
panel?.close(true);
|
|
174
|
+
} catch (err) {
|
|
175
|
+
E.toast(`Not saved: ${err.message || err}`, {type: 'error'});
|
|
176
|
+
} finally {
|
|
177
|
+
saving.value = false;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
};
|
|
181
|
+
try {
|
|
182
|
+
panel = await openPanel({title: c.name, size: 'md', html, methods, dirty, busy: () => saving.peek(),
|
|
183
|
+
model: {name, alertsOn, sev, allSources, sourceList: M.observable(sources), formsOn, allForms, formList: M.observable(forms), detail, saving},
|
|
184
|
+
cleanup: () => panels.delete(id)});
|
|
185
|
+
} catch (err) {
|
|
186
|
+
panels.delete(id);
|
|
187
|
+
E.toast(`Not opened: ${err.message || err}`, {type: 'error'});
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const bindings = M.applyBindings({rows, link, connected, botAt, making}, view, {
|
|
192
|
+
methods: {
|
|
193
|
+
async code() {
|
|
194
|
+
making.value = true;
|
|
195
|
+
await run(() => api.linkCode());
|
|
196
|
+
making.value = false;
|
|
197
|
+
},
|
|
198
|
+
copyCode: () => copy(link.peek().line, 'Copied'),
|
|
199
|
+
async check() {
|
|
200
|
+
const before = (s().chats || []).length;
|
|
201
|
+
const next = await run(() => ctx.reload());
|
|
202
|
+
if (!next) return;
|
|
203
|
+
if ((next.chats || []).length > before) E.toast('Linked.', {type: 'success'});
|
|
204
|
+
else E.toast(next.linkCode ? 'Not linked yet - send the /link line in the chat first.' : 'The code was used or has run out - make a new one.', {type: 'warning'});
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
});
|
|
208
|
+
wireRows(list, {
|
|
209
|
+
scope, openMenuAt: kit.openMenuAt, main: edit,
|
|
210
|
+
items: (id) => {
|
|
211
|
+
const c = chat(id);
|
|
212
|
+
if (!c) return [];
|
|
213
|
+
return manage ? [
|
|
214
|
+
{label: 'What it gets…', icon: 'sliders', action: () => edit(id)},
|
|
215
|
+
{label: 'Send a test', icon: 'send', action: () => test(id)},
|
|
216
|
+
{label: c.paused ? 'Resume' : 'Pause', icon: c.paused ? 'play' : 'pause', action: () => pause(id)},
|
|
217
|
+
{type: 'divider'},
|
|
218
|
+
{label: 'Unlink…', icon: 'x', action: () => unlink(id)}
|
|
219
|
+
] : [{label: 'Only an administrator can change chats', disabled: true}];
|
|
220
|
+
}
|
|
221
|
+
});
|
|
222
|
+
return () => { bindings.dispose(); stop(); };
|
|
223
|
+
}
|