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,129 @@
|
|
|
1
|
+
/// <reference path="../../types/pocketbase.d.ts" />
|
|
2
|
+
// Telegram Bot API client and the bridge's settings, all from the environment (DESIGN.md §26.2):
|
|
3
|
+
// - TELEGRAM_BOT_TOKEN: the bot's token from @BotFather. Unset, the bridge does nothing (telegram.pb.js).
|
|
4
|
+
// - TELEGRAM_WEBHOOK_URL: this server's public https URL of POST /api/telegram/webhook. Unset, the bridge polls
|
|
5
|
+
// Telegram instead (getUpdates), which is meant for development.
|
|
6
|
+
// - TELEGRAM_WEBHOOK_SECRET: what Telegram sends with each webhook call; derived from the token when unset.
|
|
7
|
+
// - TELEGRAM_API_BASE: the Bot API server (tests point it at a stub).
|
|
8
|
+
|
|
9
|
+
const env = (/** @type {string} */ name) => $os.getenv(name).trim();
|
|
10
|
+
|
|
11
|
+
function config() {
|
|
12
|
+
const token = env("TELEGRAM_BOT_TOKEN");
|
|
13
|
+
return {
|
|
14
|
+
token,
|
|
15
|
+
base: (env("TELEGRAM_API_BASE") || "https://api.telegram.org").replace(/\/+$/, ""),
|
|
16
|
+
webhookUrl: env("TELEGRAM_WEBHOOK_URL"),
|
|
17
|
+
secret: env("TELEGRAM_WEBHOOK_SECRET") || $security.sha256(`chat-telegram-webhook:${token}`),
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** The updates the bridge asks for: a channel's posts come as channel_post, not message. Telegram sends
|
|
22
|
+
* message_reaction only where the bot is an admin. */
|
|
23
|
+
const UPDATES = ["message", "edited_message", "channel_post", "edited_channel_post", "my_chat_member", "message_reaction"];
|
|
24
|
+
|
|
25
|
+
/** A refused or failed call. `retryAfter`: seconds Telegram asks to wait (429). `status` 0: no answer. */
|
|
26
|
+
class TelegramError extends Error {
|
|
27
|
+
/**
|
|
28
|
+
* @param {number} status
|
|
29
|
+
* @param {string} message
|
|
30
|
+
* @param {number} [retryAfter]
|
|
31
|
+
*/
|
|
32
|
+
constructor(status, message, retryAfter = 0) {
|
|
33
|
+
super(message);
|
|
34
|
+
this.name = "TelegramError";
|
|
35
|
+
this.status = status;
|
|
36
|
+
this.retryAfter = retryAfter;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Worth trying again later: no answer, Telegram's own trouble, or too many requests. */
|
|
40
|
+
get transient() {
|
|
41
|
+
return this.status === 0 || this.status === 429 || this.status >= 500;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* The error as a TelegramError, or null for anything else (a bug).
|
|
47
|
+
* @param {unknown} err
|
|
48
|
+
* @returns {TelegramError | null}
|
|
49
|
+
*/
|
|
50
|
+
const asTelegram = (err) => (err instanceof TelegramError ? err : null);
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Call a Bot API method. Files (filesystem.File by field name) go as multipart, the other params as fields (objects
|
|
54
|
+
* as JSON); without files the params are a JSON body.
|
|
55
|
+
* @param {string} method
|
|
56
|
+
* @param {Record<string, unknown>} [params]
|
|
57
|
+
* @param {Record<string, any>} [files]
|
|
58
|
+
* @param {number} [timeout] seconds
|
|
59
|
+
* @returns {any} the method's result
|
|
60
|
+
*/
|
|
61
|
+
function call(method, params = {}, files, timeout = 30) {
|
|
62
|
+
const { token, base } = config();
|
|
63
|
+
const url = `${base}/bot${token}/${method}`;
|
|
64
|
+
/** @type {any} */
|
|
65
|
+
let res;
|
|
66
|
+
try {
|
|
67
|
+
if (files && Object.keys(files).length) {
|
|
68
|
+
// @ts-expect-error PocketBase's FormData (its types declare only the interface, there is no lib.dom here)
|
|
69
|
+
const form = /** @type {FormData} */ (new FormData());
|
|
70
|
+
for (const [k, v] of Object.entries(params)) {
|
|
71
|
+
if (v !== undefined) form.append(k, typeof v === "string" ? v : JSON.stringify(v));
|
|
72
|
+
}
|
|
73
|
+
for (const [k, f] of Object.entries(files)) form.append(k, f);
|
|
74
|
+
res = $http.send({ url, method: "POST", body: form, timeout: Math.max(timeout, 300) });
|
|
75
|
+
} else {
|
|
76
|
+
res = $http.send({ url, method: "POST", body: JSON.stringify(params), headers: { "content-type": "application/json" }, timeout });
|
|
77
|
+
}
|
|
78
|
+
} catch (err) {
|
|
79
|
+
throw new TelegramError(0, `${method}: ${String(err).replace(token, "<token>")}`);
|
|
80
|
+
}
|
|
81
|
+
const json = res.json;
|
|
82
|
+
if (!json?.ok) {
|
|
83
|
+
const description = json?.description || `HTTP ${res.statusCode}`;
|
|
84
|
+
throw new TelegramError(res.statusCode || 500, `${method}: ${description}`, json?.parameters?.retry_after || 0);
|
|
85
|
+
}
|
|
86
|
+
return json.result;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* A stored name as PocketBase makes them ("report_k3j2h1g0f9.pdf"): the client tells images and videos by its
|
|
91
|
+
* extension, so it is the original's, or else that of the path Telegram serves the file at.
|
|
92
|
+
* @param {string} name
|
|
93
|
+
* @param {string} path
|
|
94
|
+
*/
|
|
95
|
+
function storedName(name, path) {
|
|
96
|
+
const ext = (/** @type {string} */ s) => (/\.([a-z0-9]{1,8})$/i.exec(s) || ["", ""])[1].toLowerCase();
|
|
97
|
+
const base =
|
|
98
|
+
name
|
|
99
|
+
.replace(/\.[^.]*$/, "")
|
|
100
|
+
.toLowerCase()
|
|
101
|
+
.replace(/[^a-z0-9]+/g, "_")
|
|
102
|
+
.replace(/^_+|_+$/g, "")
|
|
103
|
+
.slice(0, 60) || "file";
|
|
104
|
+
const suffix = $security.randomStringWithAlphabet(10, "abcdefghijklmnopqrstuvwxyz0123456789");
|
|
105
|
+
const e = ext(name) || ext(path);
|
|
106
|
+
return `${base}_${suffix}${e ? `.${e}` : ""}`;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Download a file the bot can see (at most 20 MB, the Bot API's limit), named `name`.
|
|
111
|
+
* @param {string} fileId
|
|
112
|
+
* @param {string} name
|
|
113
|
+
*/
|
|
114
|
+
function download(fileId, name) {
|
|
115
|
+
const { token, base } = config();
|
|
116
|
+
const info = call("getFile", { file_id: fileId });
|
|
117
|
+
if (!info?.file_path) throw new TelegramError(400, "getFile: no file_path");
|
|
118
|
+
let file;
|
|
119
|
+
try {
|
|
120
|
+
file = $filesystem.fileFromURL(`${base}/file/bot${token}/${info.file_path}`, 120);
|
|
121
|
+
} catch (err) {
|
|
122
|
+
throw new TelegramError(0, `download: ${String(err).replace(token, "<token>")}`);
|
|
123
|
+
}
|
|
124
|
+
file.originalName = name;
|
|
125
|
+
file.name = storedName(name, info.file_path);
|
|
126
|
+
return file;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
module.exports = { config, call, download, asTelegram, TelegramError, UPDATES };
|
|
@@ -0,0 +1,553 @@
|
|
|
1
|
+
/// <reference path="../../types/pocketbase.d.ts" />
|
|
2
|
+
// Telegram → chat (DESIGN.md §26.4): updates from the webhook, or from polling in development. A Telegram message
|
|
3
|
+
// becomes a chat message of its sender's stand-in, with its files; an album (sent as one update per item) becomes one
|
|
4
|
+
// message once all of it is in; an edit edits it. Telegram doesn't tell bots about deleted messages.
|
|
5
|
+
|
|
6
|
+
const { call, config, download } = require(`${__hooks}/telegram/api.js`);
|
|
7
|
+
const { personOf } = require(`${__hooks}/telegram/people.js`);
|
|
8
|
+
const { activeLink, ensureLink, linkedRoom, linkOfChat, moveLink, tellLinkChange } = require(`${__hooks}/telegram/links.js`);
|
|
9
|
+
const { richText } = require(`${__hooks}/telegram/rich.js`);
|
|
10
|
+
const { isBlank } = require(`${__hooks}/lib/text.js`);
|
|
11
|
+
|
|
12
|
+
/** The largest file the Bot API lets a bot download, and the largest attachment (§17.1). */
|
|
13
|
+
const MAX_FILE = 20 * 1024 * 1024;
|
|
14
|
+
/** messages.files maxSelect and messages.text max. */
|
|
15
|
+
const MAX_FILES = 10;
|
|
16
|
+
const MAX_TEXT = 2000;
|
|
17
|
+
/** An album is complete when nothing more of it came for this long. */
|
|
18
|
+
const ALBUM_QUIET_MS = 1500;
|
|
19
|
+
|
|
20
|
+
const mb = (/** @type {number} */ n) => `${(n / 1024 / 1024).toFixed(1).replace(/\.0$/, "")} MB`;
|
|
21
|
+
|
|
22
|
+
/** The most of a Telegram quote that comes over, so that it leaves room for the message's own text. */
|
|
23
|
+
const MAX_QUOTE = 500;
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Who a message came from first (a MessageOrigin: a forward's, an external reply's), or "".
|
|
27
|
+
* @param {any} o
|
|
28
|
+
*/
|
|
29
|
+
function originName(o) {
|
|
30
|
+
if (!o) return "";
|
|
31
|
+
return o.type === "user"
|
|
32
|
+
? [o.sender_user.first_name, o.sender_user.last_name].filter(Boolean).join(" ")
|
|
33
|
+
: o.type === "hidden_user"
|
|
34
|
+
? o.sender_user_name
|
|
35
|
+
: o.type === "chat"
|
|
36
|
+
? o.sender_chat.title
|
|
37
|
+
: o.type === "channel"
|
|
38
|
+
? o.chat.title
|
|
39
|
+
: "";
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* "Forwarded from Bob", when the Telegram message is a forward.
|
|
44
|
+
* @param {any} msg
|
|
45
|
+
*/
|
|
46
|
+
function forwardLine(msg) {
|
|
47
|
+
if (!msg.forward_origin) return "";
|
|
48
|
+
return `↪ Forwarded from ${originName(msg.forward_origin) || "someone"}`;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* What a Telegram reply quotes, as lines over its text: the part it quotes ("> …"), and whom it answers when the room
|
|
53
|
+
* can't show that as a reply: a message in another chat (a channel's post) or one the bridge doesn't know. A reply to
|
|
54
|
+
* a message in the room that quotes nothing needs no lines: it replies to it there.
|
|
55
|
+
* @param {any} msg
|
|
56
|
+
* @param {boolean} known its reply_to_message is in the room
|
|
57
|
+
*/
|
|
58
|
+
function quoteLines(msg, known) {
|
|
59
|
+
const ext = msg.external_reply;
|
|
60
|
+
const replied = msg.reply_to_message;
|
|
61
|
+
const quote = String(msg.quote?.text || "").trim();
|
|
62
|
+
if (!ext && !quote) return [];
|
|
63
|
+
/** @type {string[]} */
|
|
64
|
+
const lines = [];
|
|
65
|
+
let from = null;
|
|
66
|
+
if (ext) from = originName(ext.origin) || ext.chat?.title || "";
|
|
67
|
+
else if (replied && !known)
|
|
68
|
+
from = replied.sender_chat?.title || [replied.from?.first_name, replied.from?.last_name].filter(Boolean).join(" ");
|
|
69
|
+
if (from !== null) lines.push(`↩ In reply to ${from || "a message"}`);
|
|
70
|
+
if (quote) {
|
|
71
|
+
const chars = [...quote];
|
|
72
|
+
const cut = chars.length <= MAX_QUOTE ? quote : `${chars.slice(0, MAX_QUOTE - 1).join("")}…`;
|
|
73
|
+
lines.push(...cut.split("\n").map((l) => `> ${l}`));
|
|
74
|
+
}
|
|
75
|
+
return lines;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* A Telegram message's text (its caption, or a rich message's blocks as text), its files (that can be brought over),
|
|
80
|
+
* and lines for what can't be: files over the download limit, and things that aren't files (a location, a poll…).
|
|
81
|
+
* @param {any} msg
|
|
82
|
+
* @returns {{ text: string, files: { id: string, name: string }[], notes: string[] }}
|
|
83
|
+
*/
|
|
84
|
+
function partsOf(msg) {
|
|
85
|
+
/** @type {{ id: string, name: string }[]} */
|
|
86
|
+
const files = [];
|
|
87
|
+
/** @type {string[]} */
|
|
88
|
+
const notes = [];
|
|
89
|
+
const n = msg.message_id;
|
|
90
|
+
/**
|
|
91
|
+
* @param {any} f
|
|
92
|
+
* @param {string} name
|
|
93
|
+
*/
|
|
94
|
+
const add = (f, name) => {
|
|
95
|
+
if (f.file_size && f.file_size > MAX_FILE) notes.push(`[${name}, ${mb(f.file_size)}: too large to bring over from Telegram]`);
|
|
96
|
+
else files.push({ id: f.file_id, name });
|
|
97
|
+
};
|
|
98
|
+
if (msg.photo?.length) add(msg.photo[msg.photo.length - 1], `photo_${n}.jpg`);
|
|
99
|
+
if (msg.video) add(msg.video, msg.video.file_name || `video_${n}.mp4`);
|
|
100
|
+
// A GIF comes as an animation, with a document of the same file next to it.
|
|
101
|
+
if (msg.animation) add(msg.animation, msg.animation.file_name || `animation_${n}.mp4`);
|
|
102
|
+
else if (msg.document) add(msg.document, msg.document.file_name || `file_${n}`);
|
|
103
|
+
if (msg.audio) add(msg.audio, msg.audio.file_name || `audio_${n}.mp3`);
|
|
104
|
+
if (msg.voice) add(msg.voice, `voice_${n}.ogg`);
|
|
105
|
+
if (msg.video_note) add(msg.video_note, `video_note_${n}.mp4`);
|
|
106
|
+
if (msg.sticker) {
|
|
107
|
+
if (msg.sticker.is_animated) notes.push(`[sticker ${msg.sticker.emoji || ""}]`.replace(" ]", "]"));
|
|
108
|
+
else add(msg.sticker, `sticker_${n}.${msg.sticker.is_video ? "webm" : "webp"}`);
|
|
109
|
+
}
|
|
110
|
+
const loc = msg.venue ? msg.venue.location : msg.location;
|
|
111
|
+
if (loc) {
|
|
112
|
+
const where = `https://www.openstreetmap.org/?mlat=${loc.latitude}&mlon=${loc.longitude}`;
|
|
113
|
+
notes.push(msg.venue ? `[${msg.venue.title}, ${msg.venue.address}: ${where}]` : `[location: ${where}]`);
|
|
114
|
+
}
|
|
115
|
+
if (msg.contact)
|
|
116
|
+
notes.push(`[contact: ${[msg.contact.first_name, msg.contact.last_name].filter(Boolean).join(" ")} ${msg.contact.phone_number}]`);
|
|
117
|
+
if (msg.poll) notes.push(`[poll: ${msg.poll.question}]`);
|
|
118
|
+
if (msg.dice) notes.push(`[${msg.dice.emoji} ${msg.dice.value}]`);
|
|
119
|
+
// A rich message (Bot API 10.1) has neither text nor caption: without this it was taken for a service message.
|
|
120
|
+
const text = msg.text || msg.caption || (msg.rich_message ? richText(msg.rich_message, n, add, notes) : "");
|
|
121
|
+
return { text, files, notes };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Text in pieces that each fit messages.text (in code points, as PocketBase counts): a Telegram message holds twice as
|
|
126
|
+
* much as a chat message, and comes over as several rather than cut. Each piece ends at a line break, else a space, in
|
|
127
|
+
* its second half; a text with neither there is cut at the limit. Always one piece at least, blank for no text.
|
|
128
|
+
* @param {string} text
|
|
129
|
+
* @returns {string[]}
|
|
130
|
+
*/
|
|
131
|
+
function split(text) {
|
|
132
|
+
/** @type {string[]} */
|
|
133
|
+
const pieces = [];
|
|
134
|
+
let chars = [...text];
|
|
135
|
+
while (chars.length > MAX_TEXT) {
|
|
136
|
+
// The character just past the limit may be where it breaks: the break itself is left out.
|
|
137
|
+
const room = chars.slice(0, MAX_TEXT + 1);
|
|
138
|
+
let at = room.lastIndexOf("\n");
|
|
139
|
+
if (at < MAX_TEXT / 2) for (at = MAX_TEXT; at >= MAX_TEXT / 2 && !/\s/.test(room[at]); at--);
|
|
140
|
+
const cut = at >= MAX_TEXT / 2;
|
|
141
|
+
pieces.push(
|
|
142
|
+
chars
|
|
143
|
+
.slice(0, cut ? at : MAX_TEXT)
|
|
144
|
+
.join("")
|
|
145
|
+
.trim(),
|
|
146
|
+
);
|
|
147
|
+
chars = chars.slice(cut ? at + 1 : MAX_TEXT);
|
|
148
|
+
}
|
|
149
|
+
pieces.push(chars.join("").trim());
|
|
150
|
+
const kept = pieces.filter((p) => !isBlank(p));
|
|
151
|
+
return kept.length ? kept : [""];
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Ids for messages saved at once, in the order they were written: the room shows messages by created, then id, and
|
|
156
|
+
* those saved within the same millisecond would otherwise show in any order.
|
|
157
|
+
* @param {number} n
|
|
158
|
+
*/
|
|
159
|
+
function orderedIds(n) {
|
|
160
|
+
const ids = Array.from({ length: n }, () => $security.randomStringWithAlphabet(15, "abcdefghijklmnopqrstuvwxyz0123456789"));
|
|
161
|
+
return ids.sort();
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* What a Telegram message came over as: its tg_messages rows (either way), first part first.
|
|
166
|
+
* @param {core.App} app
|
|
167
|
+
* @param {string} chatId
|
|
168
|
+
* @param {number} tgId
|
|
169
|
+
*/
|
|
170
|
+
function partsMapped(app, chatId, tgId) {
|
|
171
|
+
return app
|
|
172
|
+
.findRecordsByFilter("tg_messages", "chat_id = {:chat} && tg_message_id = {:id}", "part", 0, 0, { chat: chatId, id: tgId })
|
|
173
|
+
.filter((r) => !!r);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* The chat message a Telegram message is (either way; its first part, when it came over as several), or null.
|
|
178
|
+
* @param {core.App} app
|
|
179
|
+
* @param {string} chatId
|
|
180
|
+
* @param {number} tgId
|
|
181
|
+
*/
|
|
182
|
+
function mapped(app, chatId, tgId) {
|
|
183
|
+
try {
|
|
184
|
+
const row = app.findFirstRecordByFilter("tg_messages", "chat_id = {:chat} && tg_message_id = {:id} && part = 0", {
|
|
185
|
+
chat: chatId,
|
|
186
|
+
id: tgId,
|
|
187
|
+
});
|
|
188
|
+
return app.findRecordById("messages", row.getString("message"));
|
|
189
|
+
} catch {
|
|
190
|
+
return null;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* Save the tg_messages row of a part of a Telegram message.
|
|
196
|
+
* @param {core.App} tx
|
|
197
|
+
* @param {string} messageId
|
|
198
|
+
* @param {string} chatId
|
|
199
|
+
* @param {number} tgId
|
|
200
|
+
* @param {"text" | "media"} kind
|
|
201
|
+
* @param {number} part
|
|
202
|
+
*/
|
|
203
|
+
function rememberIn(tx, messageId, chatId, tgId, kind, part) {
|
|
204
|
+
const row = new Record(tx.findCollectionByNameOrId("tg_messages"));
|
|
205
|
+
row.set("message", messageId);
|
|
206
|
+
row.set("chat_id", chatId);
|
|
207
|
+
row.set("tg_message_id", tgId);
|
|
208
|
+
row.set("direction", "in");
|
|
209
|
+
row.set("kind", kind);
|
|
210
|
+
row.set("part", part);
|
|
211
|
+
tx.save(row);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* A further part of a long Telegram message: its text, under the same stand-in, after the first.
|
|
216
|
+
* @param {core.App} tx
|
|
217
|
+
* @param {string} roomId
|
|
218
|
+
* @param {string} authorId
|
|
219
|
+
* @param {string} text
|
|
220
|
+
* @param {string} [id]
|
|
221
|
+
*/
|
|
222
|
+
function savePart(tx, roomId, authorId, text, id) {
|
|
223
|
+
const rec = new Record(tx.findCollectionByNameOrId("messages"));
|
|
224
|
+
if (id) rec.id = id;
|
|
225
|
+
rec.set("room", roomId);
|
|
226
|
+
rec.set("author", authorId);
|
|
227
|
+
rec.set("text", text);
|
|
228
|
+
tx.save(rec);
|
|
229
|
+
return rec;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* Stand-ins write in a private room as members, and in a room where only some people post as writers (the messages
|
|
234
|
+
* hook checks both, §23, §23.6): the Telegram group decides who speaks.
|
|
235
|
+
* @param {core.App} app
|
|
236
|
+
* @param {core.Record} room
|
|
237
|
+
* @param {string} userId
|
|
238
|
+
*/
|
|
239
|
+
function ensureMember(app, room, userId) {
|
|
240
|
+
if (room.getString("created_by") === userId) return;
|
|
241
|
+
const members = room.getStringSlice("members");
|
|
242
|
+
const writers = room.getStringSlice("writers");
|
|
243
|
+
const member = room.getString("visibility") !== "private" || members.includes(userId);
|
|
244
|
+
const writer = room.getString("posting") !== "selected" || writers.includes(userId);
|
|
245
|
+
if (member && writer) return;
|
|
246
|
+
if (!member) room.set("members", [...members, userId]);
|
|
247
|
+
if (!writer) room.set("writers", [...writers, userId]);
|
|
248
|
+
app.save(room);
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* Bring Telegram messages over as one chat message: one message, or the items of an album.
|
|
253
|
+
* @param {core.App} app
|
|
254
|
+
* @param {core.Record} link tg_links
|
|
255
|
+
* @param {core.Record} room
|
|
256
|
+
* @param {any[]} msgs
|
|
257
|
+
*/
|
|
258
|
+
function bringOver(app, link, room, msgs) {
|
|
259
|
+
const chatId = link.getString("chat_id");
|
|
260
|
+
// Delivered twice (a webhook retry): brought over already, or an album item queued twice, which would fail the save
|
|
261
|
+
// of the whole album on the unique (chat_id, tg_message_id) (QA BUG-147).
|
|
262
|
+
const seen = new Set();
|
|
263
|
+
msgs = msgs.filter((m) => !seen.has(m.message_id) && seen.add(m.message_id) && !mapped(app, chatId, m.message_id));
|
|
264
|
+
if (!msgs.length) return;
|
|
265
|
+
msgs.sort((a, b) => a.message_id - b.message_id);
|
|
266
|
+
const first = msgs[0];
|
|
267
|
+
const parts = msgs.map(partsOf);
|
|
268
|
+
const notes = parts.flatMap((p) => p.notes);
|
|
269
|
+
// A service message (a new group photo, a timer, a topic…) has nothing to show: it makes no stand-in, and none joins
|
|
270
|
+
// a private room for it (QA BUG-88).
|
|
271
|
+
if (!notes.length && !parts.some((p) => p.files.length) && !parts.some((p) => p.text.trim())) return;
|
|
272
|
+
const author = personOf(app, first);
|
|
273
|
+
ensureMember(app, room, author.id);
|
|
274
|
+
|
|
275
|
+
/** @type {any[]} */
|
|
276
|
+
const files = [];
|
|
277
|
+
for (const f of parts.flatMap((p) => p.files)) {
|
|
278
|
+
if (files.length >= MAX_FILES) {
|
|
279
|
+
notes.push(`[${f.name}: more files than a message holds]`);
|
|
280
|
+
continue;
|
|
281
|
+
}
|
|
282
|
+
try {
|
|
283
|
+
files.push(download(f.id, f.name));
|
|
284
|
+
} catch (err) {
|
|
285
|
+
app.logger().warn("telegram: download", "chat", chatId, "error", String(err));
|
|
286
|
+
notes.push(`[${f.name}: couldn't be brought over from Telegram]`);
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
const reply = first.reply_to_message ? mapped(app, chatId, first.reply_to_message.message_id) : null;
|
|
290
|
+
const known = !!reply && reply.getString("room") === room.id && !reply.getBool("deleted");
|
|
291
|
+
const textOf = (/** @type {boolean} */ withReply) =>
|
|
292
|
+
[forwardLine(first), ...quoteLines(first, withReply && known), ...parts.map((p) => p.text), ...notes].filter(Boolean).join("\n");
|
|
293
|
+
if (!textOf(true).trim() && !files.length) return;
|
|
294
|
+
|
|
295
|
+
// The messages and what they map to in one transaction: the outbound hook queues them for the room's other linked
|
|
296
|
+
// groups, and the worker must find they came from this one (outbound.js), never send them back. A text too long for
|
|
297
|
+
// one message comes as several: the first with the files and the reply, the rest after it.
|
|
298
|
+
const save = (/** @type {boolean} */ withReply) =>
|
|
299
|
+
app.runInTransaction((tx) => {
|
|
300
|
+
const pieces = split(textOf(withReply));
|
|
301
|
+
const ids = orderedIds(pieces.length);
|
|
302
|
+
const rec = new Record(tx.findCollectionByNameOrId("messages"));
|
|
303
|
+
rec.id = ids[0];
|
|
304
|
+
rec.set("room", room.id);
|
|
305
|
+
rec.set("author", author.id);
|
|
306
|
+
rec.set("text", pieces[0]);
|
|
307
|
+
if (files.length) require(`${__hooks}/lib/files.js`).attachUploads(tx, rec, files);
|
|
308
|
+
if (withReply && known && reply) rec.set("reply_to", reply.id);
|
|
309
|
+
tx.save(rec);
|
|
310
|
+
msgs.forEach((m, i) => {
|
|
311
|
+
rememberIn(tx, rec.id, chatId, m.message_id, i === 0 ? "text" : "media", 0);
|
|
312
|
+
});
|
|
313
|
+
for (let i = 1; i < pieces.length; i++) {
|
|
314
|
+
const part = savePart(tx, room.id, author.id, pieces[i], ids[i]);
|
|
315
|
+
rememberIn(tx, part.id, chatId, first.message_id, "text", i);
|
|
316
|
+
}
|
|
317
|
+
});
|
|
318
|
+
try {
|
|
319
|
+
save(true);
|
|
320
|
+
} catch (err) {
|
|
321
|
+
if (!reply) throw err;
|
|
322
|
+
save(false); // the quoted message went meanwhile: without the quote, as the app does (§19)
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* A Telegram edit: the chat message gets the new text.
|
|
328
|
+
* @param {core.App} app
|
|
329
|
+
* @param {any} msg
|
|
330
|
+
*/
|
|
331
|
+
function editOver(app, msg) {
|
|
332
|
+
const chatId = String(msg.chat.id);
|
|
333
|
+
const rows = partsMapped(app, chatId, msg.message_id);
|
|
334
|
+
const rec = rows[0]?.getInt("part") === 0 ? findMessage(app, rows[0].getString("message")) : null;
|
|
335
|
+
if (!rec || rec.getBool("deleted") || rec.getString("forwarded_from")) return;
|
|
336
|
+
const quoted = quoteLines(msg, !!rec.getString("reply_to"));
|
|
337
|
+
const { text, notes } = partsOf(msg);
|
|
338
|
+
const lines = [forwardLine(msg), ...quoted, text, ...notes].filter(Boolean);
|
|
339
|
+
const pieces = split(lines.join("\n"));
|
|
340
|
+
if (!pieces[0] && !rec.getStringSlice("files").length) return;
|
|
341
|
+
// The parts still in the room get the pieces in order: a shorter text deletes the parts left over, a longer one adds
|
|
342
|
+
// parts (after what came since). A deleted message can't come back, so a part deleted meanwhile is passed over.
|
|
343
|
+
const parts = /** @type {core.Record[]} */ (
|
|
344
|
+
rows
|
|
345
|
+
.slice(1)
|
|
346
|
+
.map((r) => findMessage(app, r.getString("message")))
|
|
347
|
+
.filter((p) => !!p && !p.getBool("deleted"))
|
|
348
|
+
);
|
|
349
|
+
const next = rows.length ? rows[rows.length - 1].getInt("part") + 1 : 1;
|
|
350
|
+
app.runInTransaction((tx) => {
|
|
351
|
+
[rec, ...parts].forEach((part, i) => {
|
|
352
|
+
if (i >= pieces.length) part.set("deleted", true);
|
|
353
|
+
else if (pieces[i] === part.getString("text")) return;
|
|
354
|
+
else part.set("text", pieces[i]);
|
|
355
|
+
tx.save(part);
|
|
356
|
+
});
|
|
357
|
+
const ids = orderedIds(pieces.length);
|
|
358
|
+
for (let i = parts.length + 1; i < pieces.length; i++) {
|
|
359
|
+
const part = savePart(tx, rec.getString("room"), rec.getString("author"), pieces[i], ids[i]);
|
|
360
|
+
rememberIn(tx, part.id, chatId, msg.message_id, "text", next + i - parts.length - 1);
|
|
361
|
+
}
|
|
362
|
+
});
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/**
|
|
366
|
+
* @param {core.App} app
|
|
367
|
+
* @param {string} id
|
|
368
|
+
*/
|
|
369
|
+
function findMessage(app, id) {
|
|
370
|
+
try {
|
|
371
|
+
return app.findRecordById("messages", id);
|
|
372
|
+
} catch {
|
|
373
|
+
return null;
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/**
|
|
378
|
+
* Queue an album's item: the album becomes one message when it is complete (flushAlbums).
|
|
379
|
+
* @param {core.App} app
|
|
380
|
+
* @param {any} msg
|
|
381
|
+
*/
|
|
382
|
+
function queueAlbumItem(app, msg) {
|
|
383
|
+
const row = new Record(app.findCollectionByNameOrId("tg_queue"));
|
|
384
|
+
row.set("op", "album");
|
|
385
|
+
row.set("chat_id", String(msg.chat.id));
|
|
386
|
+
row.set("album", msg.media_group_id);
|
|
387
|
+
row.set("payload", msg);
|
|
388
|
+
app.save(row);
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/**
|
|
392
|
+
* Take an album's queued items, so only one caller brings it over.
|
|
393
|
+
* @param {core.App} app
|
|
394
|
+
* @param {string} chatId
|
|
395
|
+
* @param {string} album
|
|
396
|
+
* @returns {any[]} its Telegram messages
|
|
397
|
+
*/
|
|
398
|
+
function takeAlbum(app, chatId, album) {
|
|
399
|
+
/** @type {any[]} */
|
|
400
|
+
const msgs = [];
|
|
401
|
+
app.runInTransaction((tx) => {
|
|
402
|
+
const rows = tx.findRecordsByFilter("tg_queue", "op = 'album' && chat_id = {:chat} && album = {:album}", "created", 0, 0, {
|
|
403
|
+
chat: chatId,
|
|
404
|
+
album,
|
|
405
|
+
});
|
|
406
|
+
for (const row of rows) {
|
|
407
|
+
if (!row) continue;
|
|
408
|
+
msgs.push(JSON.parse(row.getString("payload") || "null"));
|
|
409
|
+
tx.delete(row);
|
|
410
|
+
}
|
|
411
|
+
});
|
|
412
|
+
return msgs.filter(Boolean);
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/**
|
|
416
|
+
* Bring over queued albums: those of `chatId` except `except` (something else came after them, so they are complete),
|
|
417
|
+
* or with no chat given, those quiet for ALBUM_QUIET_MS or full. `renew` (the worker's lock) after each one.
|
|
418
|
+
* @param {core.App} app
|
|
419
|
+
* @param {string} [chatId]
|
|
420
|
+
* @param {string} [except]
|
|
421
|
+
* @param {() => void} [renew]
|
|
422
|
+
*/
|
|
423
|
+
function flushAlbums(app, chatId, except, renew) {
|
|
424
|
+
const rows = chatId
|
|
425
|
+
? app.findRecordsByFilter("tg_queue", "op = 'album' && chat_id = {:chat}", "created", 0, 0, { chat: chatId })
|
|
426
|
+
: app.findRecordsByFilter("tg_queue", "op = 'album'", "created", 0, 0);
|
|
427
|
+
/** @type {Map<string, { chat: string, album: string, last: number, count: number }>} */
|
|
428
|
+
const groups = new Map();
|
|
429
|
+
for (const row of rows) {
|
|
430
|
+
if (!row) continue;
|
|
431
|
+
const key = `${row.getString("chat_id")} ${row.getString("album")}`;
|
|
432
|
+
const g = groups.get(key) || { chat: row.getString("chat_id"), album: row.getString("album"), last: 0, count: 0 };
|
|
433
|
+
g.last = Math.max(g.last, row.getDateTime("created").time().unixMilli());
|
|
434
|
+
g.count++;
|
|
435
|
+
groups.set(key, g);
|
|
436
|
+
}
|
|
437
|
+
for (const g of groups.values()) {
|
|
438
|
+
if (chatId ? g.album === except : g.count < MAX_FILES && Date.now() - g.last < ALBUM_QUIET_MS) continue;
|
|
439
|
+
const msgs = takeAlbum(app, g.chat, g.album);
|
|
440
|
+
const link = linkOfChat(app, g.chat);
|
|
441
|
+
const room = link && activeLink(app, link);
|
|
442
|
+
if (!msgs.length || !link || !room) continue;
|
|
443
|
+
try {
|
|
444
|
+
bringOver(app, link, room, msgs);
|
|
445
|
+
} catch (err) {
|
|
446
|
+
app.logger().error("telegram: album", "chat", g.chat, "error", String(err));
|
|
447
|
+
}
|
|
448
|
+
renew?.();
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
/** /chatid or /start, maybe addressed to the bot ("/chatid@my_bot"). */
|
|
453
|
+
const COMMAND = /^\/(chatid|start)(@\w+)?(\s|$)/;
|
|
454
|
+
|
|
455
|
+
/**
|
|
456
|
+
* Tell a group its id and whether it is linked: what a superuser needs to link it in the admin UI.
|
|
457
|
+
* @param {core.App} app
|
|
458
|
+
* @param {string} chatId
|
|
459
|
+
*/
|
|
460
|
+
function sayStatus(app, chatId) {
|
|
461
|
+
const link = linkOfChat(app, chatId);
|
|
462
|
+
const room = link && activeLink(app, link);
|
|
463
|
+
const text = room
|
|
464
|
+
? `This group is linked to the chat room "${room.getString("name")}". Chat id: ${chatId}`
|
|
465
|
+
: `This group isn't linked to a chat room yet. Chat id: ${chatId}\nAn admin of the chat links it in the admin UI (collection tg_links).`;
|
|
466
|
+
call("sendMessage", { chat_id: chatId, text });
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/**
|
|
470
|
+
* Handle one update, from the webhook or polling.
|
|
471
|
+
* @param {core.App} app
|
|
472
|
+
* @param {any} update
|
|
473
|
+
*/
|
|
474
|
+
function handleUpdate(app, update) {
|
|
475
|
+
if (update.my_chat_member) return memberChange(app, update.my_chat_member);
|
|
476
|
+
// Sent only where the bot is an admin (§26.9). What came before it must be there to react to.
|
|
477
|
+
if (update.message_reaction) {
|
|
478
|
+
if (update.message_reaction.chat) flushAlbums(app, String(update.message_reaction.chat.id));
|
|
479
|
+
return require(`${__hooks}/telegram/reactions.js`).reactionOver(app, update.message_reaction);
|
|
480
|
+
}
|
|
481
|
+
// A channel's posts and their edits come as channel_post and edited_channel_post, sent as the channel itself.
|
|
482
|
+
const posted = update.message || update.channel_post;
|
|
483
|
+
const edited = update.edited_message || update.edited_channel_post;
|
|
484
|
+
const msg = posted || edited;
|
|
485
|
+
if (!msg?.chat) return;
|
|
486
|
+
const chatId = String(msg.chat.id);
|
|
487
|
+
if (msg.chat.type === "private") {
|
|
488
|
+
if (posted)
|
|
489
|
+
call("sendMessage", { chat_id: chatId, text: "I bring messages between Telegram groups and chat rooms. Add me to a group." });
|
|
490
|
+
return;
|
|
491
|
+
}
|
|
492
|
+
// A group that became a supergroup: Telegram says so in both, in either order (QA BUG-89).
|
|
493
|
+
if (msg.migrate_to_chat_id) return moveLink(app, chatId, String(msg.migrate_to_chat_id));
|
|
494
|
+
if (msg.migrate_from_chat_id) return moveLink(app, String(msg.migrate_from_chat_id), chatId);
|
|
495
|
+
const link = ensureLink(app, msg.chat);
|
|
496
|
+
if (posted && COMMAND.test(msg.text || "")) return sayStatus(app, chatId);
|
|
497
|
+
const room = activeLink(app, link);
|
|
498
|
+
if (!room) return;
|
|
499
|
+
if (posted && msg.media_group_id) {
|
|
500
|
+
flushAlbums(app, chatId, msg.media_group_id);
|
|
501
|
+
queueAlbumItem(app, msg);
|
|
502
|
+
return;
|
|
503
|
+
}
|
|
504
|
+
flushAlbums(app, chatId); // what came before this must show before it
|
|
505
|
+
if (edited) editOver(app, msg);
|
|
506
|
+
else if (!msg.new_chat_members && !msg.left_chat_member && !msg.pinned_message && !msg.new_chat_title) bringOver(app, link, room, [msg]);
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
/**
|
|
510
|
+
* The bot was added to a group, or removed from it.
|
|
511
|
+
* @param {core.App} app
|
|
512
|
+
* @param {any} change
|
|
513
|
+
*/
|
|
514
|
+
function memberChange(app, change) {
|
|
515
|
+
if (change.chat.type === "private") return;
|
|
516
|
+
const status = change.new_chat_member?.status;
|
|
517
|
+
const link = ensureLink(app, change.chat);
|
|
518
|
+
if (status === "left" || status === "kicked") {
|
|
519
|
+
app.runInTransaction((tx) => {
|
|
520
|
+
// Read again in the transaction: the same news twice at once must tell the room once.
|
|
521
|
+
const fresh = tx.findRecordById("tg_links", link.id);
|
|
522
|
+
const was = linkedRoom(fresh);
|
|
523
|
+
if (!was) return;
|
|
524
|
+
fresh.set("enabled", false);
|
|
525
|
+
// Past the tg_links hooks, which would tell the room it was disconnected without saying why.
|
|
526
|
+
tx.unsafeWithoutHooks().save(fresh);
|
|
527
|
+
tellLinkChange(tx, fresh, was, "", ": the bot was removed from the group");
|
|
528
|
+
});
|
|
529
|
+
return;
|
|
530
|
+
}
|
|
531
|
+
const was = change.old_chat_member?.status;
|
|
532
|
+
if ((status === "member" || status === "administrator") && (was === "left" || was === "kicked")) sayStatus(app, String(change.chat.id));
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
/**
|
|
536
|
+
* POST /api/telegram/webhook: an update from Telegram, which signs it with the secret given to setWebhook. Always
|
|
537
|
+
* answers 200 once the secret is right: Telegram would retry a failed update, and one that can't be handled
|
|
538
|
+
* (logged) shouldn't block the ones after it.
|
|
539
|
+
* @param {core.RequestEvent} e
|
|
540
|
+
*/
|
|
541
|
+
function webhook(e) {
|
|
542
|
+
const given = e.request ? e.request.header.get("X-Telegram-Bot-Api-Secret-Token") : "";
|
|
543
|
+
if (!$security.equal(given, config().secret)) throw new UnauthorizedError("Wrong secret."); // in constant time (QA BUG-91)
|
|
544
|
+
const update = e.requestInfo().body;
|
|
545
|
+
try {
|
|
546
|
+
handleUpdate(e.app, update);
|
|
547
|
+
} catch (err) {
|
|
548
|
+
e.app.logger().error("telegram: update", "update", update?.update_id, "error", String(err));
|
|
549
|
+
}
|
|
550
|
+
return e.json(200, { ok: true });
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
module.exports = { webhook, handleUpdate, flushAlbums, mapped };
|