chirkle 0.2.0 → 0.3.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 (64) hide show
  1. package/README.md +4 -1
  2. package/package.json +1 -1
  3. package/pb_hooks/federation/messages.js +48 -2
  4. package/pb_hooks/lib/anonymous.js +10 -6
  5. package/pb_hooks/lib/bulk.js +2 -0
  6. package/pb_hooks/lib/files.js +39 -47
  7. package/pb_hooks/lib/handles.js +337 -0
  8. package/pb_hooks/lib/http.js +35 -23
  9. package/pb_hooks/lib/inbox.js +383 -0
  10. package/pb_hooks/lib/lists.js +8 -2
  11. package/pb_hooks/lib/live.js +137 -0
  12. package/pb_hooks/lib/messages.js +4 -0
  13. package/pb_hooks/lib/reactions.js +2 -0
  14. package/pb_hooks/lib/reads.js +3 -1
  15. package/pb_hooks/lib/site.js +1 -1
  16. package/pb_hooks/lib/stats.js +252 -0
  17. package/pb_hooks/lib/users.js +6 -1
  18. package/pb_hooks/main.pb.js +103 -26
  19. package/pb_hooks/telegram/people.js +4 -0
  20. package/pb_hooks/telegram/reactions.js +67 -11
  21. package/pb_migrations/1760000044_stats.js +70 -0
  22. package/pb_migrations/1760000045_mentions.js +187 -0
  23. package/pb_migrations/1760000046_reserved_handles.js +29 -0
  24. package/pb_public/assets/access-GUDTDXIP.js +2 -0
  25. package/pb_public/assets/access-GUDTDXIP.js.map +7 -0
  26. package/pb_public/assets/app-3WX5JYL2.js +3 -0
  27. package/pb_public/assets/app-3WX5JYL2.js.map +7 -0
  28. package/pb_public/assets/app-WAFKVN2H.css +2 -0
  29. package/pb_public/assets/app-WAFKVN2H.css.map +7 -0
  30. package/pb_public/assets/{emoji-WSTVXAW5.css → emoji-VA2WCEAC.css} +2 -2
  31. package/pb_public/assets/{emoji-WSTVXAW5.css.map → emoji-VA2WCEAC.css.map} +2 -2
  32. package/pb_public/assets/{emoji-picker-QYRX6NYL.js → emoji-picker-65VVVGYW.js} +2 -2
  33. package/pb_public/assets/forward-66PELNWT.js +2 -0
  34. package/pb_public/assets/forward-66PELNWT.js.map +7 -0
  35. package/pb_public/assets/inbox-3FSOPY2T.css +2 -0
  36. package/pb_public/assets/inbox-3FSOPY2T.css.map +7 -0
  37. package/pb_public/assets/inbox-TZJWPRTG.js +2 -0
  38. package/pb_public/assets/inbox-TZJWPRTG.js.map +7 -0
  39. package/pb_public/assets/login-G7Y44CJ7.js +2 -0
  40. package/pb_public/assets/login-G7Y44CJ7.js.map +7 -0
  41. package/pb_public/assets/mention-suggest-R7MXUH6R.js +2 -0
  42. package/pb_public/assets/mention-suggest-R7MXUH6R.js.map +7 -0
  43. package/pb_public/assets/notify-RQ6ZLR46.js +2 -0
  44. package/pb_public/assets/notify-RQ6ZLR46.js.map +7 -0
  45. package/pb_public/assets/profile-2CNVT2KX.js +2 -0
  46. package/pb_public/assets/profile-2CNVT2KX.js.map +7 -0
  47. package/pb_public/assets/stats-A2TBRUI6.css +2 -0
  48. package/pb_public/assets/stats-A2TBRUI6.css.map +7 -0
  49. package/pb_public/assets/stats-JX52AQCO.js +2 -0
  50. package/pb_public/assets/stats-JX52AQCO.js.map +7 -0
  51. package/pb_public/assets/user-search-7GNEIXMN.js +2 -0
  52. package/pb_public/assets/user-search-7GNEIXMN.js.map +7 -0
  53. package/pb_public/index.html +2 -2
  54. package/pb_public/stats.html +25 -0
  55. package/pb_public/sw.js +1 -1
  56. package/pb_public/assets/access-ALBW2MT2.js +0 -2
  57. package/pb_public/assets/access-ALBW2MT2.js.map +0 -7
  58. package/pb_public/assets/app-A3SXD3FF.css +0 -2
  59. package/pb_public/assets/app-A3SXD3FF.css.map +0 -7
  60. package/pb_public/assets/app-NDSIQW4L.js +0 -3
  61. package/pb_public/assets/app-NDSIQW4L.js.map +0 -7
  62. package/pb_public/assets/notify-L6GERFNO.js +0 -2
  63. package/pb_public/assets/notify-L6GERFNO.js.map +0 -7
  64. /package/pb_public/assets/{emoji-picker-QYRX6NYL.js.map → emoji-picker-65VVVGYW.js.map} +0 -0
@@ -92,7 +92,9 @@ function unread(e) {
92
92
  if (row.id) ids.push(row.id);
93
93
  else out[row.room] = row.n;
94
94
  }
95
- return e.json(200, { at, rooms: out, ids });
95
+ // The inbox's unseen rows and each room's unread mentions and replies (§41).
96
+ const { inbox, mentions } = require(`${__hooks}/lib/inbox.js`).counts(e.app, user);
97
+ return e.json(200, { at, rooms: out, ids, inbox, mentions });
96
98
  }
97
99
 
98
100
  /**
@@ -99,4 +99,4 @@ function assetLinks(e) {
99
99
  ]);
100
100
  }
101
101
 
102
- module.exports = { checkInvite, checkOAuth2Signup, manifest, assetLinks };
102
+ module.exports = { siteOf, checkInvite, checkOAuth2Signup, manifest, assetLinks };
@@ -0,0 +1,252 @@
1
+ /// <reference path="../../types/pocketbase.d.ts" />
2
+ // Usage statistics (DESIGN.md §40): GET /api/chat/stats, for moderators and superusers, and what feeds it. Counts only:
3
+ // no response names anyone, and the per-account rows (stats_activity) never leave the server.
4
+ //
5
+ // Online is who has a realtime connection now: every open web tab and the Android app while it is in front hold one,
6
+ // with at least one subscription. A connection's app (web or Android) is noted when it subscribes, from its
7
+ // User-Agent (the app's OkHttp sends "okhttp/…"). Not on connecting: a JS hook on GET /api/realtime would hold a JS
8
+ // runtime for as long as the connection is open (docs/PERF.md §6).
9
+ //
10
+ // Every 5 minutes `run` writes a sample of those counts and marks everyone online active today; a subscription marks
11
+ // its account too, at most once an hour (so a visit shorter than 5 minutes counts). `site.no_stats` stops both.
12
+
13
+ const KEY_APP = "chirkle_app";
14
+ const SAMPLE_MINUTES = 5;
15
+ const ACTIVITY_DAYS = 90;
16
+ const SAMPLE_DAYS = 365;
17
+ const DAY_MS = 86_400_000;
18
+
19
+ /** @param {Date} d @returns {string} as PocketBase stores dates */
20
+ const dbDate = (d) => d.toISOString().replace("T", " ");
21
+
22
+ /** @param {string} ua @returns {"web" | "android" | "other"} */
23
+ function appOf(ua) {
24
+ if (/^okhttp\//i.test(ua)) return "android";
25
+ if (/^Mozilla\//.test(ua)) return "web";
26
+ return "other";
27
+ }
28
+
29
+ /** @param {core.App} app */
30
+ function off(app) {
31
+ return !!require(`${__hooks}/lib/site.js`).siteOf(app)?.getBool("no_stats");
32
+ }
33
+
34
+ /**
35
+ * `user` was online at `at`: its row for that (UTC) day says so.
36
+ * @param {core.App} app
37
+ * @param {string[]} users
38
+ * @param {Date} at
39
+ */
40
+ function touch(app, users, at) {
41
+ const day = at.toISOString().slice(0, 10);
42
+ const when = dbDate(at);
43
+ for (const user of users) {
44
+ app
45
+ .db()
46
+ .newQuery(
47
+ "INSERT INTO stats_activity (id, user, day, last_at) VALUES ({:id}, {:user}, {:day}, {:at}) ON CONFLICT (user, day) DO UPDATE SET last_at = excluded.last_at",
48
+ )
49
+ .bind({ id: $security.randomStringWithAlphabet(15, "abcdefghijklmnopqrstuvwxyz0123456789"), user, day, at: when })
50
+ .execute();
51
+ }
52
+ }
53
+
54
+ /**
55
+ * realtime subscribe request: note the connection's app, and mark its account active (once an hour). Never fails the
56
+ * subscription.
57
+ * @param {core.RealtimeSubscribeRequestEvent} e
58
+ */
59
+ function subscribed(e) {
60
+ try {
61
+ // (This event's e.request is undefined in the JS runtime; requestInfo has the headers, lowercased.)
62
+ e.client.set(KEY_APP, appOf(String(e.requestInfo().headers.user_agent ?? "")));
63
+ const user = e.auth && !e.auth.isSuperuser() && e.auth.collection().name === "users" ? e.auth.id : "";
64
+ if (!user) return;
65
+ const now = new Date();
66
+ const hour = now.toISOString().slice(0, 13);
67
+ const key = `stats.touched.${user}`;
68
+ if (e.app.store().get(key) === hour) return;
69
+ e.app.store().set(key, hour);
70
+ if (!off(e.app)) touch(e.app, [user], now);
71
+ } catch (err) {
72
+ e.app.logger().warn("stats: subscribe", "error", String(err));
73
+ }
74
+ }
75
+
76
+ /**
77
+ * Who is online now: distinct accounts (also by app; someone on both counts in each) and guests' connections.
78
+ * Superusers (the admin UI) and connections that haven't subscribed to anything yet don't count.
79
+ * @param {core.App} app
80
+ */
81
+ function online(app) {
82
+ const people = new Set();
83
+ const web = new Set();
84
+ const android = new Set();
85
+ let guests = 0;
86
+ const clients = app.subscriptionsBroker().clients();
87
+ for (const id of Object.keys(clients)) {
88
+ const client = clients[id];
89
+ if (!client || client.isDiscarded() || !Object.keys(client.subscriptions()).length) continue;
90
+ /** @type {core.Record | null | undefined} */
91
+ const auth = client.get("auth");
92
+ if (auth?.isSuperuser()) continue;
93
+ if (!auth) {
94
+ guests++;
95
+ continue;
96
+ }
97
+ people.add(auth.id);
98
+ const kind = client.get(KEY_APP);
99
+ if (kind === "web") web.add(auth.id);
100
+ else if (kind === "android") android.add(auth.id);
101
+ }
102
+ return { ids: [...people], online: people.size, guests, web: web.size, android: android.size };
103
+ }
104
+
105
+ /**
106
+ * The 5-minute run: a sample, and everyone online marked active. Nothing while `site.no_stats` is ticked.
107
+ * @param {core.App} app
108
+ */
109
+ function run(app) {
110
+ if (off(app)) return;
111
+ const now = new Date();
112
+ const o = online(app);
113
+ app.runInTransaction((tx) => {
114
+ tx.db()
115
+ .newQuery(
116
+ "INSERT INTO stats_samples (id, at, online, guests, web, android) VALUES ({:id}, {:at}, {:online}, {:guests}, {:web}, {:android})",
117
+ )
118
+ .bind({
119
+ id: $security.randomStringWithAlphabet(15, "abcdefghijklmnopqrstuvwxyz0123456789"),
120
+ at: dbDate(now),
121
+ online: o.online,
122
+ guests: o.guests,
123
+ web: o.web,
124
+ android: o.android,
125
+ })
126
+ .execute();
127
+ touch(tx, o.ids, now);
128
+ });
129
+ }
130
+
131
+ /**
132
+ * Daily: activity rows after 90 days, samples after a year. Also while statistics are off, so what there is goes.
133
+ * @param {core.App} app
134
+ */
135
+ function prune(app) {
136
+ const now = Date.now();
137
+ app
138
+ .db()
139
+ .newQuery("DELETE FROM stats_activity WHERE day < {:day}")
140
+ .bind({ day: new Date(now - ACTIVITY_DAYS * DAY_MS).toISOString().slice(0, 10) })
141
+ .execute();
142
+ app
143
+ .db()
144
+ .newQuery("DELETE FROM stats_samples WHERE at < {:at}")
145
+ .bind({ at: dbDate(new Date(now - SAMPLE_DAYS * DAY_MS)) })
146
+ .execute();
147
+ }
148
+
149
+ /** POST /api/stats/tick (superusers, tests): a run now, and the prune with it. @param {core.RequestEvent} e */
150
+ function tick(e) {
151
+ run(e.app);
152
+ prune(e.app);
153
+ return e.noContent(204);
154
+ }
155
+
156
+ /** Accounts of this server's own: not a linked server's people (§33), nor the Telegram bridge's stand-ins (§26). */
157
+ const LOCAL_USER = "(u.peer = '' AND u.id NOT IN (SELECT user FROM tg_people))";
158
+
159
+ const DAYS_SQL = `
160
+ SELECT date(m.created, {:shift}) AS day, COUNT(*) AS messages, COUNT(DISTINCT m.author) AS people
161
+ FROM messages m JOIN users u ON u.id = m.author
162
+ WHERE m.created >= {:since} AND ${LOCAL_USER}
163
+ GROUP BY day ORDER BY day`;
164
+
165
+ const MESSAGES_SQL = `
166
+ SELECT
167
+ COUNT(DISTINCT CASE WHEN m.created >= {:week} THEN m.author END) AS people_week,
168
+ COUNT(DISTINCT m.author) AS people_month,
169
+ COALESCE(SUM(r.kind = 'dm'), 0) AS dms,
170
+ COALESCE(SUM(CASE WHEN json_valid(m.files) THEN json_array_length(m.files) ELSE 0 END), 0) AS files,
171
+ COALESCE(SUM((SELECT SUM(json_array_length(x.value, '$.users')) FROM json_each(CASE WHEN json_valid(m.reactions) THEN m.reactions ELSE '[]' END) x)), 0) AS reactions
172
+ FROM messages m JOIN users u ON u.id = m.author JOIN rooms r ON r.id = m.room
173
+ WHERE m.created >= {:month} AND ${LOCAL_USER}`;
174
+
175
+ const ACCOUNTS_SQL = `
176
+ SELECT COUNT(*) AS total, COALESCE(SUM(u.created >= {:week}), 0) AS new_week,
177
+ COALESCE(SUM(u.moderator), 0) AS moderators, COALESCE(SUM(u.banned), 0) AS banned
178
+ FROM users u WHERE ${LOCAL_USER}`;
179
+
180
+ const ACTIVE_SQL = `
181
+ SELECT COUNT(DISTINCT CASE WHEN last_at >= {:day} THEN user END) AS day,
182
+ COUNT(DISTINCT CASE WHEN last_at >= {:week} THEN user END) AS week,
183
+ COUNT(DISTINCT user) AS month
184
+ FROM stats_activity WHERE last_at >= {:month}`;
185
+
186
+ /**
187
+ * GET /api/chat/stats?tz=<minutes east of UTC>: for moderators and superusers. Days (the messages per day) are the
188
+ * viewer's, from `tz`; "today" on the page is theirs too.
189
+ * @param {core.RequestEvent} e
190
+ */
191
+ function get(e) {
192
+ const auth = e.auth;
193
+ if (!auth || !(auth.isSuperuser() || require(`${__hooks}/lib/moderation.js`).isModerator(auth))) {
194
+ throw new ForbiddenError("Only moderators can see the statistics.");
195
+ }
196
+ const tzRaw = Math.round(Number(e.request?.url?.query().get("tz") || 0));
197
+ const tz = Number.isFinite(tzRaw) ? Math.max(-840, Math.min(840, tzRaw)) : 0;
198
+ const now = Date.now();
199
+ // The viewer's midnight today, as a UTC instant, and the 30 days' first.
200
+ const midnight = Math.floor((now + tz * 60_000) / DAY_MS) * DAY_MS - tz * 60_000;
201
+ const month = dbDate(new Date(midnight - 29 * DAY_MS));
202
+ const week = dbDate(new Date(midnight - 6 * DAY_MS));
203
+ const db = e.app.db();
204
+
205
+ const days = arrayOf(new DynamicModel({ day: "", messages: 0, people: 0 }));
206
+ db.newQuery(DAYS_SQL)
207
+ .bind({ shift: `${tz >= 0 ? "+" : ""}${tz} minutes`, since: month })
208
+ .all(days);
209
+
210
+ const msgs = new DynamicModel({ people_week: 0, people_month: 0, dms: 0, files: 0, reactions: 0 });
211
+ db.newQuery(MESSAGES_SQL).bind({ week, month }).one(msgs);
212
+
213
+ const accounts = new DynamicModel({ total: 0, new_week: 0, moderators: 0, banned: 0 });
214
+ db.newQuery(ACCOUNTS_SQL)
215
+ .bind({ week: dbDate(new Date(now - 7 * DAY_MS)) })
216
+ .one(accounts);
217
+
218
+ const active = new DynamicModel({ day: 0, week: 0, month: 0 });
219
+ db.newQuery(ACTIVE_SQL)
220
+ .bind({
221
+ day: dbDate(new Date(now - DAY_MS)),
222
+ week: dbDate(new Date(now - 7 * DAY_MS)),
223
+ month: dbDate(new Date(now - 30 * DAY_MS)),
224
+ })
225
+ .one(active);
226
+
227
+ const rows = arrayOf(new DynamicModel({ at: "", online: 0, guests: 0, web: 0, android: 0 }));
228
+ db.newQuery("SELECT at, online, guests, web, android FROM stats_samples WHERE at >= {:since} ORDER BY at")
229
+ .bind({ since: dbDate(new Date(now - 7 * DAY_MS)) })
230
+ .all(rows);
231
+
232
+ const o = online(e.app);
233
+ return e.json(200, {
234
+ at: now,
235
+ history: !off(e.app),
236
+ sample_minutes: SAMPLE_MINUTES,
237
+ now: { online: o.online, guests: o.guests, web: o.web, android: o.android },
238
+ active: { day: active.day, week: active.week, month: active.month },
239
+ accounts: { total: accounts.total, new_week: accounts.new_week, moderators: accounts.moderators, banned: accounts.banned },
240
+ messages: {
241
+ days: days.map((d) => ({ day: d.day, messages: d.messages, people: d.people })),
242
+ people_week: msgs.people_week,
243
+ people_month: msgs.people_month,
244
+ dms_month: msgs.dms,
245
+ files_month: msgs.files,
246
+ reactions_month: msgs.reactions,
247
+ },
248
+ samples: rows.map((r) => [Date.parse(String(r.at).replace(" ", "T")), r.online, r.guests, r.web, r.android]),
249
+ });
250
+ }
251
+
252
+ module.exports = { appOf, subscribed, online, run, prune, tick, get };
@@ -19,8 +19,11 @@ function searchUsers(e) {
19
19
  const key = nameKey(typeof raw === "string" ? raw.trim() : "");
20
20
  if (!key) return e.json(200, []);
21
21
  // `~` treats a % in the value as a wildcard (and then stops adding its own): escape it (QA BUG-34). `_` is escaped.
22
- const found = e.app.findRecordsByFilter("users", "name_key ~ {:q} && id != {:me}", "name", LIMIT, 0, {
22
+ // "@ann" finds Ann by her handle (§41) as well as by name.
23
+ const handle = key.replace(/^@/, "");
24
+ const found = e.app.findRecordsByFilter("users", "(name_key ~ {:q} || handle ~ {:h}) && id != {:me}", "name", LIMIT, 0, {
23
25
  q: key.replace(/%/g, "\\%"),
26
+ h: handle.replace(/%/g, "\\%"),
24
27
  me: me.id,
25
28
  });
26
29
  // Only the public profile, never the email (§6).
@@ -32,6 +35,7 @@ function searchUsers(e) {
32
35
  {
33
36
  id: u.id,
34
37
  name: u.getString("name"),
38
+ handle: u.getString("handle"),
35
39
  avatar: u.getString("avatar"),
36
40
  no_dms: u.getBool("no_dms"),
37
41
  instance: u.getString("instance"),
@@ -60,6 +64,7 @@ function beforeUserSave(e) {
60
64
  } else {
61
65
  setNameKey(e.app, "users", rec, "This display name is taken. Choose another one.");
62
66
  }
67
+ require(`${__hooks}/lib/handles.js`).setHandle(e.app, rec);
63
68
  assertImagesFit(rec, "avatar");
64
69
  originalNames(rec, "avatar"); // only for the upload's own name (QA BUG-35)
65
70
  }
@@ -1,5 +1,5 @@
1
1
  /// <reference path="../types/pocketbase.d.ts" />
2
- // Server-side hooks (DESIGN.md §5.6, §16, §18, §20, §21, §22, §23, §24, §28, §30, §31, §36, §37; docs/ANDROID.md §9.4). Logic lives in lib/, one module per collection
2
+ // Server-side hooks (DESIGN.md §5.6, §16, §18, §20, §21, §22, §23, §24, §28, §30, §31, §36, §37, §40; docs/ANDROID.md §9.4). Logic lives in lib/, one module per collection
3
3
  // or route: PocketBase hook handlers can't see top-level variables, so each handler require()s its module.
4
4
 
5
5
  onBootstrap((e) => {
@@ -7,37 +7,65 @@ onBootstrap((e) => {
7
7
  require(`${__hooks}/lib/http.js`).trustProxy(e.app);
8
8
  });
9
9
 
10
- routerUse((e) => {
11
- require(`${__hooks}/lib/http.js`).headers(e);
12
- return e.next();
13
- });
14
-
15
- // Bodies up to 10 attachments of 20 MB (§17.1): replaces PocketBase's default limit (same middleware id); lib/http.js
16
- // keeps the default for everything but a message create.
17
- routerUse($apis.bodyLimit(require(`${__hooks}/lib/http.js`).MESSAGE_BODY_LIMIT));
18
- routerUse((e) => require(`${__hooks}/lib/http.js`).bodyLimit(e));
10
+ // No routerUse with a JS handler here: it holds a JS runtime of the pool (--hooksPool) for the whole request, so every
11
+ // open realtime connection and every file on its way from S3 would keep some, and room pages, whose enrich hooks need
12
+ // one each, would make new ones (docs/PERF.md §6). What one would do for every request is done by the routes and hooks
13
+ // it concerns: the headers by the routes that serve pages (lib/http.js), the body limit by PocketBase (it sizes each
14
+ // collection's create and update by its fields, DESIGN.md §17.1), the files and the anonymous rooms' checks below.
19
15
 
20
- // Nobody but superusers finds out who wrote a message in an anonymous room by filtering, sorting or expanding (§35).
21
- routerUse((e) => {
22
- // Re-encoded: letters never are (%61uthor would pass a look at the raw query).
23
- if (/author|forwarded_from/i.test(e.request?.url?.query().encode() ?? "")) require(`${__hooks}/lib/anonymous.js`).refuseProbes(e);
24
- return e.next();
16
+ // Nobody but superusers finds out who wrote a message in an anonymous room by filtering, sorting or expanding (§35):
17
+ // checked by everything that takes a filter, sort or expand (the routes here that enrich records do too).
18
+ onRecordsListRequest((e) => {
19
+ require(`${__hooks}/lib/anonymous.js`).refuseProbes(e);
20
+ e.next();
25
21
  });
26
- // A message's or collection item's file is its shared `files` row's (§37): served without a file token.
27
- routerUse((e) => {
28
- if (e.request?.url?.path.startsWith("/api/files/") && require(`${__hooks}/lib/files.js`).serve(e)) return;
29
- return e.next();
22
+ onRecordViewRequest((e) => {
23
+ require(`${__hooks}/lib/anonymous.js`).refuseProbes(e);
24
+ e.next();
25
+ });
26
+ onRecordCreateRequest((e) => {
27
+ require(`${__hooks}/lib/anonymous.js`).refuseProbes(e);
28
+ e.next();
29
+ });
30
+ onRecordUpdateRequest((e) => {
31
+ require(`${__hooks}/lib/anonymous.js`).refuseProbes(e);
32
+ e.next();
33
+ });
34
+ // Every auth answer (password, OAuth2, OTP, refresh, impersonation) has the record, expanded as asked.
35
+ onRecordAuthRequest((e) => {
36
+ require(`${__hooks}/lib/anonymous.js`).refuseProbes(e);
37
+ e.next();
30
38
  });
31
-
32
39
  onRealtimeSubscribeRequest((e) => {
33
40
  require(`${__hooks}/lib/anonymous.js`).refuseSubscriptionProbes(e);
41
+ // Which app the connection is, and its account active today, for the statistics (§40).
42
+ require(`${__hooks}/lib/stats.js`).subscribed(e);
34
43
  e.next();
35
44
  });
36
45
 
37
- // Not the app's index.html (PocketBase's fallback for any other path, §7.1) for a missing asset or API.
46
+ // A message's or collection item's file is its shared `files` row's (§37): served without a file token, by routes more
47
+ // specific than PocketBase's /api/files/{collection}/… (lib/files.js serve). The rows themselves never directly.
48
+ routerAdd("GET", "/api/files/messages/{recordId}/{filename}", (e) => require(`${__hooks}/lib/files.js`).serve(e, "messages"));
49
+ routerAdd("GET", "/api/files/collection_items/{recordId}/{filename}", (e) =>
50
+ require(`${__hooks}/lib/files.js`).serve(e, "collection_items"),
51
+ );
52
+ onFileDownloadRequest(() => {
53
+ throw new NotFoundError();
54
+ }, "files");
55
+
56
+ // The app's pages (index.html at any path that isn't a file, §7.1) and its files, with their headers (§5.6).
57
+ routerAdd("GET", "/{path...}", (e) => require(`${__hooks}/lib/http.js`).page(e));
58
+ // Not the app's index.html for a missing asset or API.
59
+ routerAdd("GET", "/stats", (e) => require(`${__hooks}/lib/http.js`).statsPage(e));
38
60
  routerAdd("GET", "/assets/{path...}", (e) => require(`${__hooks}/lib/http.js`).asset(e));
39
- routerAdd("GET", "/manifest.webmanifest", (e) => require(`${__hooks}/lib/site.js`).manifest(e));
40
- routerAdd("GET", "/.well-known/assetlinks.json", (e) => require(`${__hooks}/lib/site.js`).assetLinks(e));
61
+ routerAdd("GET", "/manifest.webmanifest", (e) => {
62
+ require(`${__hooks}/lib/http.js`).headers(e);
63
+ return require(`${__hooks}/lib/site.js`).manifest(e);
64
+ });
65
+ routerAdd("GET", "/.well-known/assetlinks.json", (e) => {
66
+ require(`${__hooks}/lib/http.js`).headers(e);
67
+ return require(`${__hooks}/lib/site.js`).assetLinks(e);
68
+ });
41
69
  routerAdd("GET", "/api/{path...}", () => {
42
70
  throw new NotFoundError();
43
71
  });
@@ -46,6 +74,7 @@ routerAdd("GET", "/api/chat/rooms", (e) => require(`${__hooks}/lib/lists.js`).ro
46
74
  routerAdd("GET", "/api/chat/rooms/{room}/messages", (e) => require(`${__hooks}/lib/lists.js`).messages(e));
47
75
  routerAdd("GET", "/api/chat/notifiable", (e) => require(`${__hooks}/lib/lists.js`).notifiable(e), $apis.requireAuth("users"));
48
76
  routerAdd("POST", "/api/chat/dms", (e) => require(`${__hooks}/lib/dms.js`).openDm(e), $apis.requireAuth("users"));
77
+ routerAdd("GET", "/api/chat/live", (e) => require(`${__hooks}/lib/live.js`).info(e));
49
78
  routerAdd("GET", "/api/chat/unread", (e) => require(`${__hooks}/lib/reads.js`).unread(e), $apis.requireAuth("users"));
50
79
  routerAdd("GET", "/api/chat/unread/{room}", (e) => require(`${__hooks}/lib/reads.js`).firstUnread(e), $apis.requireAuth("users"));
51
80
  routerAdd("POST", "/api/chat/reads", (e) => require(`${__hooks}/lib/reads.js`).markRead(e), $apis.requireAuth("users"));
@@ -64,8 +93,13 @@ routerAdd("DELETE", "/api/chat/items/{id}", (e) => require(`${__hooks}/lib/colle
64
93
  routerAdd("POST", "/api/chat/subs", (e) => require(`${__hooks}/lib/collections.js`).subscribe(e), $apis.requireAuth("users"));
65
94
  routerAdd("POST", "/api/chat/subs/seen", (e) => require(`${__hooks}/lib/collections.js`).markSeen(e), $apis.requireAuth("users"));
66
95
  routerAdd("POST", "/api/keepalive/tick", (e) => require(`${__hooks}/lib/keepalive.js`).tick(e), $apis.requireSuperuserAuth());
96
+ routerAdd("GET", "/api/chat/stats", (e) => require(`${__hooks}/lib/stats.js`).get(e));
97
+ routerAdd("POST", "/api/stats/tick", (e) => require(`${__hooks}/lib/stats.js`).tick(e), $apis.requireSuperuserAuth());
67
98
  routerAdd("POST", "/api/media/tick", (e) => require(`${__hooks}/lib/media.js`).tick(e), $apis.requireSuperuserAuth());
68
99
  routerAdd("GET", "/api/chat/users", (e) => require(`${__hooks}/lib/users.js`).searchUsers(e), $apis.requireAuth("users"));
100
+ routerAdd("GET", "/api/chat/mentionable", (e) => require(`${__hooks}/lib/handles.js`).mentionable(e), $apis.requireAuth("users"));
101
+ routerAdd("GET", "/api/chat/inbox", (e) => require(`${__hooks}/lib/inbox.js`).list(e), $apis.requireAuth("users"));
102
+ routerAdd("POST", "/api/chat/inbox/seen", (e) => require(`${__hooks}/lib/inbox.js`).markSeen(e), $apis.requireAuth("users"));
69
103
  routerAdd("POST", "/api/chat/password", (e) => require(`${__hooks}/lib/account.js`).changePassword(e), $apis.requireAuth("users"));
70
104
 
71
105
  // The core collections' hooks (messages, rooms, users) are all here, with the optional features' parts (lib/features.js)
@@ -227,12 +261,18 @@ onRecordDelete((e) => {
227
261
  onRecordCreate((e) => {
228
262
  const messages = require(`${__hooks}/lib/messages.js`);
229
263
  messages.beforeMessageCreate(e);
230
- if (e.record) messages.setTextKey(e.record);
264
+ const features = require(`${__hooks}/lib/features.js`);
265
+ if (e.record) {
266
+ messages.setTextKey(e.record);
267
+ // Who it mentions (§41): from its text, or as the linked instance it comes from says.
268
+ const fed = features.federation(e.app);
269
+ require(`${__hooks}/lib/handles.js`).setMentions(e.app, e.record, !!fed && fed.messages.isFromPeer(e.app, e.record));
270
+ }
231
271
  e.next();
232
272
  const rec = e.record;
233
273
  if (!rec) return;
234
- // Saved: what each feature does with a new message is queued, in the save's transaction.
235
- const features = require(`${__hooks}/lib/features.js`);
274
+ // Saved: whom it tells (§41), and what each feature does with a new message is queued, in the save's transaction.
275
+ require(`${__hooks}/lib/inbox.js`).messageCreated(e.app, rec);
236
276
  features.telegram()?.outbound.queueCreate(e.app, rec);
237
277
  require(`${__hooks}/lib/previews.js`).queue(e.app, rec);
238
278
  require(`${__hooks}/lib/media.js`).add(e.app, rec);
@@ -244,6 +284,31 @@ onRecordAfterCreateSuccess((e) => {
244
284
  e.next();
245
285
  }, "messages");
246
286
 
287
+ // Live (lib/live.js): each message once to everyone listening who can see its room, once committed. A failure to send
288
+ // is logged, never the save's: the apps load what they missed when they reconnect.
289
+ onRecordAfterCreateSuccess((e) => {
290
+ e.next();
291
+ require(`${__hooks}/lib/live.js`).sendSafely(e.app, e.record, "create");
292
+ }, "messages");
293
+ onRecordAfterUpdateSuccess((e) => {
294
+ e.next();
295
+ require(`${__hooks}/lib/live.js`).sendSafely(e.app, e.record, "update");
296
+ }, "messages");
297
+ onRecordAfterDeleteSuccess((e) => {
298
+ e.next();
299
+ require(`${__hooks}/lib/live.js`).sendSafely(e.app, e.record, "delete");
300
+ }, "messages");
301
+
302
+ // The inbox (§41): each row added or removed, once committed, to its person's apps.
303
+ onRecordAfterCreateSuccess((e) => {
304
+ e.next();
305
+ require(`${__hooks}/lib/inbox.js`).tell(e.app, e.record, "create");
306
+ }, "inbox");
307
+ onRecordAfterDeleteSuccess((e) => {
308
+ e.next();
309
+ require(`${__hooks}/lib/inbox.js`).tell(e.app, e.record, "delete");
310
+ }, "inbox");
311
+
247
312
  // Committed (with the message that queued it): the workers look at it now, not on their next look round.
248
313
  onRecordAfterCreateSuccess((e) => {
249
314
  e.next();
@@ -266,8 +331,11 @@ onRecordUpdate((e) => {
266
331
  const was = fed ? fed.messages.before(rec) : null;
267
332
  if (fed) fed.messages.checkMirrorChange(e.app, rec);
268
333
  const messages = require(`${__hooks}/lib/messages.js`);
334
+ const inbox = require(`${__hooks}/lib/inbox.js`);
335
+ const told = inbox.before(rec);
269
336
  messages.beforeMessageUpdate(e);
270
337
  messages.setTextKey(rec);
338
+ require(`${__hooks}/lib/handles.js`).setMentions(e.app, rec, !!fed && fed.messages.isFromPeer(e.app, rec));
271
339
  const touch = messages.changesForwards(rec);
272
340
  const edited = rec.getString("text") !== rec.original().getString("text");
273
341
  const deleted = rec.getBool("deleted") && !rec.original().getBool("deleted");
@@ -276,6 +344,8 @@ onRecordUpdate((e) => {
276
344
  const tg = features.telegram();
277
345
  const change = tg ? tg.outbound.changeOf(e.app, rec) : "";
278
346
  e.next();
347
+ // Saved: mentions, replies and reactions told or taken back (§41).
348
+ inbox.messageChanged(e.app, rec, told);
279
349
  if (tg) tg.outbound.queueUpdate(e.app, rec, change);
280
350
  // Saved: a deleted message's media leave the grid, its forwards' too (§30.1), and its files are named once less (§37).
281
351
  if (deleted) require(`${__hooks}/lib/media.js`).drop(e.app, rec.id);
@@ -317,6 +387,13 @@ if (require(`${__hooks}/lib/previews.js`).enabled()) {
317
387
  // (lib/keepalive.js).
318
388
  cronAdd("keepalive", "*/3 * * * *", () => require(`${__hooks}/lib/keepalive.js`).run($app));
319
389
 
390
+ // Usage statistics (§40): a sample of who is online every 5 minutes (unless site.no_stats), old rows dropped daily.
391
+ // STATS_CRON=off leaves them to POST /api/stats/tick (tests).
392
+ if ($os.getenv("STATS_CRON").trim().toLowerCase() !== "off") {
393
+ cronAdd("stats", "*/5 * * * *", () => require(`${__hooks}/lib/stats.js`).run($app));
394
+ cronAdd("stats-prune", "23 3 * * *", () => require(`${__hooks}/lib/stats.js`).prune($app));
395
+ }
396
+
320
397
  // The media grid's thumbnails and video posters (§30.1): made by a worker, a minute's run at a time. MEDIA_CRON=off
321
398
  // leaves them to POST /api/media/tick (tests).
322
399
  if ($os.getenv("MEDIA_CRON").trim().toLowerCase() !== "off") {
@@ -93,6 +93,10 @@ function personOf(app, msg) {
93
93
  user.set("email", `tg${s.id.replace(/\D/g, "")}.${$security.randomStringWithAlphabet(6, "abcdefghijklmnopqrstuvwxyz")}@telegram.invalid`);
94
94
  user.setPassword($security.randomString(40));
95
95
  user.set("no_dms", true);
96
+ // Their Telegram username as their handle when it is one and free (§41), so "@username" means them on both sides.
97
+ const { HANDLE, freeHandle, normalHandle } = require(`${__hooks}/lib/handles.js`);
98
+ const wanted = normalHandle(s.username);
99
+ if (HANDLE.test(wanted)) user.set("handle", freeHandle(app, wanted, user.id));
96
100
  saveWithName(app, user, s.name);
97
101
  row = new Record(app.findCollectionByNameOrId("tg_people"));
98
102
  row.set("tg_user_id", s.id);
@@ -1,8 +1,9 @@
1
1
  /// <reference path="../../types/pocketbase.d.ts" />
2
2
  // Reactions across the bridge (DESIGN.md §26.9). Telegram tells a bot about reactions only where it is an admin
3
- // (`message_reaction`): each person's change comes over as their stand-in's reaction on the message. The other way, a
4
- // bot may set one reaction of its own on a message: it shows the one most of the room's own people (not Telegram's
5
- // stand-ins, whose reactions are in the group already) reacted with, among those Telegram offers.
3
+ // (`message_reaction`): each person's change comes over as their stand-in's reaction on the message, as the nearest
4
+ // emoji the picker has. The other way, a bot may set one reaction of its own on a message: it shows the one most of
5
+ // the room's own people (not Telegram's stand-ins, whose reactions are in the group already) reacted with, among those
6
+ // Telegram offers.
6
7
 
7
8
  const { call } = require(`${__hooks}/telegram/api.js`);
8
9
  const { isReactionEmoji } = require(`${__hooks}/lib/emoji.js`);
@@ -18,15 +19,68 @@ const TELEGRAM = new Set(
18
19
  ).split(" "),
19
20
  );
20
21
 
22
+ /** Telegram's reaction emoji the picker hasn't got (bare, as in TELEGRAM), and the picker's nearest to each. */
23
+ const SIMILAR = new Map([
24
+ ["🕊", "🐦"],
25
+ ["❤‍🔥", "❤️"],
26
+ ["💋", "😘"],
27
+ ["🖕", "👎"],
28
+ ["👨‍💻", "💻"],
29
+ ["🫡", "🙇"],
30
+ ["🎅", "🎄"],
31
+ ["🗿", "😐"],
32
+ ["👾", "👽"],
33
+ ]);
34
+
35
+ /** What a reaction is when nothing nearer is found: Telegram's own default (a double tap). */
36
+ const FALLBACK = "❤️";
37
+
38
+ /**
39
+ * The picker's emoji for `emoji`, or "" when neither it nor a near one is there.
40
+ * @param {string} emoji
41
+ * @returns {string}
42
+ */
43
+ function pickerEmoji(emoji) {
44
+ const bare = emoji.replace(/\uFE0F/g, "").replace(/\u200D[♂♀]$/, "");
45
+ const found = [emoji, bare, `${bare}${VS16}`].find((e) => isReactionEmoji(e)) || SIMILAR.get(bare) || "";
46
+ if (found) return found;
47
+ // Skin tones aside; a sequence (👩‍🚀) as the first of its parts the picker has.
48
+ const plain = bare.replace(/[\u{1F3FB}-\u{1F3FF}]/gu, "");
49
+ if (plain !== bare) return pickerEmoji(plain);
50
+ const parts = plain.split("\u200D");
51
+ return parts.length > 1 ? parts.map(pickerEmoji).find(Boolean) || "" : "";
52
+ }
53
+
21
54
  /**
22
- * The picker's emoji (§20.1) for a Telegram reaction, or "" when it has none: "❤" is "❤️", a shrug of either gender is
23
- * "🤷". Custom and paid reactions have no emoji.
55
+ * The picker's emoji (§20.1) for a Telegram reaction, never none: "❤" is "❤️", a shrug of either gender is "🤷",
56
+ * one the picker hasn't got is the nearest it has ("🕊" is "🐦"), a custom emoji is the emoji it stands for (from
57
+ * `customs`), a paid reaction is "⭐", and anything else is "❤️".
24
58
  * @param {any} r ReactionType
59
+ * @param {Map<string, string>} [customs] custom emoji ids to the emoji they stand for
25
60
  */
26
- function fromTelegram(r) {
27
- if (r?.type !== "emoji" || typeof r.emoji !== "string") return "";
28
- const bare = r.emoji.replace(/\uFE0F/g, "").replace(/\u200D[♂♀]$/, "");
29
- return [r.emoji, bare, `${bare}${VS16}`].find((e) => isReactionEmoji(e)) || "";
61
+ function fromTelegram(r, customs) {
62
+ const emoji =
63
+ r?.type === "emoji" ? r.emoji : r?.type === "custom_emoji" ? customs?.get(String(r.custom_emoji_id)) : r?.type === "paid" ? "⭐" : "";
64
+ return (typeof emoji === "string" && emoji && pickerEmoji(emoji)) || FALLBACK;
65
+ }
66
+
67
+ /**
68
+ * The emoji custom emoji stand for (getCustomEmojiStickers), by id; those Telegram doesn't say are left out.
69
+ * @param {any[]} reactions ReactionType
70
+ */
71
+ function customEmoji(reactions) {
72
+ /** @type {Map<string, string>} */
73
+ const out = new Map();
74
+ const ids = [...new Set(reactions.filter((r) => r?.type === "custom_emoji" && r.custom_emoji_id).map((r) => String(r.custom_emoji_id)))];
75
+ if (!ids.length) return out;
76
+ try {
77
+ for (const s of call("getCustomEmojiStickers", { custom_emoji_ids: ids.slice(0, 200) }) || []) {
78
+ if (s?.custom_emoji_id && typeof s.emoji === "string") out.set(String(s.custom_emoji_id), s.emoji);
79
+ }
80
+ } catch (err) {
81
+ $app.logger().warn("telegram: custom emoji", "error", String(err));
82
+ }
83
+ return out;
30
84
  }
31
85
 
32
86
  /**
@@ -66,7 +120,7 @@ function botReaction(app, rec) {
66
120
 
67
121
  /**
68
122
  * A `message_reaction` update: someone's reactions on a message changed. Their stand-in's reactions on the chat message
69
- * change the same way (those the picker has; the rest are left out).
123
+ * change the same way, each as the picker's emoji or the nearest it has (none is left out).
70
124
  * @param {core.App} app
71
125
  * @param {any} update MessageReactionUpdated
72
126
  */
@@ -80,7 +134,9 @@ function reactionOver(app, update) {
80
134
  if (!room) return;
81
135
  const found = mapped(app, chatId, update.message_id);
82
136
  if (!found || found.getString("room") !== room.id || !found.getString("author")) return;
83
- const emojiOf = (/** @type {any} */ list) => new Set((Array.isArray(list) ? list : []).map(fromTelegram).filter(Boolean));
137
+ const listOf = (/** @type {any} */ list) => (Array.isArray(list) ? list : []);
138
+ const customs = customEmoji([...listOf(update.old_reaction), ...listOf(update.new_reaction)]);
139
+ const emojiOf = (/** @type {any} */ list) => new Set(listOf(list).map((r) => fromTelegram(r, customs)));
84
140
  const was = emojiOf(update.old_reaction);
85
141
  const now = emojiOf(update.new_reaction);
86
142
  const changes = [