chirkle 0.0.0-stage → 0.1.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 +310 -2
- package/package.json +75 -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 +128 -0
- package/pb_hooks/telegram/inbound.js +548 -0
- package/pb_hooks/telegram/links.js +157 -0
- package/pb_hooks/telegram/outbound.js +323 -0
- package/pb_hooks/telegram/people.js +166 -0
- package/pb_hooks/telegram/rich.js +192 -0
- package/pb_hooks/telegram/worker.js +181 -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_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-ECR34OBK.css +2 -0
- package/pb_public/assets/app-ECR34OBK.css.map +7 -0
- package/pb_public/assets/app-SILEBEXB.js +3 -0
- package/pb_public/assets/app-SILEBEXB.js.map +7 -0
- package/pb_public/assets/collections-VEOIOCAW.css +2 -0
- package/pb_public/assets/collections-VEOIOCAW.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-SCCVSUZO.js +2 -0
- package/pb_public/assets/lazy-SCCVSUZO.js.map +7 -0
- package/pb_public/assets/media-DH7ECZSF.js +2 -0
- package/pb_public/assets/media-DH7ECZSF.js.map +7 -0
- package/pb_public/assets/media-L3EYTHKT.css +2 -0
- package/pb_public/assets/media-L3EYTHKT.css.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,157 @@
|
|
|
1
|
+
/// <reference path="../../types/pocketbase.d.ts" />
|
|
2
|
+
// Which Telegram group goes with which room (DESIGN.md §26.5, collection tg_links). A row appears, disabled and with
|
|
3
|
+
// no room, for every group the bot is in; a superuser links it in the admin UI by picking the room and enabling it.
|
|
4
|
+
|
|
5
|
+
const { postService } = require(`${__hooks}/lib/messages.js`);
|
|
6
|
+
const { fieldError, recordOf } = require(`${__hooks}/lib/records.js`);
|
|
7
|
+
const { isBlank, tidy } = require(`${__hooks}/lib/text.js`);
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* @param {core.App} app
|
|
11
|
+
* @param {string} chatId
|
|
12
|
+
*/
|
|
13
|
+
function linkOfChat(app, chatId) {
|
|
14
|
+
try {
|
|
15
|
+
return app.findFirstRecordByFilter("tg_links", "chat_id = {:chat}", { chat: chatId });
|
|
16
|
+
} catch {
|
|
17
|
+
return null;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* The room of a link that is in use: enabled, with a room that isn't archived. Null otherwise.
|
|
23
|
+
* @param {core.App} app
|
|
24
|
+
* @param {core.Record} link
|
|
25
|
+
*/
|
|
26
|
+
function activeLink(app, link) {
|
|
27
|
+
if (!link.getBool("enabled") || !link.getString("room")) return null;
|
|
28
|
+
try {
|
|
29
|
+
const room = app.findRecordById("rooms", link.getString("room"));
|
|
30
|
+
return room.getBool("archived") ? null : room;
|
|
31
|
+
} catch {
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* The enabled links of a room (a room may be linked to several groups).
|
|
38
|
+
* @param {core.App} app
|
|
39
|
+
* @param {string} roomId
|
|
40
|
+
*/
|
|
41
|
+
function linksOfRoom(app, roomId) {
|
|
42
|
+
return app.findRecordsByFilter("tg_links", "room = {:room} && enabled = true", "created", 0, 0, { room: roomId }).filter((l) => !!l);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* The group's link, made (disabled, no room) the first time the bot hears from it; its title kept up to date.
|
|
47
|
+
* @param {core.App} app
|
|
48
|
+
* @param {any} chat
|
|
49
|
+
*/
|
|
50
|
+
function ensureLink(app, chat) {
|
|
51
|
+
const chatId = String(chat.id);
|
|
52
|
+
const title = String(chat.title || "").slice(0, 255);
|
|
53
|
+
let link = linkOfChat(app, chatId);
|
|
54
|
+
if (!link) {
|
|
55
|
+
link = new Record(app.findCollectionByNameOrId("tg_links"));
|
|
56
|
+
link.set("chat_id", chatId);
|
|
57
|
+
link.set("title", title);
|
|
58
|
+
link.set("enabled", false);
|
|
59
|
+
try {
|
|
60
|
+
app.save(link);
|
|
61
|
+
} catch (err) {
|
|
62
|
+
const again = linkOfChat(app, chatId); // made meanwhile (the unique index)
|
|
63
|
+
if (!again) throw err;
|
|
64
|
+
link = again;
|
|
65
|
+
}
|
|
66
|
+
} else if (title && title !== link.getString("title")) {
|
|
67
|
+
link.set("title", title);
|
|
68
|
+
app.save(link);
|
|
69
|
+
}
|
|
70
|
+
return link;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* A group became a supergroup, which has a new id: its link follows.
|
|
75
|
+
* @param {core.App} app
|
|
76
|
+
* @param {string} from
|
|
77
|
+
* @param {string} to
|
|
78
|
+
*/
|
|
79
|
+
function moveLink(app, from, to) {
|
|
80
|
+
const link = linkOfChat(app, from);
|
|
81
|
+
if (!link) return;
|
|
82
|
+
app.runInTransaction((tx) => {
|
|
83
|
+
// The new group heard from first (QA BUG-89) has a link of its own, unused: the old group's takes its place.
|
|
84
|
+
const there = linkOfChat(tx, to);
|
|
85
|
+
if (there) {
|
|
86
|
+
if (there.getString("room") || there.getBool("enabled")) return;
|
|
87
|
+
tx.delete(there);
|
|
88
|
+
}
|
|
89
|
+
link.set("chat_id", to);
|
|
90
|
+
tx.save(link);
|
|
91
|
+
for (const table of ["tg_messages", "tg_queue"]) {
|
|
92
|
+
tx.db().newQuery(`UPDATE ${table} SET chat_id = {:to} WHERE chat_id = {:from}`).bind({ to, from }).execute();
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* tg_links create/update: only a room (not a DM) can be linked, and only a link with a room can be enabled.
|
|
99
|
+
* @param {core.RecordEvent} e
|
|
100
|
+
*/
|
|
101
|
+
function beforeLinkSave(e) {
|
|
102
|
+
const rec = recordOf(e);
|
|
103
|
+
const roomId = rec.getString("room");
|
|
104
|
+
if (roomId) {
|
|
105
|
+
const room = e.app.findRecordById("rooms", roomId);
|
|
106
|
+
if (room.getString("kind") === "dm") throw fieldError("room", "Direct messages can't be linked to Telegram.");
|
|
107
|
+
}
|
|
108
|
+
if (rec.getBool("enabled") && !roomId) throw fieldError("enabled", "Choose the room first.");
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* The room a link passes messages to: "" when disabled or without a room.
|
|
113
|
+
* @param {core.Record} link
|
|
114
|
+
*/
|
|
115
|
+
const linkedRoom = (link) => (link.getBool("enabled") ? link.getString("room") : "");
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* "Telegram group "Friends"", for service messages. The title is the group's (or a superuser's): tidied like a name,
|
|
119
|
+
* so it can't break the line or turn it around (bidi overrides), and a blank one is left out.
|
|
120
|
+
* @param {core.Record} link
|
|
121
|
+
*/
|
|
122
|
+
const groupName = (link) => {
|
|
123
|
+
const title = tidy(link.getString("title"));
|
|
124
|
+
return isBlank(title) ? "A Telegram group" : `Telegram group "${title}"`;
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* A service message (§5.3) in the room, unless it is gone or archived (it passes nothing then anyway).
|
|
129
|
+
* @param {core.App} app
|
|
130
|
+
* @param {string} roomId
|
|
131
|
+
* @param {string} text
|
|
132
|
+
*/
|
|
133
|
+
function tellRoom(app, roomId, text) {
|
|
134
|
+
try {
|
|
135
|
+
if (app.findRecordById("rooms", roomId).getBool("archived")) return;
|
|
136
|
+
} catch {
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
postService(app, roomId, text);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* tg_links saved or deleted: the room it stopped passing messages to and the one it started passing them to say so
|
|
144
|
+
* (a superuser linking, unlinking or moving it; the bot removed from the group).
|
|
145
|
+
* @param {core.App} app
|
|
146
|
+
* @param {core.Record} link
|
|
147
|
+
* @param {string} was linkedRoom before (read before the save)
|
|
148
|
+
* @param {string} now linkedRoom after: "" once deleted
|
|
149
|
+
* @param {string} [why] after "disconnected from this room", e.g. ": the bot was removed from the group"
|
|
150
|
+
*/
|
|
151
|
+
function tellLinkChange(app, link, was, now, why = "") {
|
|
152
|
+
if (was === now) return;
|
|
153
|
+
if (was) tellRoom(app, was, `${groupName(link)} was disconnected from this room${why}.`);
|
|
154
|
+
if (now) tellRoom(app, now, `${groupName(link)} was connected to this room.`);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
module.exports = { linkOfChat, activeLink, linksOfRoom, ensureLink, moveLink, beforeLinkSave, linkedRoom, tellLinkChange };
|
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
/// <reference path="../../types/pocketbase.d.ts" />
|
|
2
|
+
// Chirkle → Telegram (DESIGN.md §26.6). The messages hooks only queue the work (tg_queue): a message, edit or delete in
|
|
3
|
+
// a linked room. The worker (worker.js) sends it, so a user's request never waits for Telegram, and what Telegram
|
|
4
|
+
// refuses for now (it is down, or asks to slow down) is retried in order.
|
|
5
|
+
|
|
6
|
+
const { roomName, sourceName } = require(`${__hooks}/lib/anonymous.js`);
|
|
7
|
+
const { asTelegram, call } = require(`${__hooks}/telegram/api.js`);
|
|
8
|
+
const { linkOfChat, linksOfRoom } = require(`${__hooks}/telegram/links.js`);
|
|
9
|
+
|
|
10
|
+
/** Telegram's limits: a caption's length, and the largest photo it takes as a photo (bigger ones go as files). */
|
|
11
|
+
const MAX_CAPTION = 1024;
|
|
12
|
+
const MAX_PHOTO = 10 * 1024 * 1024;
|
|
13
|
+
|
|
14
|
+
const PHOTO_EXT = new Set(["jpg", "jpeg", "png", "webp"]);
|
|
15
|
+
/** A sticker's largest side: a lone WebP no bigger goes as a sticker, which keeps its transparency (a photo is made a JPEG). */
|
|
16
|
+
const MAX_STICKER = 512;
|
|
17
|
+
/** MPEG-4 and QuickTime (what phones record): Telegram plays them inline. WebM and Ogg would arrive as files anyway. */
|
|
18
|
+
const VIDEO_EXT = new Set(["mp4", "m4v", "mov"]);
|
|
19
|
+
/** A video plays while it downloads, rather than only once it has (Telegram shows it as a file to fetch first). */
|
|
20
|
+
const STREAM = { supports_streaming: true };
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* @param {core.App} app
|
|
24
|
+
* @param {string} op
|
|
25
|
+
* @param {string} messageId
|
|
26
|
+
* @param {string} chatId
|
|
27
|
+
*/
|
|
28
|
+
function enqueue(app, op, messageId, chatId) {
|
|
29
|
+
const row = new Record(app.findCollectionByNameOrId("tg_queue"));
|
|
30
|
+
row.set("op", op);
|
|
31
|
+
row.set("message", messageId);
|
|
32
|
+
row.set("chat_id", chatId);
|
|
33
|
+
app.save(row);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* messages create (saved): queue it for each group its room is linked to. A message that came from one of them is
|
|
38
|
+
* queued too, for the others; the worker leaves out the group it came from. Service messages (no author, §5.3) stay
|
|
39
|
+
* in the room.
|
|
40
|
+
* @param {core.App} app
|
|
41
|
+
* @param {core.Record} rec
|
|
42
|
+
*/
|
|
43
|
+
function queueCreate(app, rec) {
|
|
44
|
+
if (!rec.getString("author")) return;
|
|
45
|
+
for (const link of linksOfRoom(app, rec.getString("room"))) enqueue(app, "send", rec.id, link.getString("chat_id"));
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* What a messages update changes for Telegram, read before it is saved.
|
|
50
|
+
* @param {core.Record} rec
|
|
51
|
+
* @returns {"" | "edit" | "delete"}
|
|
52
|
+
*/
|
|
53
|
+
function changeOf(rec) {
|
|
54
|
+
const orig = rec.original();
|
|
55
|
+
if (rec.getBool("deleted") && !orig.getBool("deleted")) return "delete";
|
|
56
|
+
if (!rec.getBool("deleted") && rec.getString("text") !== orig.getString("text")) return "edit";
|
|
57
|
+
return "";
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* messages update (saved): queue an edit or delete for the groups of its room.
|
|
62
|
+
* @param {core.App} app
|
|
63
|
+
* @param {core.Record} rec
|
|
64
|
+
* @param {"" | "edit" | "delete"} change
|
|
65
|
+
*/
|
|
66
|
+
function queueUpdate(app, rec, change) {
|
|
67
|
+
if (!change || !rec.getString("author")) return; // a service message never went to Telegram
|
|
68
|
+
for (const link of linksOfRoom(app, rec.getString("room"))) enqueue(app, change, rec.id, link.getString("chat_id"));
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// ---------------------------------------------------------------- the worker's side
|
|
72
|
+
|
|
73
|
+
const esc = (/** @type {string} */ s) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
74
|
+
|
|
75
|
+
/** A header over a text, either of which may be "". */
|
|
76
|
+
const joined = (/** @type {string} */ header, /** @type {string} */ text) => (header && text ? `${header}\n${text}` : header || text);
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* @param {core.App} app
|
|
80
|
+
* @param {string} id
|
|
81
|
+
*/
|
|
82
|
+
function findMessage(app, id) {
|
|
83
|
+
try {
|
|
84
|
+
return app.findRecordById("messages", id);
|
|
85
|
+
} catch {
|
|
86
|
+
return null;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* @param {core.App} app
|
|
92
|
+
* @param {string} id
|
|
93
|
+
*/
|
|
94
|
+
function userName(app, id) {
|
|
95
|
+
try {
|
|
96
|
+
return app.findRecordById("users", id).getString("name");
|
|
97
|
+
} catch {
|
|
98
|
+
return "";
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* What a message shows, as Telegram HTML: its author in bold over its text; a forward says whose it is, and shows its
|
|
104
|
+
* original's text and files (§21.3). An anonymous link's group gets no header: only the text (and files). A message of an
|
|
105
|
+
* anonymous room is the room's, and a forward of one from its room (DESIGN.md §35).
|
|
106
|
+
* @param {core.App} app
|
|
107
|
+
* @param {core.Record} msg
|
|
108
|
+
* @param {boolean} anonymous
|
|
109
|
+
*/
|
|
110
|
+
function contentOf(app, msg, anonymous) {
|
|
111
|
+
let source = msg;
|
|
112
|
+
const author = msg.getBool("anonymous") ? roomName(app, msg.getString("room")) : userName(app, msg.getString("author"));
|
|
113
|
+
let header = anonymous ? "" : `<b>${esc(author || "Someone")}</b>`;
|
|
114
|
+
if (msg.getString("forwarded_from")) {
|
|
115
|
+
const original = msg.getString("forward_of") ? findMessage(app, msg.getString("forward_of")) : null;
|
|
116
|
+
const from = !msg.getBool("forwarded_anonymous")
|
|
117
|
+
? userName(app, msg.getString("forwarded_from"))
|
|
118
|
+
: original
|
|
119
|
+
? sourceName(app, original.getString("room"))
|
|
120
|
+
: "Anonymous";
|
|
121
|
+
if (!anonymous) header += ` <i>forwarded from ${esc(from || "someone")}</i>`;
|
|
122
|
+
if (msg.getString("forward_of")) source = original && !original.getBool("deleted") ? original : msg;
|
|
123
|
+
}
|
|
124
|
+
const text = source.getString("text");
|
|
125
|
+
const plain = joined(header.replace(/<[^>]+>/g, ""), text);
|
|
126
|
+
return { html: joined(header, esc(text)), plain, source, header, text };
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* The caption of a message's files: its content, the text cut to fit Telegram's limit. A message is sent with its text
|
|
131
|
+
* as a caption only when it fits, but an edit can make it longer, which Telegram would refuse (QA BUG-87).
|
|
132
|
+
* @param {ReturnType<typeof contentOf>} content
|
|
133
|
+
*/
|
|
134
|
+
function captionOf({ html, plain, header, text }) {
|
|
135
|
+
const over = [...plain].length - MAX_CAPTION;
|
|
136
|
+
if (over <= 0) return html;
|
|
137
|
+
const chars = [...text];
|
|
138
|
+
return joined(header, `${esc(chars.slice(0, chars.length - over - 1).join(""))}…`);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* @param {core.App} app
|
|
143
|
+
* @param {string} messageId
|
|
144
|
+
* @param {string} chatId
|
|
145
|
+
* @param {string} [filter] more conditions
|
|
146
|
+
*/
|
|
147
|
+
function mappings(app, messageId, chatId, filter = "") {
|
|
148
|
+
return app
|
|
149
|
+
.findRecordsByFilter("tg_messages", `message = {:message} && chat_id = {:chat}${filter}`, "tg_message_id", 0, 0, {
|
|
150
|
+
message: messageId,
|
|
151
|
+
chat: chatId,
|
|
152
|
+
})
|
|
153
|
+
.filter((r) => !!r);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Record what Telegram messages a chat message became.
|
|
158
|
+
* @param {core.App} app
|
|
159
|
+
* @param {string} messageId
|
|
160
|
+
* @param {string} chatId
|
|
161
|
+
* @param {any} sent Telegram's Message
|
|
162
|
+
* @param {"text" | "caption" | "media"} kind
|
|
163
|
+
*/
|
|
164
|
+
function remember(app, messageId, chatId, sent, kind) {
|
|
165
|
+
const row = new Record(app.findCollectionByNameOrId("tg_messages"));
|
|
166
|
+
row.set("message", messageId);
|
|
167
|
+
row.set("chat_id", chatId);
|
|
168
|
+
row.set("tg_message_id", sent.message_id);
|
|
169
|
+
row.set("direction", "out");
|
|
170
|
+
row.set("kind", kind);
|
|
171
|
+
app.save(row);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* A message's files as Telegram takes them: photos and videos (shown, and sent together as an album), and documents
|
|
176
|
+
* (an album of their own: Telegram doesn't mix them). Each is its shared file (§37); one that is gone is left out.
|
|
177
|
+
* @param {core.App} app
|
|
178
|
+
* @param {filesystem.System} fsys
|
|
179
|
+
* @param {core.Record} source
|
|
180
|
+
*/
|
|
181
|
+
function filesOf(app, fsys, source) {
|
|
182
|
+
const shared = require(`${__hooks}/lib/files.js`);
|
|
183
|
+
const names = /** @type {Record<string, string>} */ (JSON.parse(source.getString("file_names") || "{}") || {});
|
|
184
|
+
const dims = /** @type {Record<string, number[]>} */ (JSON.parse(source.getString("file_dims") || "{}") || {});
|
|
185
|
+
const rows = shared.byNames(app, source.getStringSlice("files"));
|
|
186
|
+
const all = source.getStringSlice("files").filter((name) => rows.has(name));
|
|
187
|
+
return all.map((name) => {
|
|
188
|
+
const key = shared.keyOf(/** @type {core.Record} */ (rows.get(name)));
|
|
189
|
+
const ext = name.slice(name.lastIndexOf(".") + 1).toLowerCase();
|
|
190
|
+
const size = fsys.attributes(key).size;
|
|
191
|
+
const [w, h] = Array.isArray(dims[name]) ? dims[name] : [];
|
|
192
|
+
const sticker = all.length === 1 && ext === "webp" && w > 0 && h > 0 && w <= MAX_STICKER && h <= MAX_STICKER;
|
|
193
|
+
const kind = sticker ? "sticker" : PHOTO_EXT.has(ext) && size <= MAX_PHOTO ? "photo" : VIDEO_EXT.has(ext) ? "video" : "document";
|
|
194
|
+
const file = fsys.getReuploadableFile(key, true);
|
|
195
|
+
file.name = names[name] || name.replace(/_[a-z0-9]{10}(\.[^.]*)?$/i, "$1");
|
|
196
|
+
return { kind, file };
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
const SEND = /** @type {Record<string, string>} */ ({
|
|
201
|
+
photo: "sendPhoto",
|
|
202
|
+
video: "sendVideo",
|
|
203
|
+
document: "sendDocument",
|
|
204
|
+
sticker: "sendSticker",
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Send a message to a group: its text (with its files as their caption when it fits), its files as one or two
|
|
209
|
+
* albums, as a reply when the message it answers is there.
|
|
210
|
+
* @param {core.App} app
|
|
211
|
+
* @param {string} messageId
|
|
212
|
+
* @param {string} chatId
|
|
213
|
+
*/
|
|
214
|
+
function send(app, messageId, chatId) {
|
|
215
|
+
const msg = findMessage(app, messageId);
|
|
216
|
+
if (!msg || msg.getBool("deleted")) return;
|
|
217
|
+
const link = linkOfChat(app, chatId);
|
|
218
|
+
if (!link?.getBool("enabled") || link.getString("room") !== msg.getString("room")) return;
|
|
219
|
+
// Came from this group, or already sent (a retry after the worker stopped halfway).
|
|
220
|
+
if (mappings(app, messageId, chatId).length) return;
|
|
221
|
+
|
|
222
|
+
const { html, plain, source } = contentOf(app, msg, link.getBool("anonymous"));
|
|
223
|
+
const replyTo = msg.getString("reply_to") ? mappings(app, msg.getString("reply_to"), chatId)[0] : null;
|
|
224
|
+
/** @type {any} */
|
|
225
|
+
let reply = replyTo ? { reply_parameters: { message_id: replyTo.getInt("tg_message_id"), allow_sending_without_reply: true } } : {};
|
|
226
|
+
|
|
227
|
+
const fsys = app.newFilesystem();
|
|
228
|
+
try {
|
|
229
|
+
const files = filesOf(app, fsys, source);
|
|
230
|
+
const groups = [files.filter((f) => f.kind !== "document"), files.filter((f) => f.kind === "document")].filter((g) => g.length);
|
|
231
|
+
// A sticker takes no caption: its text goes before it.
|
|
232
|
+
const captioned = groups.length && files[0].kind !== "sticker";
|
|
233
|
+
let caption = captioned && [...plain].length <= MAX_CAPTION ? { caption: html, parse_mode: "HTML" } : null;
|
|
234
|
+
// No text goes alone when there is none: an anonymous link's sticker, or a forward of a deleted message.
|
|
235
|
+
if (!caption && html) {
|
|
236
|
+
remember(app, messageId, chatId, call("sendMessage", { chat_id: chatId, text: html, parse_mode: "HTML", ...reply }), "text");
|
|
237
|
+
reply = {};
|
|
238
|
+
}
|
|
239
|
+
for (const group of groups) {
|
|
240
|
+
if (group.length === 1) {
|
|
241
|
+
const f = group[0];
|
|
242
|
+
const sent = call(
|
|
243
|
+
SEND[f.kind],
|
|
244
|
+
{ chat_id: chatId, ...(f.kind === "video" ? STREAM : {}), ...(caption || {}), ...reply },
|
|
245
|
+
{ [f.kind]: f.file },
|
|
246
|
+
);
|
|
247
|
+
remember(app, messageId, chatId, sent, caption ? "caption" : "media");
|
|
248
|
+
} else {
|
|
249
|
+
/** @type {Record<string, any>} */
|
|
250
|
+
const attach = {};
|
|
251
|
+
const media = group.map((f, i) => {
|
|
252
|
+
attach[`file${i}`] = f.file;
|
|
253
|
+
return {
|
|
254
|
+
type: f.kind,
|
|
255
|
+
media: `attach://file${i}`,
|
|
256
|
+
...(f.kind === "video" ? STREAM : {}),
|
|
257
|
+
...(i === 0 && caption ? caption : {}),
|
|
258
|
+
};
|
|
259
|
+
});
|
|
260
|
+
const sent = call("sendMediaGroup", { chat_id: chatId, media, ...reply }, attach);
|
|
261
|
+
for (let i = 0; i < sent.length; i++) remember(app, messageId, chatId, sent[i], i === 0 && caption ? "caption" : "media");
|
|
262
|
+
}
|
|
263
|
+
caption = null;
|
|
264
|
+
reply = {};
|
|
265
|
+
}
|
|
266
|
+
} finally {
|
|
267
|
+
fsys.close();
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* Pass an edit on: the Telegram messages that hold the text (sent from here) get the new one.
|
|
273
|
+
* @param {core.App} app
|
|
274
|
+
* @param {string} messageId
|
|
275
|
+
* @param {string} chatId
|
|
276
|
+
*/
|
|
277
|
+
function edit(app, messageId, chatId) {
|
|
278
|
+
const msg = findMessage(app, messageId);
|
|
279
|
+
if (!msg || msg.getBool("deleted")) return;
|
|
280
|
+
const content = contentOf(app, msg, !!linkOfChat(app, chatId)?.getBool("anonymous"));
|
|
281
|
+
const { html } = content;
|
|
282
|
+
for (const row of mappings(app, messageId, chatId, " && direction = 'out' && kind != 'media'")) {
|
|
283
|
+
const id = row.getInt("tg_message_id");
|
|
284
|
+
try {
|
|
285
|
+
if (row.getString("kind") === "text") call("editMessageText", { chat_id: chatId, message_id: id, text: html, parse_mode: "HTML" });
|
|
286
|
+
else call("editMessageCaption", { chat_id: chatId, message_id: id, caption: captionOf(content), parse_mode: "HTML" });
|
|
287
|
+
} catch (err) {
|
|
288
|
+
const tg = asTelegram(err);
|
|
289
|
+
if (!tg || tg.transient || !/not modified/i.test(tg.message)) throw err;
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* Pass a delete on: delete the Telegram messages. Bots can delete their own only for 48 hours (and others' only as an
|
|
296
|
+
* admin): one that stays says it was deleted instead.
|
|
297
|
+
* @param {core.App} app
|
|
298
|
+
* @param {string} messageId
|
|
299
|
+
* @param {string} chatId
|
|
300
|
+
*/
|
|
301
|
+
function remove(app, messageId, chatId) {
|
|
302
|
+
// A later part of a long Telegram message (§26.4) is only a piece of it: deleting it leaves the message there.
|
|
303
|
+
for (const row of mappings(app, messageId, chatId, " && part = 0")) {
|
|
304
|
+
const id = row.getInt("tg_message_id");
|
|
305
|
+
try {
|
|
306
|
+
call("deleteMessage", { chat_id: chatId, message_id: id });
|
|
307
|
+
} catch (err) {
|
|
308
|
+
const tg = asTelegram(err);
|
|
309
|
+
if (!tg || tg.transient) throw err;
|
|
310
|
+
if (row.getString("direction") !== "out" || row.getString("kind") === "media") continue;
|
|
311
|
+
const gone = "<i>Message deleted</i>";
|
|
312
|
+
try {
|
|
313
|
+
if (row.getString("kind") === "text") call("editMessageText", { chat_id: chatId, message_id: id, text: gone, parse_mode: "HTML" });
|
|
314
|
+
else call("editMessageCaption", { chat_id: chatId, message_id: id, caption: gone, parse_mode: "HTML" });
|
|
315
|
+
} catch (err2) {
|
|
316
|
+
const tg2 = asTelegram(err2);
|
|
317
|
+
if (!tg2 || tg2.transient) throw err2;
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
module.exports = { queueCreate, queueUpdate, changeOf, send, edit, remove };
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
/// <reference path="../../types/pocketbase.d.ts" />
|
|
2
|
+
// Telegram senders as chat users (DESIGN.md §26.3): each gets a stand-in user ("Ann (TG)") that their messages show
|
|
3
|
+
// under, with their Telegram profile picture. Stand-ins can't log in (an address nobody receives mail at, a random
|
|
4
|
+
// password nobody knows) and take no direct messages (`no_dms`, §16.7).
|
|
5
|
+
|
|
6
|
+
const { call, download } = require(`${__hooks}/telegram/api.js`);
|
|
7
|
+
const { fieldError } = require(`${__hooks}/lib/records.js`);
|
|
8
|
+
const { nameKey, tidy } = require(`${__hooks}/lib/text.js`);
|
|
9
|
+
|
|
10
|
+
/** users.name max. */
|
|
11
|
+
const NAME_MAX = 32;
|
|
12
|
+
const SUFFIX = " (TG)";
|
|
13
|
+
/** How often a sender's profile picture is checked for a change. */
|
|
14
|
+
const PHOTO_CHECK_MS = 24 * 60 * 60 * 1000;
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Who sent a Telegram message: a user, or a chat posting as itself (an anonymous admin, a linked channel).
|
|
18
|
+
* @param {any} msg
|
|
19
|
+
* @returns {{ id: string, name: string, username: string, isChat: boolean }}
|
|
20
|
+
*/
|
|
21
|
+
function senderOf(msg) {
|
|
22
|
+
const chat = msg.sender_chat;
|
|
23
|
+
if (chat) return { id: String(chat.id), name: chat.title || chat.username || "Telegram", username: chat.username || "", isChat: true };
|
|
24
|
+
const u = msg.from || {};
|
|
25
|
+
const name = [u.first_name, u.last_name].filter(Boolean).join(" ");
|
|
26
|
+
return { id: String(u.id), name: name || u.username || "Telegram user", username: u.username || "", isChat: false };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* "Ann (TG)", or "Ann 2 (TG)" and so on when that is taken (names are unique, §22.1), within users.name's 32.
|
|
31
|
+
* @param {string} name
|
|
32
|
+
* @param {number} n
|
|
33
|
+
*/
|
|
34
|
+
function displayName(name, n) {
|
|
35
|
+
const tail = `${n > 1 ? ` ${n}` : ""}${SUFFIX}`;
|
|
36
|
+
const base =
|
|
37
|
+
[...tidy(name)]
|
|
38
|
+
.slice(0, NAME_MAX - tail.length)
|
|
39
|
+
.join("")
|
|
40
|
+
.trim() || "Telegram user";
|
|
41
|
+
return `${base}${tail}`;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Save `user` with the first free display name for `name`.
|
|
46
|
+
* @param {core.App} app
|
|
47
|
+
* @param {core.Record} user
|
|
48
|
+
* @param {string} name
|
|
49
|
+
*/
|
|
50
|
+
function saveWithName(app, user, name) {
|
|
51
|
+
for (let n = 1; n < 1000; n++) {
|
|
52
|
+
const candidate = displayName(name, n);
|
|
53
|
+
try {
|
|
54
|
+
app.findFirstRecordByFilter("users", "name_key = {:key} && id != {:id}", { key: nameKey(candidate), id: user.id });
|
|
55
|
+
continue; // taken
|
|
56
|
+
} catch {
|
|
57
|
+
// free
|
|
58
|
+
}
|
|
59
|
+
user.set("name", candidate);
|
|
60
|
+
app.save(user);
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
throw new Error("no free display name");
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* The stand-in user of a Telegram sender, made on their first message. A changed Telegram name renames it.
|
|
68
|
+
* @param {core.App} app
|
|
69
|
+
* @param {any} msg
|
|
70
|
+
* @returns {core.Record} the users record
|
|
71
|
+
*/
|
|
72
|
+
function personOf(app, msg) {
|
|
73
|
+
const s = senderOf(msg);
|
|
74
|
+
let row = null;
|
|
75
|
+
try {
|
|
76
|
+
row = app.findFirstRecordByFilter("tg_people", "tg_user_id = {:id}", { id: s.id });
|
|
77
|
+
} catch {
|
|
78
|
+
row = null;
|
|
79
|
+
}
|
|
80
|
+
if (row) {
|
|
81
|
+
const user = app.findRecordById("users", row.getString("user"));
|
|
82
|
+
if (row.getString("name") !== s.name || row.getString("username") !== s.username) {
|
|
83
|
+
saveWithName(app, user, s.name);
|
|
84
|
+
row.set("name", s.name);
|
|
85
|
+
row.set("username", s.username);
|
|
86
|
+
app.save(row);
|
|
87
|
+
}
|
|
88
|
+
if (!s.isChat) refreshPhoto(app, row, user, s.id);
|
|
89
|
+
return user;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const user = new Record(app.findCollectionByNameOrId("users"));
|
|
93
|
+
user.set("email", `tg${s.id.replace(/\D/g, "")}.${$security.randomStringWithAlphabet(6, "abcdefghijklmnopqrstuvwxyz")}@telegram.invalid`);
|
|
94
|
+
user.setPassword($security.randomString(40));
|
|
95
|
+
user.set("no_dms", true);
|
|
96
|
+
saveWithName(app, user, s.name);
|
|
97
|
+
row = new Record(app.findCollectionByNameOrId("tg_people"));
|
|
98
|
+
row.set("tg_user_id", s.id);
|
|
99
|
+
row.set("user", user.id);
|
|
100
|
+
row.set("name", s.name);
|
|
101
|
+
row.set("username", s.username);
|
|
102
|
+
app.save(row);
|
|
103
|
+
if (!s.isChat) refreshPhoto(app, row, user, s.id);
|
|
104
|
+
return user;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Use the sender's Telegram profile picture as the stand-in's avatar: on their first message, then at most once a
|
|
109
|
+
* day. A picture that can't be fetched is left for the next check; the stand-in keeps its initials meanwhile.
|
|
110
|
+
* @param {core.App} app
|
|
111
|
+
* @param {core.Record} row tg_people
|
|
112
|
+
* @param {core.Record} user
|
|
113
|
+
* @param {string} tgUserId
|
|
114
|
+
*/
|
|
115
|
+
function refreshPhoto(app, row, user, tgUserId) {
|
|
116
|
+
const checked = row.getDateTime("photo_checked");
|
|
117
|
+
if (!checked.isZero() && Date.now() - checked.unix() * 1000 < PHOTO_CHECK_MS) return;
|
|
118
|
+
row.set("photo_checked", new DateTime());
|
|
119
|
+
app.save(row);
|
|
120
|
+
try {
|
|
121
|
+
const res = call("getUserProfilePhotos", { user_id: Number(tgUserId), limit: 1 });
|
|
122
|
+
const sizes = res?.photos?.[0] || [];
|
|
123
|
+
// The smallest size at least 160 px wide (avatars show at up to 96 px), else the largest.
|
|
124
|
+
const size = sizes.find((/** @type {any} */ p) => p.width >= 160) || sizes[sizes.length - 1];
|
|
125
|
+
const id = size ? size.file_unique_id : "";
|
|
126
|
+
if (id === row.getString("photo")) return;
|
|
127
|
+
user.set("avatar", size ? download(size.file_id, "avatar.jpg") : null);
|
|
128
|
+
app.save(user);
|
|
129
|
+
row.set("photo", id);
|
|
130
|
+
app.save(row);
|
|
131
|
+
} catch (err) {
|
|
132
|
+
app.logger().warn("telegram: profile picture", "tgUser", tgUserId, "error", String(err));
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Is this user a Telegram stand-in? Their messages came from Telegram and don't go back.
|
|
138
|
+
* @param {core.App} app
|
|
139
|
+
* @param {string} userId
|
|
140
|
+
*/
|
|
141
|
+
function isStandIn(app, userId) {
|
|
142
|
+
try {
|
|
143
|
+
app.findFirstRecordByFilter("tg_people", "user = {:user}", { user: userId });
|
|
144
|
+
return true;
|
|
145
|
+
} catch {
|
|
146
|
+
return false;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* users create/update request: a name ending in "(TG)", however written ("(tg)", full-width, spaced), is a stand-in's.
|
|
152
|
+
* Anyone else could pass for a Telegram person, here and in the groups (QA BUG-86). Superusers name anyone.
|
|
153
|
+
* @param {core.RecordRequestEvent} e
|
|
154
|
+
*/
|
|
155
|
+
function refuseStandInName(e) {
|
|
156
|
+
const rec = e.record;
|
|
157
|
+
if (!rec || e.hasSuperuserAuth()) return;
|
|
158
|
+
const name = rec.getString("name");
|
|
159
|
+
if (!rec.isNew() && name === rec.original().getString("name")) return;
|
|
160
|
+
// The name as it will be stored (cleanName tidies it after this hook): "Ann (TG)\u0001" is "Ann (TG)" (QA BUG-142).
|
|
161
|
+
if (nameKey(tidy(name)).replace(/\s+/g, "").endsWith(nameKey(SUFFIX).trim())) {
|
|
162
|
+
throw fieldError("name", "Names ending in (TG) are for people on Telegram. Choose another one.");
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
module.exports = { personOf, isStandIn, senderOf, displayName, refuseStandInName };
|