chirkle 0.0.0-stage → 0.2.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/LICENSE +674 -0
- package/README.md +326 -2
- package/package.json +76 -4
- package/pb_hooks/federation/config.js +276 -0
- package/pb_hooks/federation/inbox.js +316 -0
- package/pb_hooks/federation/messages.js +420 -0
- package/pb_hooks/federation/mirror.js +277 -0
- package/pb_hooks/federation/net.js +247 -0
- package/pb_hooks/federation/peers.js +490 -0
- package/pb_hooks/federation/people.js +376 -0
- package/pb_hooks/federation/rooms.js +552 -0
- package/pb_hooks/federation/worker.js +413 -0
- package/pb_hooks/federation.pb.js +141 -0
- package/pb_hooks/lib/access.js +102 -0
- package/pb_hooks/lib/account.js +31 -0
- package/pb_hooks/lib/anonymous.js +189 -0
- package/pb_hooks/lib/bulk.js +187 -0
- package/pb_hooks/lib/collections.js +587 -0
- package/pb_hooks/lib/dms.js +123 -0
- package/pb_hooks/lib/emoji.js +28 -0
- package/pb_hooks/lib/enrich.js +75 -0
- package/pb_hooks/lib/features.js +31 -0
- package/pb_hooks/lib/files.js +375 -0
- package/pb_hooks/lib/http.js +146 -0
- package/pb_hooks/lib/images.js +160 -0
- package/pb_hooks/lib/keepalive.js +31 -0
- package/pb_hooks/lib/lists.js +173 -0
- package/pb_hooks/lib/media.js +635 -0
- package/pb_hooks/lib/messages.js +519 -0
- package/pb_hooks/lib/moderation.js +128 -0
- package/pb_hooks/lib/outbound.js +116 -0
- package/pb_hooks/lib/pages.js +171 -0
- package/pb_hooks/lib/previews.js +346 -0
- package/pb_hooks/lib/reactions.js +110 -0
- package/pb_hooks/lib/reads.js +181 -0
- package/pb_hooks/lib/records.js +77 -0
- package/pb_hooks/lib/rooms.js +148 -0
- package/pb_hooks/lib/site.js +102 -0
- package/pb_hooks/lib/text.js +110 -0
- package/pb_hooks/lib/users.js +81 -0
- package/pb_hooks/lib/worker.js +159 -0
- package/pb_hooks/main.pb.js +324 -0
- package/pb_hooks/telegram/api.js +129 -0
- package/pb_hooks/telegram/inbound.js +553 -0
- package/pb_hooks/telegram/links.js +157 -0
- package/pb_hooks/telegram/outbound.js +352 -0
- package/pb_hooks/telegram/people.js +166 -0
- package/pb_hooks/telegram/reactions.js +137 -0
- package/pb_hooks/telegram/rich.js +192 -0
- package/pb_hooks/telegram/worker.js +182 -0
- package/pb_hooks/telegram.pb.js +47 -0
- package/pb_migrations/1760000000_init.js +150 -0
- package/pb_migrations/1760000001_qa_fixes.js +69 -0
- package/pb_migrations/1760000002_avatars.js +39 -0
- package/pb_migrations/1760000003_direct_messages.js +142 -0
- package/pb_migrations/1760000004_attachments.js +28 -0
- package/pb_migrations/1760000005_file_names.js +16 -0
- package/pb_migrations/1760000006_room_reads.js +41 -0
- package/pb_migrations/1760000007_replies.js +23 -0
- package/pb_migrations/1760000008_lowercase_emails.js +24 -0
- package/pb_migrations/1760000009_reactions.js +32 -0
- package/pb_migrations/1760000010_fit_thumbs.js +18 -0
- package/pb_migrations/1760000011_forwarding.js +39 -0
- package/pb_migrations/1760000012_accounts.js +55 -0
- package/pb_migrations/1760000013_qa_pass5.js +19 -0
- package/pb_migrations/1760000014_room_access.js +96 -0
- package/pb_migrations/1760000015_site.js +46 -0
- package/pb_migrations/1760000016_forward_refs.js +43 -0
- package/pb_migrations/1760000017_no_dms.js +18 -0
- package/pb_migrations/1760000018_attachment_limits.js +24 -0
- package/pb_migrations/1760000019_telegram.js +109 -0
- package/pb_migrations/1760000020_service_messages.js +21 -0
- package/pb_migrations/1760000021_forward_view_index.js +41 -0
- package/pb_migrations/1760000022_link_previews.js +43 -0
- package/pb_migrations/1760000023_room_writers.js +49 -0
- package/pb_migrations/1760000024_message_search.js +51 -0
- package/pb_migrations/1760000025_search_dotted_i.js +16 -0
- package/pb_migrations/1760000026_push.js +67 -0
- package/pb_migrations/1760000027_push_tokens_per_user.js +31 -0
- package/pb_migrations/1760000028_media_grid_thumbs.js +18 -0
- package/pb_migrations/1760000029_media.js +71 -0
- package/pb_migrations/1760000030_collections.js +140 -0
- package/pb_migrations/1760000031_unread_limit.js +20 -0
- package/pb_migrations/1760000032_federation.js +227 -0
- package/pb_migrations/1760000033_federation_requests.js +44 -0
- package/pb_migrations/1760000034_telegram_parts.js +26 -0
- package/pb_migrations/1760000035_telegram_anonymous.js +16 -0
- package/pb_migrations/1760000036_chirkle.js +20 -0
- package/pb_migrations/1760000037_file_dims.js +35 -0
- package/pb_migrations/1760000038_drop_push.js +64 -0
- package/pb_migrations/1760000039_anonymous_rooms.js +40 -0
- package/pb_migrations/1760000040_moderators.js +42 -0
- package/pb_migrations/1760000041_shared_files.js +500 -0
- package/pb_migrations/1760000042_files_src.js +17 -0
- package/pb_migrations/1760000043_telegram_reactions.js +21 -0
- package/pb_public/assets/access-ALBW2MT2.js +2 -0
- package/pb_public/assets/access-ALBW2MT2.js.map +7 -0
- package/pb_public/assets/access-PB77EH4F.css +2 -0
- package/pb_public/assets/access-PB77EH4F.css.map +7 -0
- package/pb_public/assets/app-A3SXD3FF.css +2 -0
- package/pb_public/assets/app-A3SXD3FF.css.map +7 -0
- package/pb_public/assets/app-NDSIQW4L.js +3 -0
- package/pb_public/assets/app-NDSIQW4L.js.map +7 -0
- package/pb_public/assets/collections-DHJEOLHW.css +2 -0
- package/pb_public/assets/collections-DHJEOLHW.css.map +7 -0
- package/pb_public/assets/emoji-WSTVXAW5.css +2 -0
- package/pb_public/assets/emoji-WSTVXAW5.css.map +7 -0
- package/pb_public/assets/emoji-picker-QYRX6NYL.js +609 -0
- package/pb_public/assets/emoji-picker-QYRX6NYL.js.map +7 -0
- package/pb_public/assets/inter-cyrillic-JEOLYBOO.woff2 +0 -0
- package/pb_public/assets/inter-cyrillic-ext-IYF56FF6.woff2 +0 -0
- package/pb_public/assets/inter-greek-IRE366VL.woff2 +0 -0
- package/pb_public/assets/inter-latin-NRMW37G5.woff2 +0 -0
- package/pb_public/assets/inter-latin-ext-HA22NDSG.woff2 +0 -0
- package/pb_public/assets/lazy-4CXRBHHM.js +2 -0
- package/pb_public/assets/lazy-4CXRBHHM.js.map +7 -0
- package/pb_public/assets/media-7TCBG7WM.css +2 -0
- package/pb_public/assets/media-7TCBG7WM.css.map +7 -0
- package/pb_public/assets/media-FPRU2QH5.js +2 -0
- package/pb_public/assets/media-FPRU2QH5.js.map +7 -0
- package/pb_public/assets/notify-L6GERFNO.js +2 -0
- package/pb_public/assets/notify-L6GERFNO.js.map +7 -0
- package/pb_public/assets/search-3UT4HMES.js +2 -0
- package/pb_public/assets/search-3UT4HMES.js.map +7 -0
- package/pb_public/assets/switcher-CEUKRLEY.js +2 -0
- package/pb_public/assets/switcher-CEUKRLEY.js.map +7 -0
- package/pb_public/assets/viewer-DXT7SKOU.js +2 -0
- package/pb_public/assets/viewer-DXT7SKOU.js.map +7 -0
- package/pb_public/assets/viewer-P7GYCBYM.css +2 -0
- package/pb_public/assets/viewer-P7GYCBYM.css.map +7 -0
- package/pb_public/icons/apple-touch-icon.png +0 -0
- package/pb_public/icons/icon-192.png +0 -0
- package/pb_public/icons/icon-512.png +0 -0
- package/pb_public/icons/icon.svg +1 -0
- package/pb_public/icons/maskable-512.png +0 -0
- package/pb_public/index.html +21 -0
- package/pb_public/sw.js +1 -0
- package/scripts/fetch-pocketbase.sh +63 -0
- package/scripts/start.mjs +93 -0
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
/// <reference path="../../types/pocketbase.d.ts" />
|
|
2
|
+
// Reactions across the bridge (DESIGN.md §26.9). Telegram tells a bot about reactions only where it is an admin
|
|
3
|
+
// (`message_reaction`): each person's change comes over as their stand-in's reaction on the message. The other way, a
|
|
4
|
+
// bot may set one reaction of its own on a message: it shows the one most of the room's own people (not Telegram's
|
|
5
|
+
// stand-ins, whose reactions are in the group already) reacted with, among those Telegram offers.
|
|
6
|
+
|
|
7
|
+
const { call } = require(`${__hooks}/telegram/api.js`);
|
|
8
|
+
const { isReactionEmoji } = require(`${__hooks}/lib/emoji.js`);
|
|
9
|
+
const { reactionsOf, setReaction } = require(`${__hooks}/lib/reactions.js`);
|
|
10
|
+
|
|
11
|
+
const VS16 = "️";
|
|
12
|
+
|
|
13
|
+
/** The emoji Telegram takes as a reaction (Bot API ReactionTypeEmoji), written without variation selectors. */
|
|
14
|
+
const TELEGRAM = new Set(
|
|
15
|
+
(
|
|
16
|
+
"❤ 👍 👎 🔥 🥰 👏 😁 🤔 🤯 😱 🤬 😢 🎉 🤩 🤮 💩 🙏 👌 🕊 🤡 🥱 🥴 😍 🐳 ❤🔥 🌚 🌭 💯 🤣 ⚡ 🍌 🏆 💔 🤨 😐 🍓 🍾 💋 🖕 😈 😴 😭 🤓 👻 " +
|
|
17
|
+
"👨💻 👀 🎃 🙈 😇 😨 🤝 ✍ 🤗 🫡 🎅 🎄 ☃ 💅 🤪 🗿 🆒 💘 🙉 🦄 😘 💊 🙊 😎 👾 🤷♂ 🤷 🤷♀ 😡"
|
|
18
|
+
).split(" "),
|
|
19
|
+
);
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* The picker's emoji (§20.1) for a Telegram reaction, or "" when it has none: "❤" is "❤️", a shrug of either gender is
|
|
23
|
+
* "🤷". Custom and paid reactions have no emoji.
|
|
24
|
+
* @param {any} r ReactionType
|
|
25
|
+
*/
|
|
26
|
+
function fromTelegram(r) {
|
|
27
|
+
if (r?.type !== "emoji" || typeof r.emoji !== "string") return "";
|
|
28
|
+
const bare = r.emoji.replace(/\uFE0F/g, "").replace(/\u200D[♂♀]$/, "");
|
|
29
|
+
return [r.emoji, bare, `${bare}${VS16}`].find((e) => isReactionEmoji(e)) || "";
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Telegram's reaction for one of the picker's emoji, or "" when it has none.
|
|
34
|
+
* @param {string} emoji
|
|
35
|
+
*/
|
|
36
|
+
function toTelegram(emoji) {
|
|
37
|
+
const bare = emoji.replace(/\uFE0F/g, "");
|
|
38
|
+
return TELEGRAM.has(bare) ? bare : "";
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* The bot's reaction on a message: the emoji most of the room's own people reacted with (the first used, of those
|
|
43
|
+
* as many), that Telegram offers; "" for none.
|
|
44
|
+
* @param {core.App} app
|
|
45
|
+
* @param {core.Record} rec
|
|
46
|
+
*/
|
|
47
|
+
function botReaction(app, rec) {
|
|
48
|
+
if (rec.getBool("deleted")) return "";
|
|
49
|
+
const { isStandIn } = require(`${__hooks}/telegram/people.js`);
|
|
50
|
+
/** @type {Map<string, boolean>} */
|
|
51
|
+
const standIns = new Map();
|
|
52
|
+
const ours = (/** @type {string} */ u) => {
|
|
53
|
+
if (!standIns.has(u)) standIns.set(u, isStandIn(app, u));
|
|
54
|
+
return !standIns.get(u);
|
|
55
|
+
};
|
|
56
|
+
let best = "";
|
|
57
|
+
let most = 0;
|
|
58
|
+
for (const r of reactionsOf(rec)) {
|
|
59
|
+
const emoji = toTelegram(r.emoji);
|
|
60
|
+
if (!emoji) continue;
|
|
61
|
+
const n = r.users.filter(ours).length;
|
|
62
|
+
if (n > most) [best, most] = [emoji, n];
|
|
63
|
+
}
|
|
64
|
+
return best;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* A `message_reaction` update: someone's reactions on a message changed. Their stand-in's reactions on the chat message
|
|
69
|
+
* change the same way (those the picker has; the rest are left out).
|
|
70
|
+
* @param {core.App} app
|
|
71
|
+
* @param {any} update MessageReactionUpdated
|
|
72
|
+
*/
|
|
73
|
+
function reactionOver(app, update) {
|
|
74
|
+
const { mapped } = require(`${__hooks}/telegram/inbound.js`);
|
|
75
|
+
const { activeLink, linkOfChat } = require(`${__hooks}/telegram/links.js`);
|
|
76
|
+
if (!update?.chat || update.chat.type === "private" || (!update.user && !update.actor_chat)) return;
|
|
77
|
+
const chatId = String(update.chat.id);
|
|
78
|
+
const link = linkOfChat(app, chatId);
|
|
79
|
+
const room = link && activeLink(app, link);
|
|
80
|
+
if (!room) return;
|
|
81
|
+
const found = mapped(app, chatId, update.message_id);
|
|
82
|
+
if (!found || found.getString("room") !== room.id || !found.getString("author")) return;
|
|
83
|
+
const emojiOf = (/** @type {any} */ list) => new Set((Array.isArray(list) ? list : []).map(fromTelegram).filter(Boolean));
|
|
84
|
+
const was = emojiOf(update.old_reaction);
|
|
85
|
+
const now = emojiOf(update.new_reaction);
|
|
86
|
+
const changes = [
|
|
87
|
+
...[...was].filter((e) => !now.has(e)).map((e) => ({ emoji: e, on: false })),
|
|
88
|
+
...[...now].filter((e) => !was.has(e)).map((e) => ({ emoji: e, on: true })),
|
|
89
|
+
];
|
|
90
|
+
if (!changes.length) return;
|
|
91
|
+
const person = require(`${__hooks}/telegram/people.js`).personOf(app, { from: update.user, sender_chat: update.actor_chat });
|
|
92
|
+
// Read and written in one transaction, as the reactions route does (§20.2): reactions at once all count.
|
|
93
|
+
app.runInTransaction((tx) => {
|
|
94
|
+
const rec = tx.findRecordById("messages", found.id);
|
|
95
|
+
if (rec.getBool("deleted")) return;
|
|
96
|
+
let list = reactionsOf(rec);
|
|
97
|
+
for (const c of changes) list = setReaction(list, c.emoji, person.id, c.on) || list;
|
|
98
|
+
if (JSON.stringify(list) === JSON.stringify(reactionsOf(rec))) return;
|
|
99
|
+
rec.set("reactions", list);
|
|
100
|
+
tx.save(rec);
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Set the bot's reaction on the Telegram message a chat message is (its first, when it is several) to what the
|
|
106
|
+
* message's reactions are now.
|
|
107
|
+
* @param {core.App} app
|
|
108
|
+
* @param {string} messageId
|
|
109
|
+
* @param {string} chatId
|
|
110
|
+
*/
|
|
111
|
+
function react(app, messageId, chatId) {
|
|
112
|
+
const { linkOfChat } = require(`${__hooks}/telegram/links.js`);
|
|
113
|
+
let msg;
|
|
114
|
+
try {
|
|
115
|
+
msg = app.findRecordById("messages", messageId);
|
|
116
|
+
} catch {
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
if (msg.getBool("deleted")) return;
|
|
120
|
+
const link = linkOfChat(app, chatId);
|
|
121
|
+
if (!link?.getBool("enabled") || link.getString("room") !== msg.getString("room")) return;
|
|
122
|
+
const row = app
|
|
123
|
+
.findRecordsByFilter("tg_messages", "message = {:message} && chat_id = {:chat} && part = 0", "tg_message_id", 1, 0, {
|
|
124
|
+
message: messageId,
|
|
125
|
+
chat: chatId,
|
|
126
|
+
})
|
|
127
|
+
.find((r) => !!r);
|
|
128
|
+
if (!row) return;
|
|
129
|
+
const emoji = botReaction(app, msg);
|
|
130
|
+
call("setMessageReaction", {
|
|
131
|
+
chat_id: chatId,
|
|
132
|
+
message_id: row.getInt("tg_message_id"),
|
|
133
|
+
reaction: emoji ? [{ type: "emoji", emoji }] : [],
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
module.exports = { botReaction, fromTelegram, toTelegram, reactionOver, react };
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
/// <reference path="../../types/pocketbase.d.ts" />
|
|
2
|
+
// Telegram rich messages (Bot API 10.1: Message.rich_message) as a chat message (DESIGN.md §26.4). A rich message has
|
|
3
|
+
// no text or caption: its content is a tree of blocks (headings, paragraphs, lists, tables, quotes, media…) holding
|
|
4
|
+
// rich text. The room shows plain text (§5), so the blocks become lines of it, and the media in them become files.
|
|
5
|
+
|
|
6
|
+
/** How deep blocks nest before the rest is left out: Telegram's own are shallow. */
|
|
7
|
+
const MAX_DEPTH = 16;
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Rich text as plain text: a string, an array of rich texts, or a formatted piece (bold, a link…) around one. A link
|
|
11
|
+
* whose text isn't its address keeps the address after it.
|
|
12
|
+
* @param {any} t
|
|
13
|
+
* @returns {string}
|
|
14
|
+
*/
|
|
15
|
+
function plain(t, depth = 0) {
|
|
16
|
+
if (t == null || depth > MAX_DEPTH) return "";
|
|
17
|
+
if (typeof t === "string") return t;
|
|
18
|
+
if (Array.isArray(t)) return t.map((x) => plain(x, depth + 1)).join("");
|
|
19
|
+
switch (t.type) {
|
|
20
|
+
case "custom_emoji":
|
|
21
|
+
return t.alternative_text || "";
|
|
22
|
+
case "mathematical_expression":
|
|
23
|
+
return t.expression || "";
|
|
24
|
+
case "anchor":
|
|
25
|
+
return "";
|
|
26
|
+
case "button":
|
|
27
|
+
return buttonText(t.button);
|
|
28
|
+
case "url": {
|
|
29
|
+
const text = plain(t.text, depth + 1);
|
|
30
|
+
return !t.url || text.trim() === t.url ? text || t.url || "" : `${text} (${t.url})`;
|
|
31
|
+
}
|
|
32
|
+
default:
|
|
33
|
+
return plain(t.text, depth + 1);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* A button that opens a link, as its text and the link; other buttons (callbacks…) only work in Telegram.
|
|
39
|
+
* @param {any} b RichMessageButton
|
|
40
|
+
*/
|
|
41
|
+
function buttonText(b) {
|
|
42
|
+
if (!b?.url) return "";
|
|
43
|
+
const text = plain(b.text).trim();
|
|
44
|
+
return text && text !== b.url ? `[${text}: ${b.url}]` : `[${b.url}]`;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** @param {string} prefix @param {string[]} lines */
|
|
48
|
+
const prefixed = (prefix, lines) => lines.map((l) => `${prefix}${l}`);
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* A caption (RichBlockCaption) and its credit, as lines.
|
|
52
|
+
* @param {any} c
|
|
53
|
+
*/
|
|
54
|
+
function captionLines(c) {
|
|
55
|
+
if (!c) return [];
|
|
56
|
+
return [plain(c.text), c.credit ? `— ${plain(c.credit)}` : ""].filter((l) => l.trim()).flatMap((l) => l.split("\n"));
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* A rich message's blocks as lines of text; the files in them go to `add` (a Telegram file, its name).
|
|
61
|
+
* @param {any[]} blocks
|
|
62
|
+
* @param {number} n the Telegram message's id, for the names of files that have none
|
|
63
|
+
* @param {(f: any, name: string) => void} add
|
|
64
|
+
* @param {string[]} notes what can't be shown as text or a file
|
|
65
|
+
* @returns {string[]}
|
|
66
|
+
*/
|
|
67
|
+
function blockLines(blocks, n, add, notes, depth = 0) {
|
|
68
|
+
if (!Array.isArray(blocks) || depth > MAX_DEPTH) return [];
|
|
69
|
+
/** @type {string[]} */
|
|
70
|
+
const out = [];
|
|
71
|
+
for (const b of blocks) {
|
|
72
|
+
const lines = blockOf(b, n, add, notes, depth);
|
|
73
|
+
// A heading opens a section: a blank line above it, when something came before.
|
|
74
|
+
if (b?.type === "heading" && out.length && out[out.length - 1] !== "") out.push("");
|
|
75
|
+
out.push(...lines);
|
|
76
|
+
}
|
|
77
|
+
return out;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* @param {any} b RichBlock
|
|
82
|
+
* @param {number} n
|
|
83
|
+
* @param {(f: any, name: string) => void} add
|
|
84
|
+
* @param {string[]} notes
|
|
85
|
+
* @param {number} depth
|
|
86
|
+
* @returns {string[]}
|
|
87
|
+
*/
|
|
88
|
+
function blockOf(b, n, add, notes, depth) {
|
|
89
|
+
if (!b) return [];
|
|
90
|
+
const text = (/** @type {any} */ t) => plain(t).split("\n");
|
|
91
|
+
const inner = (/** @type {any[]} */ blocks) => blockLines(blocks, n, add, notes, depth + 1);
|
|
92
|
+
/** A file of the message: its name, numbered when it has none (a message can hold several). */
|
|
93
|
+
const file = (/** @type {any} */ f, /** @type {string} */ kind, /** @type {string} */ ext) => {
|
|
94
|
+
if (f) add(f, f.file_name || `${kind}_${n}_${seq++}.${ext}`);
|
|
95
|
+
return captionLines(b.caption);
|
|
96
|
+
};
|
|
97
|
+
switch (b.type) {
|
|
98
|
+
case "paragraph":
|
|
99
|
+
case "heading":
|
|
100
|
+
case "footer":
|
|
101
|
+
case "pre":
|
|
102
|
+
return text(b.text);
|
|
103
|
+
case "mathematical_expression":
|
|
104
|
+
return (b.expression || "").split("\n");
|
|
105
|
+
case "divider":
|
|
106
|
+
return ["———"];
|
|
107
|
+
case "anchor":
|
|
108
|
+
case "thinking":
|
|
109
|
+
return [];
|
|
110
|
+
case "list":
|
|
111
|
+
return (b.items || []).flatMap((/** @type {any} */ item) => {
|
|
112
|
+
const box = item.has_checkbox ? (item.is_checked ? "☑ " : "☐ ") : "";
|
|
113
|
+
const label = `${item.label || "•"} ${box}`;
|
|
114
|
+
const lines = inner(item.blocks);
|
|
115
|
+
if (!lines.length) return [label.trimEnd()];
|
|
116
|
+
const indent = " ".repeat([...label].length);
|
|
117
|
+
return [label + lines[0], ...lines.slice(1).map((l) => (l ? indent + l : l))];
|
|
118
|
+
});
|
|
119
|
+
case "blockquote":
|
|
120
|
+
return prefixed("> ", [...inner(b.blocks), ...(b.credit ? [`— ${plain(b.credit)}`] : [])]);
|
|
121
|
+
case "expandable_blockquote":
|
|
122
|
+
case "pullquote":
|
|
123
|
+
return prefixed("> ", [...text(b.text), ...(b.credit ? [`— ${plain(b.credit)}`] : [])]);
|
|
124
|
+
case "collage":
|
|
125
|
+
case "slideshow":
|
|
126
|
+
return [...inner(b.blocks), ...captionLines(b.caption)];
|
|
127
|
+
case "table":
|
|
128
|
+
return [
|
|
129
|
+
...(b.caption ? text(b.caption) : []),
|
|
130
|
+
...(b.cells || []).map((/** @type {any[]} */ row) =>
|
|
131
|
+
(row || [])
|
|
132
|
+
.filter((c) => c && c.text != null) // a cell without text is hidden (taken by another's span)
|
|
133
|
+
.map((c) =>
|
|
134
|
+
plain(c.text)
|
|
135
|
+
.replace(/\s*\n\s*/g, " ")
|
|
136
|
+
.trim(),
|
|
137
|
+
)
|
|
138
|
+
.join(" | "),
|
|
139
|
+
),
|
|
140
|
+
];
|
|
141
|
+
case "details":
|
|
142
|
+
return [...text(b.summary), ...inner(b.blocks)];
|
|
143
|
+
case "map": {
|
|
144
|
+
const loc = b.location;
|
|
145
|
+
const where = loc ? [`[location: https://www.openstreetmap.org/?mlat=${loc.latitude}&mlon=${loc.longitude}]`] : [];
|
|
146
|
+
return [...where, ...captionLines(b.caption)];
|
|
147
|
+
}
|
|
148
|
+
case "buttons":
|
|
149
|
+
return (b.buttons || []).map(buttonText).filter(Boolean);
|
|
150
|
+
case "photo":
|
|
151
|
+
return file(b.photo?.length ? b.photo[b.photo.length - 1] : null, "photo", "jpg");
|
|
152
|
+
case "video":
|
|
153
|
+
return file(b.video, "video", "mp4");
|
|
154
|
+
case "animation":
|
|
155
|
+
return file(b.animation, "animation", "mp4");
|
|
156
|
+
case "audio":
|
|
157
|
+
return file(b.audio, "audio", "mp3");
|
|
158
|
+
case "voice_note":
|
|
159
|
+
return file(b.voice_note, "voice", "ogg");
|
|
160
|
+
case "document":
|
|
161
|
+
return file(b.document, "file", "bin");
|
|
162
|
+
default:
|
|
163
|
+
// A kind of block newer than this: its text, or what it holds, else a line saying something was left out.
|
|
164
|
+
if (b.text != null) return text(b.text);
|
|
165
|
+
if (Array.isArray(b.blocks)) return inner(b.blocks);
|
|
166
|
+
notes.push(`[${String(b.type || "part").replace(/_/g, " ")}: can't be shown here]`);
|
|
167
|
+
return [];
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Numbers the files without names of the message being read. */
|
|
172
|
+
let seq = 1;
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* A Telegram rich message as plain text; its files go to `add`, what can't come over to `notes`.
|
|
176
|
+
* @param {any} rich Message.rich_message
|
|
177
|
+
* @param {number} n the Telegram message's id
|
|
178
|
+
* @param {(f: any, name: string) => void} add
|
|
179
|
+
* @param {string[]} notes
|
|
180
|
+
*/
|
|
181
|
+
function richText(rich, n, add, notes) {
|
|
182
|
+
seq = 1;
|
|
183
|
+
const lines = blockLines(rich?.blocks, n, add, notes);
|
|
184
|
+
// Runs of blank lines (empty paragraphs, a heading after a gap) as one.
|
|
185
|
+
return lines
|
|
186
|
+
.map((l) => l.trimEnd())
|
|
187
|
+
.filter((l, i, all) => l !== "" || (i > 0 && all[i - 1] !== ""))
|
|
188
|
+
.join("\n")
|
|
189
|
+
.trim();
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
module.exports = { richText };
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
/// <reference path="../../types/pocketbase.d.ts" />
|
|
2
|
+
// The bridge's worker (DESIGN.md §26.7). A cron job starts it every minute and it runs for most of that minute,
|
|
3
|
+
// once a second: it brings over albums that are complete and sends what is queued for Telegram, oldest first. In
|
|
4
|
+
// development (no webhook URL) it also polls Telegram for updates. One runs at a time (a lock in the app store);
|
|
5
|
+
// POST /api/telegram/tick runs one pass at once (tests, or an admin who doesn't want to wait).
|
|
6
|
+
|
|
7
|
+
const { asTelegram, call, config, UPDATES } = require(`${__hooks}/telegram/api.js`);
|
|
8
|
+
const { flushAlbums, handleUpdate } = require(`${__hooks}/telegram/inbound.js`);
|
|
9
|
+
const { edit, remove, send } = require(`${__hooks}/telegram/outbound.js`);
|
|
10
|
+
|
|
11
|
+
const LOCK = "telegram.worker";
|
|
12
|
+
const OFFSET = "telegram.offset";
|
|
13
|
+
/** A lock not renewed for this long was left by a run that died (lib/worker.js). Renewed after every item a pass handles. */
|
|
14
|
+
const STALE_MS = 90_000;
|
|
15
|
+
/**
|
|
16
|
+
* A queue row being sent is claimed (locked_until) for this long: no other pass sends it meanwhile, even one that took
|
|
17
|
+
* over the lock while this one was stuck on a slow upload (QA BUG-147). A row left claimed by a run that died is sent
|
|
18
|
+
* once it runs out.
|
|
19
|
+
*/
|
|
20
|
+
const CLAIM_MS = 10 * 60_000;
|
|
21
|
+
/** How many times a send that failed for now is tried before it is dropped. */
|
|
22
|
+
const MAX_TRIES = 8;
|
|
23
|
+
/** Queue rows looked at in one pass. */
|
|
24
|
+
const BATCH = 50;
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Claim queue row `id` for sending (locked_until), unless another pass has it. In a transaction: PocketBase's writes
|
|
28
|
+
* go one at a time, so two passes can't both claim it.
|
|
29
|
+
* @param {core.App} app
|
|
30
|
+
* @param {string} id
|
|
31
|
+
*/
|
|
32
|
+
function claim(app, id) {
|
|
33
|
+
let mine = false;
|
|
34
|
+
app.runInTransaction((tx) => {
|
|
35
|
+
let row;
|
|
36
|
+
try {
|
|
37
|
+
row = tx.findRecordById("tg_queue", id);
|
|
38
|
+
} catch {
|
|
39
|
+
return; // done by another pass
|
|
40
|
+
}
|
|
41
|
+
const until = row.getDateTime("locked_until");
|
|
42
|
+
if (!until.isZero() && until.time().unixMilli() > Date.now()) return;
|
|
43
|
+
row.set("locked_until", new DateTime(new Date(Date.now() + CLAIM_MS).toISOString()));
|
|
44
|
+
tx.save(row);
|
|
45
|
+
mine = true;
|
|
46
|
+
});
|
|
47
|
+
return mine;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Updates from Telegram, when polling (no webhook URL), waiting at most `timeout` seconds for one.
|
|
52
|
+
* @param {core.App} app
|
|
53
|
+
* @param {number} timeout
|
|
54
|
+
*/
|
|
55
|
+
function poll(app, timeout) {
|
|
56
|
+
const offset = Number(app.store().get(OFFSET) || 0);
|
|
57
|
+
const updates = call("getUpdates", { offset, timeout, allowed_updates: UPDATES }, undefined, timeout + 10) || [];
|
|
58
|
+
for (const u of updates) {
|
|
59
|
+
app.store().set(OFFSET, u.update_id + 1);
|
|
60
|
+
try {
|
|
61
|
+
handleUpdate(app, u);
|
|
62
|
+
} catch (err) {
|
|
63
|
+
app.logger().error("telegram: update", "update", u.update_id, "error", String(err));
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Send what is queued for Telegram, oldest first. A group whose oldest item has to wait (a failure that may pass, or
|
|
70
|
+
* another pass sending it) gets nothing more this pass, so its messages arrive in order. `renew` after each one.
|
|
71
|
+
* @param {core.App} app
|
|
72
|
+
* @param {() => void} renew
|
|
73
|
+
*/
|
|
74
|
+
function drain(app, renew) {
|
|
75
|
+
const rows = app.findRecordsByFilter("tg_queue", "op != 'album'", "created,id", BATCH, 0);
|
|
76
|
+
const blocked = new Set();
|
|
77
|
+
const now = Date.now();
|
|
78
|
+
for (const row of rows) {
|
|
79
|
+
if (!row) continue;
|
|
80
|
+
const chat = row.getString("chat_id");
|
|
81
|
+
if (blocked.has(chat)) continue;
|
|
82
|
+
const due = row.getDateTime("next_at");
|
|
83
|
+
if (!due.isZero() && due.time().unixMilli() > now) {
|
|
84
|
+
blocked.add(chat);
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
if (!claim(app, row.id)) {
|
|
88
|
+
blocked.add(chat);
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
const op = row.getString("op");
|
|
92
|
+
const message = row.getString("message");
|
|
93
|
+
try {
|
|
94
|
+
if (op === "send") send(app, message, chat);
|
|
95
|
+
else if (op === "edit") edit(app, message, chat);
|
|
96
|
+
else if (op === "delete") remove(app, message, chat);
|
|
97
|
+
else if (op === "react") require(`${__hooks}/telegram/reactions.js`).react(app, message, chat);
|
|
98
|
+
app.delete(row);
|
|
99
|
+
} catch (err) {
|
|
100
|
+
const tries = row.getInt("tries") + 1;
|
|
101
|
+
const tg = asTelegram(err);
|
|
102
|
+
const transient = !tg || tg.transient;
|
|
103
|
+
app.logger().warn(`telegram: ${op}`, "message", message, "chat", chat, "try", tries, "error", String(err));
|
|
104
|
+
if (!transient || tries >= MAX_TRIES) {
|
|
105
|
+
app.delete(row);
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
const wait = Math.max(tg ? tg.retryAfter : 0, 2 ** tries) * 1000;
|
|
109
|
+
row.set("tries", tries);
|
|
110
|
+
row.set("next_at", new DateTime(new Date(Date.now() + wait).toISOString()));
|
|
111
|
+
row.set("locked_until", "");
|
|
112
|
+
row.set("error", String(err).slice(0, 1000));
|
|
113
|
+
app.save(row);
|
|
114
|
+
blocked.add(chat);
|
|
115
|
+
} finally {
|
|
116
|
+
renew();
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* One pass: poll (when polling), bring over complete albums, send what is queued. `renew` (the worker's lock) after
|
|
123
|
+
* each item. True when polling: the poll has already waited, so the next pass goes at once.
|
|
124
|
+
* @param {core.App} app
|
|
125
|
+
* @param {number} pollTimeout seconds
|
|
126
|
+
* @param {() => void} renew
|
|
127
|
+
*/
|
|
128
|
+
function pass(app, pollTimeout, renew) {
|
|
129
|
+
if (!config().webhookUrl) {
|
|
130
|
+
try {
|
|
131
|
+
poll(app, pollTimeout);
|
|
132
|
+
} catch (err) {
|
|
133
|
+
app.logger().warn("telegram: getUpdates", "error", String(err));
|
|
134
|
+
sleep(1000);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
flushAlbums(app, undefined, undefined, renew);
|
|
138
|
+
drain(app, renew);
|
|
139
|
+
return !config().webhookUrl;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** The worker (lib/worker.js); a pass waits `pollTimeout` seconds at most for Telegram's updates. */
|
|
143
|
+
const worker = (/** @type {core.App} */ app, /** @type {number} */ pollTimeout) => ({
|
|
144
|
+
name: LOCK,
|
|
145
|
+
label: "telegram",
|
|
146
|
+
staleMs: STALE_MS,
|
|
147
|
+
pass: (/** @type {() => void} */ renew) => pass(app, pollTimeout, renew),
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* The cron job: passes until the minute is nearly over.
|
|
152
|
+
* @param {core.App} app
|
|
153
|
+
*/
|
|
154
|
+
function run(app) {
|
|
155
|
+
require(`${__hooks}/lib/worker.js`).run(app, worker(app, 1));
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* POST /api/telegram/tick (superusers): one pass now, unless a run is going (it does the work within a second).
|
|
160
|
+
* @param {core.RequestEvent} e
|
|
161
|
+
*/
|
|
162
|
+
function tick(e) {
|
|
163
|
+
const ran = require(`${__hooks}/lib/worker.js`).once(e.app, worker(e.app, 0));
|
|
164
|
+
return e.json(ran ? 200 : 202, { ran });
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* On start: tell Telegram where to send updates (one at a time, so they arrive in order), or, without a webhook
|
|
169
|
+
* URL, that the bridge polls.
|
|
170
|
+
* @param {core.App} app
|
|
171
|
+
*/
|
|
172
|
+
function setup(app) {
|
|
173
|
+
const { webhookUrl, secret } = config();
|
|
174
|
+
try {
|
|
175
|
+
if (webhookUrl) call("setWebhook", { url: webhookUrl, secret_token: secret, allowed_updates: UPDATES, max_connections: 1 });
|
|
176
|
+
else call("deleteWebhook", {});
|
|
177
|
+
} catch (err) {
|
|
178
|
+
app.logger().error("telegram: setup", "error", String(err));
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
module.exports = { run, tick, setup };
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/// <reference path="../types/pocketbase.d.ts" />
|
|
2
|
+
// Telegram bridge (DESIGN.md §26): messages go both ways between rooms and the Telegram groups they are linked to.
|
|
3
|
+
// This file, telegram/ and the tg_* collections (pb_migrations/1760000019_telegram.js); what it does on the core
|
|
4
|
+
// collections' saves (messages, users) main.pb.js calls through lib/features.js, which is off without
|
|
5
|
+
// TELEGRAM_BOT_TOKEN. Without it this file registers nothing either.
|
|
6
|
+
|
|
7
|
+
if ($os.getenv("TELEGRAM_BOT_TOKEN").trim()) {
|
|
8
|
+
// Only when serving: other commands (migrate, superuser…) bootstrap too.
|
|
9
|
+
onBootstrap((e) => {
|
|
10
|
+
e.next();
|
|
11
|
+
if ($os.args.includes("serve")) require(`${__hooks}/telegram/worker.js`).setup(e.app);
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
routerAdd("POST", "/api/telegram/webhook", (e) => require(`${__hooks}/telegram/inbound.js`).webhook(e));
|
|
15
|
+
routerAdd("POST", "/api/telegram/tick", (e) => require(`${__hooks}/telegram/worker.js`).tick(e), $apis.requireSuperuserAuth());
|
|
16
|
+
|
|
17
|
+
cronAdd("telegram", "* * * * *", () => require(`${__hooks}/telegram/worker.js`).run($app));
|
|
18
|
+
|
|
19
|
+
// A room says when a group is connected to it or disconnected from it (a service message, §26.5).
|
|
20
|
+
onRecordCreate((e) => {
|
|
21
|
+
const links = require(`${__hooks}/telegram/links.js`);
|
|
22
|
+
links.beforeLinkSave(e);
|
|
23
|
+
e.next();
|
|
24
|
+
if (e.record) links.tellLinkChange(e.app, e.record, "", links.linkedRoom(e.record));
|
|
25
|
+
}, "tg_links");
|
|
26
|
+
|
|
27
|
+
onRecordUpdate((e) => {
|
|
28
|
+
const links = require(`${__hooks}/telegram/links.js`);
|
|
29
|
+
links.beforeLinkSave(e);
|
|
30
|
+
const rec = e.record;
|
|
31
|
+
if (!rec) return e.next();
|
|
32
|
+
// What it was, as stored, read in the save's transaction: the same change saved twice at once tells the room once.
|
|
33
|
+
e.app.runInTransaction((tx) => {
|
|
34
|
+
e.app = tx;
|
|
35
|
+
const was = links.linkedRoom(tx.findRecordById("tg_links", rec.id));
|
|
36
|
+
e.next();
|
|
37
|
+
links.tellLinkChange(tx, rec, was, links.linkedRoom(rec));
|
|
38
|
+
});
|
|
39
|
+
}, "tg_links");
|
|
40
|
+
|
|
41
|
+
onRecordAfterDeleteSuccess((e) => {
|
|
42
|
+
const links = require(`${__hooks}/telegram/links.js`);
|
|
43
|
+
// Deleted with its room (cascade), there's no room left to tell.
|
|
44
|
+
if (e.record) links.tellLinkChange(e.app, e.record, links.linkedRoom(e.record), "");
|
|
45
|
+
e.next();
|
|
46
|
+
}, "tg_links");
|
|
47
|
+
}
|