chirkle 0.1.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.
- package/README.md +23 -4
- package/package.json +2 -1
- package/pb_hooks/federation/messages.js +48 -2
- package/pb_hooks/lib/anonymous.js +10 -6
- package/pb_hooks/lib/bulk.js +2 -0
- package/pb_hooks/lib/files.js +39 -47
- package/pb_hooks/lib/handles.js +337 -0
- package/pb_hooks/lib/http.js +35 -23
- package/pb_hooks/lib/inbox.js +383 -0
- package/pb_hooks/lib/lists.js +8 -2
- package/pb_hooks/lib/live.js +137 -0
- package/pb_hooks/lib/messages.js +4 -0
- package/pb_hooks/lib/reactions.js +2 -0
- package/pb_hooks/lib/reads.js +3 -1
- package/pb_hooks/lib/site.js +1 -1
- package/pb_hooks/lib/stats.js +252 -0
- package/pb_hooks/lib/users.js +6 -1
- package/pb_hooks/main.pb.js +104 -27
- package/pb_hooks/telegram/api.js +3 -2
- package/pb_hooks/telegram/inbound.js +6 -1
- package/pb_hooks/telegram/outbound.js +35 -6
- package/pb_hooks/telegram/people.js +4 -0
- package/pb_hooks/telegram/reactions.js +193 -0
- package/pb_hooks/telegram/worker.js +1 -0
- package/pb_migrations/1760000043_telegram_reactions.js +21 -0
- package/pb_migrations/1760000044_stats.js +70 -0
- package/pb_migrations/1760000045_mentions.js +187 -0
- package/pb_migrations/1760000046_reserved_handles.js +29 -0
- package/pb_public/assets/access-GUDTDXIP.js +2 -0
- package/pb_public/assets/access-GUDTDXIP.js.map +7 -0
- package/pb_public/assets/app-3WX5JYL2.js +3 -0
- package/pb_public/assets/app-3WX5JYL2.js.map +7 -0
- package/pb_public/assets/app-WAFKVN2H.css +2 -0
- package/pb_public/assets/app-WAFKVN2H.css.map +7 -0
- package/pb_public/assets/collections-DHJEOLHW.css +2 -0
- package/pb_public/assets/collections-DHJEOLHW.css.map +7 -0
- package/pb_public/assets/{emoji-WSTVXAW5.css → emoji-VA2WCEAC.css} +2 -2
- package/pb_public/assets/{emoji-WSTVXAW5.css.map → emoji-VA2WCEAC.css.map} +2 -2
- package/pb_public/assets/{emoji-picker-QYRX6NYL.js → emoji-picker-65VVVGYW.js} +2 -2
- package/pb_public/assets/forward-66PELNWT.js +2 -0
- package/pb_public/assets/forward-66PELNWT.js.map +7 -0
- package/pb_public/assets/inbox-3FSOPY2T.css +2 -0
- package/pb_public/assets/inbox-3FSOPY2T.css.map +7 -0
- package/pb_public/assets/inbox-TZJWPRTG.js +2 -0
- package/pb_public/assets/inbox-TZJWPRTG.js.map +7 -0
- package/pb_public/assets/{lazy-SCCVSUZO.js → lazy-4CXRBHHM.js} +2 -2
- package/pb_public/assets/lazy-4CXRBHHM.js.map +7 -0
- package/pb_public/assets/login-G7Y44CJ7.js +2 -0
- package/pb_public/assets/login-G7Y44CJ7.js.map +7 -0
- package/pb_public/assets/{media-L3EYTHKT.css → media-7TCBG7WM.css} +2 -2
- package/pb_public/assets/{media-L3EYTHKT.css.map → media-7TCBG7WM.css.map} +2 -2
- package/pb_public/assets/media-FPRU2QH5.js +2 -0
- package/pb_public/assets/media-FPRU2QH5.js.map +7 -0
- package/pb_public/assets/mention-suggest-R7MXUH6R.js +2 -0
- package/pb_public/assets/mention-suggest-R7MXUH6R.js.map +7 -0
- package/pb_public/assets/notify-RQ6ZLR46.js +2 -0
- package/pb_public/assets/notify-RQ6ZLR46.js.map +7 -0
- package/pb_public/assets/profile-2CNVT2KX.js +2 -0
- package/pb_public/assets/profile-2CNVT2KX.js.map +7 -0
- package/pb_public/assets/stats-A2TBRUI6.css +2 -0
- package/pb_public/assets/stats-A2TBRUI6.css.map +7 -0
- package/pb_public/assets/stats-JX52AQCO.js +2 -0
- package/pb_public/assets/stats-JX52AQCO.js.map +7 -0
- package/pb_public/assets/user-search-7GNEIXMN.js +2 -0
- package/pb_public/assets/user-search-7GNEIXMN.js.map +7 -0
- package/pb_public/index.html +3 -3
- package/pb_public/stats.html +25 -0
- package/pb_public/sw.js +1 -1
- package/pb_public/assets/access-ALBW2MT2.js +0 -2
- package/pb_public/assets/access-ALBW2MT2.js.map +0 -7
- package/pb_public/assets/app-ECR34OBK.css +0 -2
- package/pb_public/assets/app-ECR34OBK.css.map +0 -7
- package/pb_public/assets/app-SILEBEXB.js +0 -3
- package/pb_public/assets/app-SILEBEXB.js.map +0 -7
- package/pb_public/assets/collections-VEOIOCAW.css +0 -2
- package/pb_public/assets/collections-VEOIOCAW.css.map +0 -7
- package/pb_public/assets/lazy-SCCVSUZO.js.map +0 -7
- package/pb_public/assets/media-DH7ECZSF.js +0 -2
- package/pb_public/assets/media-DH7ECZSF.js.map +0 -7
- package/pb_public/assets/notify-L6GERFNO.js +0 -2
- package/pb_public/assets/notify-L6GERFNO.js.map +0 -7
- /package/pb_public/assets/{emoji-picker-QYRX6NYL.js.map → emoji-picker-65VVVGYW.js.map} +0 -0
|
@@ -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 };
|
package/pb_hooks/lib/users.js
CHANGED
|
@@ -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
|
-
|
|
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
|
}
|
package/pb_hooks/main.pb.js
CHANGED
|
@@ -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(
|
|
11
|
-
|
|
12
|
-
|
|
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
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
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
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
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
|
-
//
|
|
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) =>
|
|
40
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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,16 +331,21 @@ 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");
|
|
274
342
|
// As stored, not as loaded: another delete of it may have been committed since (QA BUG-223).
|
|
275
343
|
const files = deleted ? require(`${__hooks}/lib/files.js`).namedBy(e.app, "messages", rec.id) : [];
|
|
276
344
|
const tg = features.telegram();
|
|
277
|
-
const change = tg ? tg.outbound.changeOf(rec) : "";
|
|
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") {
|
package/pb_hooks/telegram/api.js
CHANGED
|
@@ -18,8 +18,9 @@ function config() {
|
|
|
18
18
|
};
|
|
19
19
|
}
|
|
20
20
|
|
|
21
|
-
/** The updates the bridge asks for: a channel's posts come as channel_post, not message.
|
|
22
|
-
|
|
21
|
+
/** The updates the bridge asks for: a channel's posts come as channel_post, not message. Telegram sends
|
|
22
|
+
* message_reaction only where the bot is an admin. */
|
|
23
|
+
const UPDATES = ["message", "edited_message", "channel_post", "edited_channel_post", "my_chat_member", "message_reaction"];
|
|
23
24
|
|
|
24
25
|
/** A refused or failed call. `retryAfter`: seconds Telegram asks to wait (429). `status` 0: no answer. */
|
|
25
26
|
class TelegramError extends Error {
|
|
@@ -473,6 +473,11 @@ function sayStatus(app, chatId) {
|
|
|
473
473
|
*/
|
|
474
474
|
function handleUpdate(app, update) {
|
|
475
475
|
if (update.my_chat_member) return memberChange(app, update.my_chat_member);
|
|
476
|
+
// Sent only where the bot is an admin (§26.9). What came before it must be there to react to.
|
|
477
|
+
if (update.message_reaction) {
|
|
478
|
+
if (update.message_reaction.chat) flushAlbums(app, String(update.message_reaction.chat.id));
|
|
479
|
+
return require(`${__hooks}/telegram/reactions.js`).reactionOver(app, update.message_reaction);
|
|
480
|
+
}
|
|
476
481
|
// A channel's posts and their edits come as channel_post and edited_channel_post, sent as the channel itself.
|
|
477
482
|
const posted = update.message || update.channel_post;
|
|
478
483
|
const edited = update.edited_message || update.edited_channel_post;
|
|
@@ -545,4 +550,4 @@ function webhook(e) {
|
|
|
545
550
|
return e.json(200, { ok: true });
|
|
546
551
|
}
|
|
547
552
|
|
|
548
|
-
module.exports = { webhook, handleUpdate, flushAlbums };
|
|
553
|
+
module.exports = { webhook, handleUpdate, flushAlbums, mapped };
|
|
@@ -46,26 +46,55 @@ function queueCreate(app, rec) {
|
|
|
46
46
|
}
|
|
47
47
|
|
|
48
48
|
/**
|
|
49
|
-
* What a messages update changes for Telegram, read before it is saved
|
|
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
|
|
50
52
|
* @param {core.Record} rec
|
|
51
|
-
* @returns {"" | "edit" | "delete"}
|
|
53
|
+
* @returns {"" | "edit" | "delete" | "react"}
|
|
52
54
|
*/
|
|
53
|
-
function changeOf(rec) {
|
|
55
|
+
function changeOf(app, rec) {
|
|
54
56
|
const orig = rec.original();
|
|
55
57
|
if (rec.getBool("deleted") && !orig.getBool("deleted")) return "delete";
|
|
56
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
|
+
}
|
|
57
63
|
return "";
|
|
58
64
|
}
|
|
59
65
|
|
|
60
66
|
/**
|
|
61
|
-
* messages update (saved): queue an edit or
|
|
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.
|
|
62
69
|
* @param {core.App} app
|
|
63
70
|
* @param {core.Record} rec
|
|
64
|
-
* @param {"" | "edit" | "delete"} change
|
|
71
|
+
* @param {"" | "edit" | "delete" | "react"} change
|
|
65
72
|
*/
|
|
66
73
|
function queueUpdate(app, rec, change) {
|
|
67
74
|
if (!change || !rec.getString("author")) return; // a service message never went to Telegram
|
|
68
|
-
for (const link of linksOfRoom(app, rec.getString("room")))
|
|
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
|
+
}
|
|
69
98
|
}
|
|
70
99
|
|
|
71
100
|
// ---------------------------------------------------------------- the worker's side
|
|
@@ -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);
|