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.
Files changed (139) hide show
  1. package/LICENSE +674 -0
  2. package/README.md +326 -2
  3. package/package.json +76 -4
  4. package/pb_hooks/federation/config.js +276 -0
  5. package/pb_hooks/federation/inbox.js +316 -0
  6. package/pb_hooks/federation/messages.js +420 -0
  7. package/pb_hooks/federation/mirror.js +277 -0
  8. package/pb_hooks/federation/net.js +247 -0
  9. package/pb_hooks/federation/peers.js +490 -0
  10. package/pb_hooks/federation/people.js +376 -0
  11. package/pb_hooks/federation/rooms.js +552 -0
  12. package/pb_hooks/federation/worker.js +413 -0
  13. package/pb_hooks/federation.pb.js +141 -0
  14. package/pb_hooks/lib/access.js +102 -0
  15. package/pb_hooks/lib/account.js +31 -0
  16. package/pb_hooks/lib/anonymous.js +189 -0
  17. package/pb_hooks/lib/bulk.js +187 -0
  18. package/pb_hooks/lib/collections.js +587 -0
  19. package/pb_hooks/lib/dms.js +123 -0
  20. package/pb_hooks/lib/emoji.js +28 -0
  21. package/pb_hooks/lib/enrich.js +75 -0
  22. package/pb_hooks/lib/features.js +31 -0
  23. package/pb_hooks/lib/files.js +375 -0
  24. package/pb_hooks/lib/http.js +146 -0
  25. package/pb_hooks/lib/images.js +160 -0
  26. package/pb_hooks/lib/keepalive.js +31 -0
  27. package/pb_hooks/lib/lists.js +173 -0
  28. package/pb_hooks/lib/media.js +635 -0
  29. package/pb_hooks/lib/messages.js +519 -0
  30. package/pb_hooks/lib/moderation.js +128 -0
  31. package/pb_hooks/lib/outbound.js +116 -0
  32. package/pb_hooks/lib/pages.js +171 -0
  33. package/pb_hooks/lib/previews.js +346 -0
  34. package/pb_hooks/lib/reactions.js +110 -0
  35. package/pb_hooks/lib/reads.js +181 -0
  36. package/pb_hooks/lib/records.js +77 -0
  37. package/pb_hooks/lib/rooms.js +148 -0
  38. package/pb_hooks/lib/site.js +102 -0
  39. package/pb_hooks/lib/text.js +110 -0
  40. package/pb_hooks/lib/users.js +81 -0
  41. package/pb_hooks/lib/worker.js +159 -0
  42. package/pb_hooks/main.pb.js +324 -0
  43. package/pb_hooks/telegram/api.js +129 -0
  44. package/pb_hooks/telegram/inbound.js +553 -0
  45. package/pb_hooks/telegram/links.js +157 -0
  46. package/pb_hooks/telegram/outbound.js +352 -0
  47. package/pb_hooks/telegram/people.js +166 -0
  48. package/pb_hooks/telegram/reactions.js +137 -0
  49. package/pb_hooks/telegram/rich.js +192 -0
  50. package/pb_hooks/telegram/worker.js +182 -0
  51. package/pb_hooks/telegram.pb.js +47 -0
  52. package/pb_migrations/1760000000_init.js +150 -0
  53. package/pb_migrations/1760000001_qa_fixes.js +69 -0
  54. package/pb_migrations/1760000002_avatars.js +39 -0
  55. package/pb_migrations/1760000003_direct_messages.js +142 -0
  56. package/pb_migrations/1760000004_attachments.js +28 -0
  57. package/pb_migrations/1760000005_file_names.js +16 -0
  58. package/pb_migrations/1760000006_room_reads.js +41 -0
  59. package/pb_migrations/1760000007_replies.js +23 -0
  60. package/pb_migrations/1760000008_lowercase_emails.js +24 -0
  61. package/pb_migrations/1760000009_reactions.js +32 -0
  62. package/pb_migrations/1760000010_fit_thumbs.js +18 -0
  63. package/pb_migrations/1760000011_forwarding.js +39 -0
  64. package/pb_migrations/1760000012_accounts.js +55 -0
  65. package/pb_migrations/1760000013_qa_pass5.js +19 -0
  66. package/pb_migrations/1760000014_room_access.js +96 -0
  67. package/pb_migrations/1760000015_site.js +46 -0
  68. package/pb_migrations/1760000016_forward_refs.js +43 -0
  69. package/pb_migrations/1760000017_no_dms.js +18 -0
  70. package/pb_migrations/1760000018_attachment_limits.js +24 -0
  71. package/pb_migrations/1760000019_telegram.js +109 -0
  72. package/pb_migrations/1760000020_service_messages.js +21 -0
  73. package/pb_migrations/1760000021_forward_view_index.js +41 -0
  74. package/pb_migrations/1760000022_link_previews.js +43 -0
  75. package/pb_migrations/1760000023_room_writers.js +49 -0
  76. package/pb_migrations/1760000024_message_search.js +51 -0
  77. package/pb_migrations/1760000025_search_dotted_i.js +16 -0
  78. package/pb_migrations/1760000026_push.js +67 -0
  79. package/pb_migrations/1760000027_push_tokens_per_user.js +31 -0
  80. package/pb_migrations/1760000028_media_grid_thumbs.js +18 -0
  81. package/pb_migrations/1760000029_media.js +71 -0
  82. package/pb_migrations/1760000030_collections.js +140 -0
  83. package/pb_migrations/1760000031_unread_limit.js +20 -0
  84. package/pb_migrations/1760000032_federation.js +227 -0
  85. package/pb_migrations/1760000033_federation_requests.js +44 -0
  86. package/pb_migrations/1760000034_telegram_parts.js +26 -0
  87. package/pb_migrations/1760000035_telegram_anonymous.js +16 -0
  88. package/pb_migrations/1760000036_chirkle.js +20 -0
  89. package/pb_migrations/1760000037_file_dims.js +35 -0
  90. package/pb_migrations/1760000038_drop_push.js +64 -0
  91. package/pb_migrations/1760000039_anonymous_rooms.js +40 -0
  92. package/pb_migrations/1760000040_moderators.js +42 -0
  93. package/pb_migrations/1760000041_shared_files.js +500 -0
  94. package/pb_migrations/1760000042_files_src.js +17 -0
  95. package/pb_migrations/1760000043_telegram_reactions.js +21 -0
  96. package/pb_public/assets/access-ALBW2MT2.js +2 -0
  97. package/pb_public/assets/access-ALBW2MT2.js.map +7 -0
  98. package/pb_public/assets/access-PB77EH4F.css +2 -0
  99. package/pb_public/assets/access-PB77EH4F.css.map +7 -0
  100. package/pb_public/assets/app-A3SXD3FF.css +2 -0
  101. package/pb_public/assets/app-A3SXD3FF.css.map +7 -0
  102. package/pb_public/assets/app-NDSIQW4L.js +3 -0
  103. package/pb_public/assets/app-NDSIQW4L.js.map +7 -0
  104. package/pb_public/assets/collections-DHJEOLHW.css +2 -0
  105. package/pb_public/assets/collections-DHJEOLHW.css.map +7 -0
  106. package/pb_public/assets/emoji-WSTVXAW5.css +2 -0
  107. package/pb_public/assets/emoji-WSTVXAW5.css.map +7 -0
  108. package/pb_public/assets/emoji-picker-QYRX6NYL.js +609 -0
  109. package/pb_public/assets/emoji-picker-QYRX6NYL.js.map +7 -0
  110. package/pb_public/assets/inter-cyrillic-JEOLYBOO.woff2 +0 -0
  111. package/pb_public/assets/inter-cyrillic-ext-IYF56FF6.woff2 +0 -0
  112. package/pb_public/assets/inter-greek-IRE366VL.woff2 +0 -0
  113. package/pb_public/assets/inter-latin-NRMW37G5.woff2 +0 -0
  114. package/pb_public/assets/inter-latin-ext-HA22NDSG.woff2 +0 -0
  115. package/pb_public/assets/lazy-4CXRBHHM.js +2 -0
  116. package/pb_public/assets/lazy-4CXRBHHM.js.map +7 -0
  117. package/pb_public/assets/media-7TCBG7WM.css +2 -0
  118. package/pb_public/assets/media-7TCBG7WM.css.map +7 -0
  119. package/pb_public/assets/media-FPRU2QH5.js +2 -0
  120. package/pb_public/assets/media-FPRU2QH5.js.map +7 -0
  121. package/pb_public/assets/notify-L6GERFNO.js +2 -0
  122. package/pb_public/assets/notify-L6GERFNO.js.map +7 -0
  123. package/pb_public/assets/search-3UT4HMES.js +2 -0
  124. package/pb_public/assets/search-3UT4HMES.js.map +7 -0
  125. package/pb_public/assets/switcher-CEUKRLEY.js +2 -0
  126. package/pb_public/assets/switcher-CEUKRLEY.js.map +7 -0
  127. package/pb_public/assets/viewer-DXT7SKOU.js +2 -0
  128. package/pb_public/assets/viewer-DXT7SKOU.js.map +7 -0
  129. package/pb_public/assets/viewer-P7GYCBYM.css +2 -0
  130. package/pb_public/assets/viewer-P7GYCBYM.css.map +7 -0
  131. package/pb_public/icons/apple-touch-icon.png +0 -0
  132. package/pb_public/icons/icon-192.png +0 -0
  133. package/pb_public/icons/icon-512.png +0 -0
  134. package/pb_public/icons/icon.svg +1 -0
  135. package/pb_public/icons/maskable-512.png +0 -0
  136. package/pb_public/index.html +21 -0
  137. package/pb_public/sw.js +1 -0
  138. package/scripts/fetch-pocketbase.sh +63 -0
  139. 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,352 @@
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: "react" when the bot's reaction on it would
50
+ * change (§26.9).
51
+ * @param {core.App} app
52
+ * @param {core.Record} rec
53
+ * @returns {"" | "edit" | "delete" | "react"}
54
+ */
55
+ function changeOf(app, rec) {
56
+ const orig = rec.original();
57
+ if (rec.getBool("deleted") && !orig.getBool("deleted")) return "delete";
58
+ if (!rec.getBool("deleted") && rec.getString("text") !== orig.getString("text")) return "edit";
59
+ if (rec.getString("reactions") !== orig.getString("reactions")) {
60
+ const { botReaction } = require(`${__hooks}/telegram/reactions.js`);
61
+ if (botReaction(app, rec) !== botReaction(app, orig)) return "react";
62
+ }
63
+ return "";
64
+ }
65
+
66
+ /**
67
+ * messages update (saved): queue an edit, delete or reaction for the groups of its room. A reaction already waiting
68
+ * for a group isn't queued again: it sends the message's reactions as they are when it goes.
69
+ * @param {core.App} app
70
+ * @param {core.Record} rec
71
+ * @param {"" | "edit" | "delete" | "react"} change
72
+ */
73
+ function queueUpdate(app, rec, change) {
74
+ if (!change || !rec.getString("author")) return; // a service message never went to Telegram
75
+ for (const link of linksOfRoom(app, rec.getString("room"))) {
76
+ const chatId = link.getString("chat_id");
77
+ if (change === "react" && waiting(app, rec.id, chatId)) continue;
78
+ enqueue(app, change, rec.id, chatId);
79
+ }
80
+ }
81
+
82
+ /**
83
+ * Is a reaction of this message queued for this group and not yet taken by the worker?
84
+ * @param {core.App} app
85
+ * @param {string} messageId
86
+ * @param {string} chatId
87
+ */
88
+ function waiting(app, messageId, chatId) {
89
+ try {
90
+ app.findFirstRecordByFilter("tg_queue", "op = 'react' && message = {:message} && chat_id = {:chat} && locked_until = ''", {
91
+ message: messageId,
92
+ chat: chatId,
93
+ });
94
+ return true;
95
+ } catch {
96
+ return false;
97
+ }
98
+ }
99
+
100
+ // ---------------------------------------------------------------- the worker's side
101
+
102
+ const esc = (/** @type {string} */ s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
103
+
104
+ /** A header over a text, either of which may be "". */
105
+ const joined = (/** @type {string} */ header, /** @type {string} */ text) => (header && text ? `${header}\n${text}` : header || text);
106
+
107
+ /**
108
+ * @param {core.App} app
109
+ * @param {string} id
110
+ */
111
+ function findMessage(app, id) {
112
+ try {
113
+ return app.findRecordById("messages", id);
114
+ } catch {
115
+ return null;
116
+ }
117
+ }
118
+
119
+ /**
120
+ * @param {core.App} app
121
+ * @param {string} id
122
+ */
123
+ function userName(app, id) {
124
+ try {
125
+ return app.findRecordById("users", id).getString("name");
126
+ } catch {
127
+ return "";
128
+ }
129
+ }
130
+
131
+ /**
132
+ * What a message shows, as Telegram HTML: its author in bold over its text; a forward says whose it is, and shows its
133
+ * original's text and files (§21.3). An anonymous link's group gets no header: only the text (and files). A message of an
134
+ * anonymous room is the room's, and a forward of one from its room (DESIGN.md §35).
135
+ * @param {core.App} app
136
+ * @param {core.Record} msg
137
+ * @param {boolean} anonymous
138
+ */
139
+ function contentOf(app, msg, anonymous) {
140
+ let source = msg;
141
+ const author = msg.getBool("anonymous") ? roomName(app, msg.getString("room")) : userName(app, msg.getString("author"));
142
+ let header = anonymous ? "" : `<b>${esc(author || "Someone")}</b>`;
143
+ if (msg.getString("forwarded_from")) {
144
+ const original = msg.getString("forward_of") ? findMessage(app, msg.getString("forward_of")) : null;
145
+ const from = !msg.getBool("forwarded_anonymous")
146
+ ? userName(app, msg.getString("forwarded_from"))
147
+ : original
148
+ ? sourceName(app, original.getString("room"))
149
+ : "Anonymous";
150
+ if (!anonymous) header += ` <i>forwarded from ${esc(from || "someone")}</i>`;
151
+ if (msg.getString("forward_of")) source = original && !original.getBool("deleted") ? original : msg;
152
+ }
153
+ const text = source.getString("text");
154
+ const plain = joined(header.replace(/<[^>]+>/g, ""), text);
155
+ return { html: joined(header, esc(text)), plain, source, header, text };
156
+ }
157
+
158
+ /**
159
+ * The caption of a message's files: its content, the text cut to fit Telegram's limit. A message is sent with its text
160
+ * as a caption only when it fits, but an edit can make it longer, which Telegram would refuse (QA BUG-87).
161
+ * @param {ReturnType<typeof contentOf>} content
162
+ */
163
+ function captionOf({ html, plain, header, text }) {
164
+ const over = [...plain].length - MAX_CAPTION;
165
+ if (over <= 0) return html;
166
+ const chars = [...text];
167
+ return joined(header, `${esc(chars.slice(0, chars.length - over - 1).join(""))}…`);
168
+ }
169
+
170
+ /**
171
+ * @param {core.App} app
172
+ * @param {string} messageId
173
+ * @param {string} chatId
174
+ * @param {string} [filter] more conditions
175
+ */
176
+ function mappings(app, messageId, chatId, filter = "") {
177
+ return app
178
+ .findRecordsByFilter("tg_messages", `message = {:message} && chat_id = {:chat}${filter}`, "tg_message_id", 0, 0, {
179
+ message: messageId,
180
+ chat: chatId,
181
+ })
182
+ .filter((r) => !!r);
183
+ }
184
+
185
+ /**
186
+ * Record what Telegram messages a chat message became.
187
+ * @param {core.App} app
188
+ * @param {string} messageId
189
+ * @param {string} chatId
190
+ * @param {any} sent Telegram's Message
191
+ * @param {"text" | "caption" | "media"} kind
192
+ */
193
+ function remember(app, messageId, chatId, sent, kind) {
194
+ const row = new Record(app.findCollectionByNameOrId("tg_messages"));
195
+ row.set("message", messageId);
196
+ row.set("chat_id", chatId);
197
+ row.set("tg_message_id", sent.message_id);
198
+ row.set("direction", "out");
199
+ row.set("kind", kind);
200
+ app.save(row);
201
+ }
202
+
203
+ /**
204
+ * A message's files as Telegram takes them: photos and videos (shown, and sent together as an album), and documents
205
+ * (an album of their own: Telegram doesn't mix them). Each is its shared file (§37); one that is gone is left out.
206
+ * @param {core.App} app
207
+ * @param {filesystem.System} fsys
208
+ * @param {core.Record} source
209
+ */
210
+ function filesOf(app, fsys, source) {
211
+ const shared = require(`${__hooks}/lib/files.js`);
212
+ const names = /** @type {Record<string, string>} */ (JSON.parse(source.getString("file_names") || "{}") || {});
213
+ const dims = /** @type {Record<string, number[]>} */ (JSON.parse(source.getString("file_dims") || "{}") || {});
214
+ const rows = shared.byNames(app, source.getStringSlice("files"));
215
+ const all = source.getStringSlice("files").filter((name) => rows.has(name));
216
+ return all.map((name) => {
217
+ const key = shared.keyOf(/** @type {core.Record} */ (rows.get(name)));
218
+ const ext = name.slice(name.lastIndexOf(".") + 1).toLowerCase();
219
+ const size = fsys.attributes(key).size;
220
+ const [w, h] = Array.isArray(dims[name]) ? dims[name] : [];
221
+ const sticker = all.length === 1 && ext === "webp" && w > 0 && h > 0 && w <= MAX_STICKER && h <= MAX_STICKER;
222
+ const kind = sticker ? "sticker" : PHOTO_EXT.has(ext) && size <= MAX_PHOTO ? "photo" : VIDEO_EXT.has(ext) ? "video" : "document";
223
+ const file = fsys.getReuploadableFile(key, true);
224
+ file.name = names[name] || name.replace(/_[a-z0-9]{10}(\.[^.]*)?$/i, "$1");
225
+ return { kind, file };
226
+ });
227
+ }
228
+
229
+ const SEND = /** @type {Record<string, string>} */ ({
230
+ photo: "sendPhoto",
231
+ video: "sendVideo",
232
+ document: "sendDocument",
233
+ sticker: "sendSticker",
234
+ });
235
+
236
+ /**
237
+ * Send a message to a group: its text (with its files as their caption when it fits), its files as one or two
238
+ * albums, as a reply when the message it answers is there.
239
+ * @param {core.App} app
240
+ * @param {string} messageId
241
+ * @param {string} chatId
242
+ */
243
+ function send(app, messageId, chatId) {
244
+ const msg = findMessage(app, messageId);
245
+ if (!msg || msg.getBool("deleted")) return;
246
+ const link = linkOfChat(app, chatId);
247
+ if (!link?.getBool("enabled") || link.getString("room") !== msg.getString("room")) return;
248
+ // Came from this group, or already sent (a retry after the worker stopped halfway).
249
+ if (mappings(app, messageId, chatId).length) return;
250
+
251
+ const { html, plain, source } = contentOf(app, msg, link.getBool("anonymous"));
252
+ const replyTo = msg.getString("reply_to") ? mappings(app, msg.getString("reply_to"), chatId)[0] : null;
253
+ /** @type {any} */
254
+ let reply = replyTo ? { reply_parameters: { message_id: replyTo.getInt("tg_message_id"), allow_sending_without_reply: true } } : {};
255
+
256
+ const fsys = app.newFilesystem();
257
+ try {
258
+ const files = filesOf(app, fsys, source);
259
+ const groups = [files.filter((f) => f.kind !== "document"), files.filter((f) => f.kind === "document")].filter((g) => g.length);
260
+ // A sticker takes no caption: its text goes before it.
261
+ const captioned = groups.length && files[0].kind !== "sticker";
262
+ let caption = captioned && [...plain].length <= MAX_CAPTION ? { caption: html, parse_mode: "HTML" } : null;
263
+ // No text goes alone when there is none: an anonymous link's sticker, or a forward of a deleted message.
264
+ if (!caption && html) {
265
+ remember(app, messageId, chatId, call("sendMessage", { chat_id: chatId, text: html, parse_mode: "HTML", ...reply }), "text");
266
+ reply = {};
267
+ }
268
+ for (const group of groups) {
269
+ if (group.length === 1) {
270
+ const f = group[0];
271
+ const sent = call(
272
+ SEND[f.kind],
273
+ { chat_id: chatId, ...(f.kind === "video" ? STREAM : {}), ...(caption || {}), ...reply },
274
+ { [f.kind]: f.file },
275
+ );
276
+ remember(app, messageId, chatId, sent, caption ? "caption" : "media");
277
+ } else {
278
+ /** @type {Record<string, any>} */
279
+ const attach = {};
280
+ const media = group.map((f, i) => {
281
+ attach[`file${i}`] = f.file;
282
+ return {
283
+ type: f.kind,
284
+ media: `attach://file${i}`,
285
+ ...(f.kind === "video" ? STREAM : {}),
286
+ ...(i === 0 && caption ? caption : {}),
287
+ };
288
+ });
289
+ const sent = call("sendMediaGroup", { chat_id: chatId, media, ...reply }, attach);
290
+ for (let i = 0; i < sent.length; i++) remember(app, messageId, chatId, sent[i], i === 0 && caption ? "caption" : "media");
291
+ }
292
+ caption = null;
293
+ reply = {};
294
+ }
295
+ } finally {
296
+ fsys.close();
297
+ }
298
+ }
299
+
300
+ /**
301
+ * Pass an edit on: the Telegram messages that hold the text (sent from here) get the new one.
302
+ * @param {core.App} app
303
+ * @param {string} messageId
304
+ * @param {string} chatId
305
+ */
306
+ function edit(app, messageId, chatId) {
307
+ const msg = findMessage(app, messageId);
308
+ if (!msg || msg.getBool("deleted")) return;
309
+ const content = contentOf(app, msg, !!linkOfChat(app, chatId)?.getBool("anonymous"));
310
+ const { html } = content;
311
+ for (const row of mappings(app, messageId, chatId, " && direction = 'out' && kind != 'media'")) {
312
+ const id = row.getInt("tg_message_id");
313
+ try {
314
+ if (row.getString("kind") === "text") call("editMessageText", { chat_id: chatId, message_id: id, text: html, parse_mode: "HTML" });
315
+ else call("editMessageCaption", { chat_id: chatId, message_id: id, caption: captionOf(content), parse_mode: "HTML" });
316
+ } catch (err) {
317
+ const tg = asTelegram(err);
318
+ if (!tg || tg.transient || !/not modified/i.test(tg.message)) throw err;
319
+ }
320
+ }
321
+ }
322
+
323
+ /**
324
+ * Pass a delete on: delete the Telegram messages. Bots can delete their own only for 48 hours (and others' only as an
325
+ * admin): one that stays says it was deleted instead.
326
+ * @param {core.App} app
327
+ * @param {string} messageId
328
+ * @param {string} chatId
329
+ */
330
+ function remove(app, messageId, chatId) {
331
+ // A later part of a long Telegram message (§26.4) is only a piece of it: deleting it leaves the message there.
332
+ for (const row of mappings(app, messageId, chatId, " && part = 0")) {
333
+ const id = row.getInt("tg_message_id");
334
+ try {
335
+ call("deleteMessage", { chat_id: chatId, message_id: id });
336
+ } catch (err) {
337
+ const tg = asTelegram(err);
338
+ if (!tg || tg.transient) throw err;
339
+ if (row.getString("direction") !== "out" || row.getString("kind") === "media") continue;
340
+ const gone = "<i>Message deleted</i>";
341
+ try {
342
+ if (row.getString("kind") === "text") call("editMessageText", { chat_id: chatId, message_id: id, text: gone, parse_mode: "HTML" });
343
+ else call("editMessageCaption", { chat_id: chatId, message_id: id, caption: gone, parse_mode: "HTML" });
344
+ } catch (err2) {
345
+ const tg2 = asTelegram(err2);
346
+ if (!tg2 || tg2.transient) throw err2;
347
+ }
348
+ }
349
+ }
350
+ }
351
+
352
+ 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 };