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.
- package/README.md +4 -1
- package/package.json +1 -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 +103 -26
- package/pb_hooks/telegram/people.js +4 -0
- package/pb_hooks/telegram/reactions.js +67 -11
- 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/{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/login-G7Y44CJ7.js +2 -0
- package/pb_public/assets/login-G7Y44CJ7.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 +2 -2
- 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-A3SXD3FF.css +0 -2
- package/pb_public/assets/app-A3SXD3FF.css.map +0 -7
- package/pb_public/assets/app-NDSIQW4L.js +0 -3
- package/pb_public/assets/app-NDSIQW4L.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
package/README.md
CHANGED
|
@@ -10,6 +10,9 @@ A small, fast, real-time group chat. One [PocketBase](https://pocketbase.io) bin
|
|
|
10
10
|
<img alt="A room in Chirkle: the room list with unread counts on the left; messages with avatars, a reply, a photo and emoji reactions on the right" src="docs/screenshot-light.png">
|
|
11
11
|
</picture>
|
|
12
12
|
|
|
13
|
+
- Runs on a $5 VPS (1 vCPU, 1 GB of RAM): about 500 people online at a normal pace, or 100 chatting nonstop
|
|
14
|
+
(measured, [PERF.md §8](docs/PERF.md#8-2026-11-09-a-5-vps-one-cpu)); past 100–200 clients, everyone
|
|
15
|
+
reconnecting at once can still swamp it
|
|
13
16
|
- Public rooms anyone can create; hide rooms you don't care about; creators archive rooms (read-only, history kept)
|
|
14
17
|
- Room access, chosen by each room's creator: **Private** (only the people they add), **Public** (everyone with an account) or **Open Air** (anyone can read it, no account needed; the home page shows these rooms to guests, who log in or sign up to join in); and who can post: everyone who can read it, or only the people they choose (the others read and react)
|
|
15
18
|
- Live messages, edits and deletes (deleted messages leave a placeholder)
|
|
@@ -246,7 +249,7 @@ set (`/.well-known/assetlinks.json`; `ANDROID_APP_ID` only for a build with anot
|
|
|
246
249
|
One version for the npm package and the Android app. `npm run release -- 0.2.0` sets it in `package.json` and
|
|
247
250
|
`android/app/build.gradle.kts` (versionCode + 1) and creates `fastlane/…/changelogs/<versionCode>.txt` to fill in.
|
|
248
251
|
Commit, push, then publish a GitHub Release with the new tag `v0.2.0`. The Release workflow
|
|
249
|
-
(`.github/workflows/release.yml`) checks the versions, attaches the signed APK
|
|
252
|
+
(`.github/workflows/release.yml`) checks the versions, attaches the signed APK and
|
|
250
253
|
stages `chirkle@0.2.0` on npm; approve it on npmjs.com (2FA) to publish it. Setup and details:
|
|
251
254
|
[`docs/ANDROID.md` §28.7](docs/ANDROID.md#287-one-release-for-the-app-and-the-npm-package-2026-11-08).
|
|
252
255
|
|
package/package.json
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
const { reactionsOf, setReaction } = require(`${__hooks}/lib/reactions.js`);
|
|
9
9
|
/** @typedef {{ emoji: string, users: string[] }} Reaction */
|
|
10
10
|
const { isReactionEmoji } = require(`${__hooks}/lib/emoji.js`);
|
|
11
|
+
const { accessOf, canSee } = require(`${__hooks}/lib/access.js`);
|
|
11
12
|
const { enqueue, enqueueWork, fromPeer, gid, isMine, jsonOf, newId, originOf, peerById, peerHost, splitGid } = require(
|
|
12
13
|
`${__hooks}/federation/config.js`,
|
|
13
14
|
);
|
|
@@ -83,6 +84,7 @@ function messageEvent(app, rec, peer) {
|
|
|
83
84
|
const author = rec.getString("author");
|
|
84
85
|
const from = rec.getString("forwarded_from");
|
|
85
86
|
const reactions = reactionsOf(rec);
|
|
87
|
+
const mentions = rec.getStringSlice("mentions");
|
|
86
88
|
return {
|
|
87
89
|
type: "message",
|
|
88
90
|
room: roomGid(room),
|
|
@@ -95,8 +97,9 @@ function messageEvent(app, rec, peer) {
|
|
|
95
97
|
created: rec.getString("created"),
|
|
96
98
|
files,
|
|
97
99
|
reactions: reactionsOut(app, rec),
|
|
100
|
+
mentions: mentions.map((u) => gidOf(app, u)),
|
|
98
101
|
},
|
|
99
|
-
people: peopleFor(app, peer, [author, from, ...reactions.flatMap((/** @type {Reaction} */ r) => r.users)]),
|
|
102
|
+
people: peopleFor(app, peer, [author, from, ...mentions, ...reactions.flatMap((/** @type {Reaction} */ r) => r.users)]),
|
|
100
103
|
};
|
|
101
104
|
}
|
|
102
105
|
|
|
@@ -186,7 +189,16 @@ function messageChanged(app, rec, was) {
|
|
|
186
189
|
enqueue(
|
|
187
190
|
app,
|
|
188
191
|
peerId,
|
|
189
|
-
deleted
|
|
192
|
+
deleted
|
|
193
|
+
? { type: "delete", room: rg, message: g }
|
|
194
|
+
: {
|
|
195
|
+
type: "edit",
|
|
196
|
+
room: rg,
|
|
197
|
+
message: g,
|
|
198
|
+
text: rec.getString("text"),
|
|
199
|
+
mentions: rec.getStringSlice("mentions").map((u) => gidOf(app, u)),
|
|
200
|
+
people: peerById(app, peerId) ? peopleFor(app, peerById(app, peerId), rec.getStringSlice("mentions")) : {},
|
|
201
|
+
},
|
|
190
202
|
);
|
|
191
203
|
}
|
|
192
204
|
}
|
|
@@ -285,6 +297,7 @@ function applyMessage(app, sender, ev, files) {
|
|
|
285
297
|
if (from) rec.set("forwarded_from", from);
|
|
286
298
|
}
|
|
287
299
|
if (files?.length) require(`${__hooks}/lib/files.js`).attachUploads(app, rec, files);
|
|
300
|
+
rec.set("mentions", mentionsIn(app, sender, room, author, m.mentions, people));
|
|
288
301
|
if (ev.backfill && typeof m.created === "string" && /^\d{4}-\d\d-\d\d[ T]\d\d:\d\d:\d\d/.test(m.created)) {
|
|
289
302
|
rec.setRaw("created", m.created);
|
|
290
303
|
rec.setRaw("updated", m.created);
|
|
@@ -295,6 +308,35 @@ function applyMessage(app, sender, ev, files) {
|
|
|
295
308
|
if (list.length) setReactions(app, sender, rec, list, people);
|
|
296
309
|
}
|
|
297
310
|
|
|
311
|
+
/**
|
|
312
|
+
* Who a peer's message mentions (§41): the people its event names by global id (its text's "@handle"s are the sender's
|
|
313
|
+
* handles, not ours) who can see the room here, but not its author. An instance from before mentions sends none.
|
|
314
|
+
* @param {core.App} app
|
|
315
|
+
* @param {core.Record} sender
|
|
316
|
+
* @param {core.Record} room
|
|
317
|
+
* @param {string} author
|
|
318
|
+
* @param {unknown} list
|
|
319
|
+
* @param {Record<string, any>} people
|
|
320
|
+
* @returns {string[]}
|
|
321
|
+
*/
|
|
322
|
+
function mentionsIn(app, sender, room, author, list, people) {
|
|
323
|
+
if (!Array.isArray(list)) return [];
|
|
324
|
+
const access = accessOf(room);
|
|
325
|
+
const out = new Set();
|
|
326
|
+
for (const g of list.slice(0, 20)) {
|
|
327
|
+
const id = userOf(app, sender, g, people);
|
|
328
|
+
if (id && id !== author && canSee(access, id)) out.add(id);
|
|
329
|
+
}
|
|
330
|
+
return [...out];
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/**
|
|
334
|
+
* Is this save of a message a linked instance's (it then says whom the message mentions, mentionsIn)?
|
|
335
|
+
* @param {core.App} app
|
|
336
|
+
* @param {core.Record} rec
|
|
337
|
+
*/
|
|
338
|
+
const isFromPeer = (app, rec) => !!originOf(app, rec.id);
|
|
339
|
+
|
|
298
340
|
/**
|
|
299
341
|
* Set a message's reactions from a list naming people by global id.
|
|
300
342
|
* @param {core.App} app
|
|
@@ -348,6 +390,9 @@ function applyEdit(app, sender, ev) {
|
|
|
348
390
|
const text = String(ev.text || "").slice(0, 2000);
|
|
349
391
|
if (text === rec.getString("text")) return;
|
|
350
392
|
rec.set("text", text);
|
|
393
|
+
const { room } = roomOf(app, sender, ev);
|
|
394
|
+
const people = ev.people && typeof ev.people === "object" ? ev.people : {};
|
|
395
|
+
rec.set("mentions", mentionsIn(app, sender, room, rec.getString("author"), ev.mentions, people));
|
|
351
396
|
saveFor(app, rec, sender);
|
|
352
397
|
}
|
|
353
398
|
|
|
@@ -417,4 +462,5 @@ module.exports = {
|
|
|
417
462
|
applyDelete,
|
|
418
463
|
applyReact,
|
|
419
464
|
applyReactions,
|
|
465
|
+
isFromPeer,
|
|
420
466
|
};
|
|
@@ -144,15 +144,19 @@ function probes(q, me) {
|
|
|
144
144
|
const REFUSAL = "Messages can't be filtered, sorted or grouped by who wrote them.";
|
|
145
145
|
|
|
146
146
|
/**
|
|
147
|
-
*
|
|
148
|
-
*
|
|
147
|
+
* A request refused when its query filters, sorts or groups by author (the records API's ?filter, ?sort, ?expand, on any
|
|
148
|
+
* collection, as a relation or back-relation can reach messages from any of them; our routes' ?expand). Called by the
|
|
149
|
+
* record request hooks (main.pb.js) and by each route that enriches records. Superusers may.
|
|
149
150
|
* @param {core.RequestEvent} e
|
|
150
151
|
*/
|
|
151
152
|
function refuseProbes(e) {
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
153
|
+
// requestInfo, not e.request: the record request hooks' events have no `request` in JS. Its values are decoded
|
|
154
|
+
// (%61uthor is "author").
|
|
155
|
+
const info = e.requestInfo();
|
|
156
|
+
const q = { filter: info.query.filter ?? "", sort: info.query.sort ?? "", expand: info.query.expand ?? "" };
|
|
157
|
+
if (!/author|forwarded_from/i.test(`${q.filter} ${q.sort} ${q.expand}`)) return;
|
|
158
|
+
if (!probes(q, info.auth?.id ?? "")) return;
|
|
159
|
+
if (info.auth?.isSuperuser()) return;
|
|
156
160
|
throw new BadRequestError(REFUSAL);
|
|
157
161
|
}
|
|
158
162
|
|
package/pb_hooks/lib/bulk.js
CHANGED
|
@@ -148,6 +148,8 @@ function originalOf(app, m) {
|
|
|
148
148
|
* @param {core.RequestEvent} e
|
|
149
149
|
*/
|
|
150
150
|
function forward(e) {
|
|
151
|
+
// As the records API's (main.pb.js): this page's ?expand mustn't group messages by author (§35).
|
|
152
|
+
require(`${__hooks}/lib/anonymous.js`).refuseProbes(e);
|
|
151
153
|
const me = e.auth;
|
|
152
154
|
if (!me) throw new UnauthorizedError("The request requires a logged-in user.");
|
|
153
155
|
const what = "Failed to forward the messages.";
|
package/pb_hooks/lib/files.js
CHANGED
|
@@ -5,8 +5,8 @@
|
|
|
5
5
|
//
|
|
6
6
|
// - A message's `files` and an item's `file` hold stored names, as they did when they were file fields, so clients
|
|
7
7
|
// build the same URLs: /api/files/messages/{message}/{name} and /api/files/collection_items/{item}/{name}. serve()
|
|
8
|
-
// answers those with the shared file
|
|
9
|
-
// that the message or item still has it. No file token: whoever has the URL has the file (§37.3).
|
|
8
|
+
// (routes of their own, by collection name) answers those with the shared file, as PocketBase's handler would,
|
|
9
|
+
// checking only that the message or item still has it. No file token: whoever has the URL has the file (§37.3).
|
|
10
10
|
// - `refs` counts the messages and items that name a file. link() and unlink() keep it in the same save; a file named
|
|
11
11
|
// by nothing is deleted, and PocketBase deletes what is stored once that is committed.
|
|
12
12
|
// - The media worker (lib/media.js) makes each file's thumbnails and video poster once, whoever names it.
|
|
@@ -286,64 +286,56 @@ function shownBy(app, collection, id, name) {
|
|
|
286
286
|
return shows ? byName(app, name) : null;
|
|
287
287
|
}
|
|
288
288
|
|
|
289
|
+
/** The images PocketBase makes thumbnails of, and the size it makes for any file field besides the field's own. */
|
|
290
|
+
const THUMB_EXT = ["jpg", "jpeg", "png", "gif", "webp"];
|
|
291
|
+
const DEFAULT_THUMB = "100x100";
|
|
292
|
+
|
|
289
293
|
/**
|
|
290
|
-
* GET /api/files/{
|
|
291
|
-
* collection item's file
|
|
292
|
-
*
|
|
293
|
-
*
|
|
294
|
-
*
|
|
294
|
+
* GET /api/files/messages/{recordId}/{filename} and /api/files/collection_items/{recordId}/{filename}: a message's or
|
|
295
|
+
* a collection item's file, served from its `files` row (§37). Routes of their own, more specific than PocketBase's
|
|
296
|
+
* /api/files/{collection}/…, so no other request runs JS for this: a router middleware would hold a JS runtime for every
|
|
297
|
+
* request, realtime connections and file downloads too (docs/PERF.md §6). As PocketBase's handler does: `thumb` (one of
|
|
298
|
+
* the field's sizes, or 100x100) serves that thumbnail of an image, made when first asked for; `download` makes it an
|
|
299
|
+
* attachment; ranges, and the headers that keep a file from running as a page (fs.serve). The token clients still
|
|
300
|
+
* send is ignored. 404 when the message or item doesn't show it (deleted, taken out). A file not moved to its row's
|
|
301
|
+
* folder yet is served from its old place (`src`), with a thumbnail only if one is there already: those folders have
|
|
302
|
+
* the ones that were ever asked for. The `files` rows themselves are served only through these (main.pb.js).
|
|
295
303
|
* @param {core.RequestEvent} e
|
|
296
|
-
* @
|
|
304
|
+
* @param {"messages" | "collection_items"} collection
|
|
297
305
|
*/
|
|
298
|
-
function serve(e) {
|
|
306
|
+
function serve(e, collection) {
|
|
299
307
|
const req = e.request;
|
|
300
|
-
|
|
301
|
-
const
|
|
302
|
-
const
|
|
303
|
-
const name = req.pathValue("filename");
|
|
304
|
-
if (!collection || !id || !name) return false;
|
|
305
|
-
let coll;
|
|
306
|
-
try {
|
|
307
|
-
coll = e.app.findCachedCollectionByNameOrId(collection);
|
|
308
|
-
} catch {
|
|
309
|
-
return false; // PocketBase answers 404
|
|
310
|
-
}
|
|
311
|
-
if (coll.name === "files") throw new NotFoundError();
|
|
312
|
-
if (coll.name !== "messages" && coll.name !== "collection_items") return false;
|
|
313
|
-
const row = shownBy(e.app, coll.name, id, name);
|
|
308
|
+
const id = req?.pathValue("recordId") ?? "";
|
|
309
|
+
const name = req?.pathValue("filename") ?? "";
|
|
310
|
+
const row = shownBy(e.app, collection, id, name);
|
|
314
311
|
if (!row) throw new NotFoundError();
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
req.setPathValue("collection", row.collection().id);
|
|
320
|
-
req.setPathValue("recordId", row.id);
|
|
321
|
-
return false;
|
|
322
|
-
}
|
|
323
|
-
|
|
324
|
-
/**
|
|
325
|
-
* A file not moved to its folder yet, served from its old place (src): a thumbnail asked for if it is there (the old
|
|
326
|
-
* folders have those that were ever asked for), else the file itself. PocketBase's handler would make a missing one,
|
|
327
|
-
* but serves only a file field's own files. As it does, `download` makes it an attachment.
|
|
328
|
-
* @param {core.RequestEvent} e
|
|
329
|
-
* @param {core.Record} row
|
|
330
|
-
*/
|
|
331
|
-
function serveUnmoved(e, row) {
|
|
332
|
-
const key = row.getString("src");
|
|
333
|
-
const name = row.getString("file");
|
|
334
|
-
const q = e.request?.url?.query();
|
|
312
|
+
const moved = !row.getString("src");
|
|
313
|
+
const key = keyOf(row);
|
|
314
|
+
const file = row.getString("file");
|
|
315
|
+
const q = req?.url?.query();
|
|
335
316
|
const thumb = q?.get("thumb") ?? "";
|
|
336
317
|
const sizes = /** @type {any} */ (row.collection().fields.getByName("file")).thumbs ?? [];
|
|
337
318
|
const fs = e.app.newFilesystem();
|
|
338
319
|
try {
|
|
339
320
|
let served = key;
|
|
340
|
-
if (thumb && sizes.includes(thumb)
|
|
341
|
-
|
|
321
|
+
if (thumb && (thumb === DEFAULT_THUMB || sizes.includes(thumb)) && THUMB_EXT.includes(ext(file))) {
|
|
322
|
+
const at = thumbKeyOf(key, thumb);
|
|
323
|
+
if (fs.exists(at)) served = at;
|
|
324
|
+
else if (moved && fs.exists(key)) {
|
|
325
|
+
try {
|
|
326
|
+
fs.createThumb(key, at, thumb);
|
|
327
|
+
served = at;
|
|
328
|
+
} catch {
|
|
329
|
+
served = key; // as PocketBase does: the file itself when it can't make one
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
if (served === key && !fs.exists(key)) throw new NotFoundError();
|
|
342
334
|
const download = q?.get("download") ?? "";
|
|
343
335
|
if (download && download !== "0" && download !== "false") {
|
|
344
|
-
e.response.header().set("Content-Disposition", `attachment; filename=${
|
|
336
|
+
e.response.header().set("Content-Disposition", `attachment; filename=${file}`);
|
|
345
337
|
}
|
|
346
|
-
fs.serve(e.response, /** @type {any} */ (
|
|
338
|
+
fs.serve(e.response, /** @type {any} */ (req), served, file);
|
|
347
339
|
} finally {
|
|
348
340
|
fs.close();
|
|
349
341
|
}
|
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
/// <reference path="../../types/pocketbase.d.ts" />
|
|
2
|
+
// Handles and mentions (DESIGN.md §41): every account has a handle (`users.handle`, a–z 0–9 _, 3–24, unique), which
|
|
3
|
+
// "@handle" in a message names. The hooks resolve a message's mentions from its text (`messages.mentions`: those named
|
|
4
|
+
// who can see its room); GET /api/chat/mentionable suggests people as "@" is typed.
|
|
5
|
+
|
|
6
|
+
const { accessOf, canSee, visibleRoom } = require(`${__hooks}/lib/access.js`);
|
|
7
|
+
const { fieldError } = require(`${__hooks}/lib/records.js`);
|
|
8
|
+
const { nameKey } = require(`${__hooks}/lib/text.js`);
|
|
9
|
+
|
|
10
|
+
const HANDLE_MIN = 3;
|
|
11
|
+
const HANDLE_MAX = 24;
|
|
12
|
+
const HANDLE = /^[a-z0-9_]{3,24}$/;
|
|
13
|
+
/** Kept for what may one day mean everyone in a room. */
|
|
14
|
+
const RESERVED = new Set(["all", "everyone", "here", "room", "channel"]);
|
|
15
|
+
/** Most people one message mentions. */
|
|
16
|
+
const MAX_MENTIONS = 20;
|
|
17
|
+
/** Most people GET /api/chat/mentionable suggests. */
|
|
18
|
+
const SUGGESTIONS = 8;
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* "@handle" in a message: after the start or anything but a letter, digit, "_", "@", "." or "/" (an email, a path, a
|
|
22
|
+
* linked instance's "ann@b.example"), and not followed by one of those. Keep in sync with web/src/lib/mentions.ts and
|
|
23
|
+
* the app's lib/Mentions.kt (shared/vectors/mentions.json).
|
|
24
|
+
*/
|
|
25
|
+
const MENTION = /(^|[^A-Za-z0-9_@./])@([A-Za-z0-9_]{3,24})(?![A-Za-z0-9_@])/g;
|
|
26
|
+
|
|
27
|
+
/** @type {Record<string, string>} */
|
|
28
|
+
const CYRILLIC = {
|
|
29
|
+
а: "a",
|
|
30
|
+
б: "b",
|
|
31
|
+
в: "v",
|
|
32
|
+
г: "g",
|
|
33
|
+
д: "d",
|
|
34
|
+
е: "e",
|
|
35
|
+
ё: "e",
|
|
36
|
+
ж: "zh",
|
|
37
|
+
з: "z",
|
|
38
|
+
и: "i",
|
|
39
|
+
й: "y",
|
|
40
|
+
к: "k",
|
|
41
|
+
л: "l",
|
|
42
|
+
м: "m",
|
|
43
|
+
н: "n",
|
|
44
|
+
о: "o",
|
|
45
|
+
п: "p",
|
|
46
|
+
р: "r",
|
|
47
|
+
с: "s",
|
|
48
|
+
т: "t",
|
|
49
|
+
у: "u",
|
|
50
|
+
ф: "f",
|
|
51
|
+
х: "kh",
|
|
52
|
+
ц: "ts",
|
|
53
|
+
ч: "ch",
|
|
54
|
+
ш: "sh",
|
|
55
|
+
щ: "shch",
|
|
56
|
+
ъ: "",
|
|
57
|
+
ы: "y",
|
|
58
|
+
ь: "",
|
|
59
|
+
э: "e",
|
|
60
|
+
ю: "yu",
|
|
61
|
+
я: "ya",
|
|
62
|
+
і: "i",
|
|
63
|
+
ї: "yi",
|
|
64
|
+
є: "ye",
|
|
65
|
+
ґ: "g",
|
|
66
|
+
ў: "u",
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Letters NFKD leaves whole (Ł, Ø, Æ, Þ…) and Greek, spelled in Latin: "Łukasz" was "ukasz", "Ørjan" "rjan" (QA BUG-255).
|
|
71
|
+
* @type {Record<string, string>}
|
|
72
|
+
*/
|
|
73
|
+
const LATIN = {
|
|
74
|
+
ł: "l",
|
|
75
|
+
ø: "o",
|
|
76
|
+
æ: "ae",
|
|
77
|
+
œ: "oe",
|
|
78
|
+
đ: "d",
|
|
79
|
+
ð: "d",
|
|
80
|
+
þ: "th",
|
|
81
|
+
ı: "i",
|
|
82
|
+
ħ: "h",
|
|
83
|
+
ŧ: "t",
|
|
84
|
+
ŋ: "ng",
|
|
85
|
+
α: "a",
|
|
86
|
+
β: "v",
|
|
87
|
+
γ: "g",
|
|
88
|
+
δ: "d",
|
|
89
|
+
ε: "e",
|
|
90
|
+
ζ: "z",
|
|
91
|
+
η: "i",
|
|
92
|
+
θ: "th",
|
|
93
|
+
ι: "i",
|
|
94
|
+
κ: "k",
|
|
95
|
+
λ: "l",
|
|
96
|
+
μ: "m",
|
|
97
|
+
ν: "n",
|
|
98
|
+
ξ: "x",
|
|
99
|
+
ο: "o",
|
|
100
|
+
π: "p",
|
|
101
|
+
ρ: "r",
|
|
102
|
+
σ: "s",
|
|
103
|
+
ς: "s",
|
|
104
|
+
τ: "t",
|
|
105
|
+
υ: "y",
|
|
106
|
+
φ: "f",
|
|
107
|
+
χ: "ch",
|
|
108
|
+
ψ: "ps",
|
|
109
|
+
ω: "o",
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* A handle made from a display name: Latin letters without their accents, Cyrillic spelled in Latin, anything else
|
|
114
|
+
* an "_" (at most 20, so a number fits after it). Keep in sync with pb_migrations/1760000045_mentions.js.
|
|
115
|
+
* @param {string} name
|
|
116
|
+
*/
|
|
117
|
+
function handleFrom(name) {
|
|
118
|
+
let s = [...name.toLowerCase()].map((c) => CYRILLIC[c] ?? c).join("");
|
|
119
|
+
if (typeof s.normalize === "function") s = s.normalize("NFKD").replace(/[̀-ͯ]/g, "");
|
|
120
|
+
s = s
|
|
121
|
+
.replace(/ß/g, "ss")
|
|
122
|
+
.replace(/[\u0080-\uffff]/g, (c) => LATIN[c] ?? c)
|
|
123
|
+
.replace(/[^a-z0-9]+/g, "_")
|
|
124
|
+
.replace(/^_+|_+$/g, "")
|
|
125
|
+
.slice(0, 20)
|
|
126
|
+
.replace(/_+$/, "");
|
|
127
|
+
if (s.length < HANDLE_MIN) s = s ? `${s}_user` : "user";
|
|
128
|
+
return s;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Is `handle` someone else's than user `id`'s?
|
|
133
|
+
* @param {core.App} app
|
|
134
|
+
* @param {string} handle
|
|
135
|
+
* @param {string} id
|
|
136
|
+
*/
|
|
137
|
+
function taken(app, handle, id) {
|
|
138
|
+
if (RESERVED.has(handle)) return true;
|
|
139
|
+
try {
|
|
140
|
+
app.findFirstRecordByFilter("users", "handle = {:h} && id != {:id}", { h: handle, id });
|
|
141
|
+
return true;
|
|
142
|
+
} catch {
|
|
143
|
+
return false;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* The first free handle for `base` ("ann", then "ann2", "ann3"…).
|
|
149
|
+
* @param {core.App} app
|
|
150
|
+
* @param {string} base
|
|
151
|
+
* @param {string} id the user's own (their handle isn't taken from them)
|
|
152
|
+
*/
|
|
153
|
+
function freeHandle(app, base, id) {
|
|
154
|
+
for (let n = 1; n < 10000; n++) {
|
|
155
|
+
const tail = n > 1 ? String(n) : "";
|
|
156
|
+
const candidate = `${base.slice(0, HANDLE_MAX - tail.length)}${tail}`;
|
|
157
|
+
if (!taken(app, candidate, id)) return candidate;
|
|
158
|
+
}
|
|
159
|
+
return `${base.slice(0, HANDLE_MAX - 10)}_${$security.randomStringWithAlphabet(9, "abcdefghijklmnopqrstuvwxyz0123456789")}`;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* A handle as typed: no leading "@", in lower case, trimmed.
|
|
164
|
+
* @param {string} raw
|
|
165
|
+
*/
|
|
166
|
+
const normalHandle = (raw) => raw.trim().replace(/^@/, "").toLowerCase();
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* users create/update (lib/users.js beforeUserSave): a new account without a handle gets one from its name; one typed
|
|
170
|
+
* is checked (allowed characters, length, not someone else's). An update that keeps it keeps it unchecked.
|
|
171
|
+
* @param {core.App} app
|
|
172
|
+
* @param {core.Record} rec
|
|
173
|
+
*/
|
|
174
|
+
function setHandle(app, rec) {
|
|
175
|
+
const typed = normalHandle(rec.getString("handle"));
|
|
176
|
+
if (!rec.isNew() && typed === rec.original().getString("handle")) {
|
|
177
|
+
rec.set("handle", typed);
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
if (typed === "") {
|
|
181
|
+
if (!rec.isNew() && rec.original().getString("handle") !== "") throw fieldError("handle", "Cannot be blank.", "validation_required");
|
|
182
|
+
rec.set("handle", freeHandle(app, handleFrom(rec.getString("name")), rec.id));
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
if (!HANDLE.test(typed)) {
|
|
186
|
+
throw fieldError("handle", `Use ${HANDLE_MIN} to ${HANDLE_MAX} letters a–z, digits or underscores.`);
|
|
187
|
+
}
|
|
188
|
+
if (taken(app, typed, rec.id)) throw fieldError("handle", "This handle is taken. Choose another one.", "validation_not_unique");
|
|
189
|
+
rec.set("handle", typed);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* The handles "@"-named in `text`, in lower case, each once, at most MAX_MENTIONS.
|
|
194
|
+
* @param {string} text
|
|
195
|
+
*/
|
|
196
|
+
function handlesIn(text) {
|
|
197
|
+
const out = new Set();
|
|
198
|
+
for (const m of text.matchAll(MENTION)) {
|
|
199
|
+
out.add(m[2].toLowerCase());
|
|
200
|
+
if (out.size >= MAX_MENTIONS) break;
|
|
201
|
+
}
|
|
202
|
+
return [...out];
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* Who message `rec` mentions: the people its text names who can see its room, but not its author.
|
|
207
|
+
* @param {core.App} app
|
|
208
|
+
* @param {core.Record} rec
|
|
209
|
+
* @returns {string[]} user ids
|
|
210
|
+
*/
|
|
211
|
+
function mentionsOf(app, rec) {
|
|
212
|
+
const handles = handlesIn(rec.getString("text"));
|
|
213
|
+
if (!handles.length) return [];
|
|
214
|
+
let room;
|
|
215
|
+
try {
|
|
216
|
+
room = app.findRecordById("rooms", rec.getString("room"));
|
|
217
|
+
} catch {
|
|
218
|
+
return [];
|
|
219
|
+
}
|
|
220
|
+
const access = accessOf(room);
|
|
221
|
+
const params = Object.fromEntries(handles.map((h, i) => [`h${i}`, h]));
|
|
222
|
+
const found = app.findRecordsByFilter("users", handles.map((_, i) => `handle = {:h${i}}`).join(" || "), "", MAX_MENTIONS, 0, params);
|
|
223
|
+
const author = rec.getString("author");
|
|
224
|
+
const byHandle = new Map(found.flatMap((u) => (u ? [[u.getString("handle"), u.id]] : [])));
|
|
225
|
+
return handles.flatMap((h) => {
|
|
226
|
+
const id = byHandle.get(h);
|
|
227
|
+
return id && id !== author && canSee(access, id) ? [id] : [];
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* messages create and update (main.pb.js): `mentions` from the text, unless the save is a linked instance's (§33),
|
|
233
|
+
* which names the people itself (federation/messages.js). A forward mentions no one: its words are the original's.
|
|
234
|
+
* @param {core.App} app
|
|
235
|
+
* @param {core.Record} rec
|
|
236
|
+
* @param {boolean} fromPeer
|
|
237
|
+
*/
|
|
238
|
+
function setMentions(app, rec, fromPeer) {
|
|
239
|
+
if (fromPeer) return;
|
|
240
|
+
if (rec.getString("forwarded_from") !== "" || rec.getBool("deleted") || rec.getString("author") === "") {
|
|
241
|
+
rec.set("mentions", []);
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
// Unchanged text keeps them (or what PocketBase left of them, a mentioned account deleted for good). The update
|
|
245
|
+
// request hook refuses any other change.
|
|
246
|
+
if (!rec.isNew() && rec.getString("text") === rec.original().getString("text")) return;
|
|
247
|
+
rec.set("mentions", mentionsOf(app, rec));
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** Messages looked at for who has written in a room lately. */
|
|
251
|
+
const RECENT = 300;
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* GET /api/chat/mentionable?room=&q= → up to SUGGESTIONS people who can see `room` whose handle or name starts with
|
|
255
|
+
* (or, failing enough of those, contains) `q`, as the composer's "@" suggestions: [{ id, name, handle, avatar,
|
|
256
|
+
* instance }]. Those who wrote there lately first (not in an anonymous room, where that would say who they are), the
|
|
257
|
+
* caller never. An empty `q` lists those recent writers, or a private room's members.
|
|
258
|
+
* @param {core.RequestEvent} e
|
|
259
|
+
*/
|
|
260
|
+
function mentionable(e) {
|
|
261
|
+
const me = e.auth;
|
|
262
|
+
if (!me) throw new UnauthorizedError("The request requires a logged-in user.");
|
|
263
|
+
const q = e.requestInfo().query;
|
|
264
|
+
const room = visibleRoom(e.app, typeof q.room === "string" ? q.room : "", me.id);
|
|
265
|
+
if (!room) throw new NotFoundError("The room doesn't exist.");
|
|
266
|
+
const typed = normalHandle(typeof q.q === "string" ? q.q : "").slice(0, 32);
|
|
267
|
+
const key = nameKey(typed);
|
|
268
|
+
const access = accessOf(room);
|
|
269
|
+
|
|
270
|
+
/** @type {string[]} */
|
|
271
|
+
let recent = [];
|
|
272
|
+
if (!room.getBool("anonymous")) {
|
|
273
|
+
const rows = arrayOf(new DynamicModel({ author: "" }));
|
|
274
|
+
e.app
|
|
275
|
+
.db()
|
|
276
|
+
.newQuery(
|
|
277
|
+
`SELECT author FROM (SELECT author, created FROM messages WHERE room = {:room} AND author != '' AND deleted = FALSE ORDER BY created DESC LIMIT ${RECENT}) GROUP BY author ORDER BY MAX(created) DESC LIMIT 50`,
|
|
278
|
+
)
|
|
279
|
+
.bind({ room: room.id })
|
|
280
|
+
.all(rows);
|
|
281
|
+
recent = rows.map((r) => r.author);
|
|
282
|
+
}
|
|
283
|
+
const rank = new Map(recent.map((id, i) => [id, i]));
|
|
284
|
+
|
|
285
|
+
/** @type {core.Record[]} */
|
|
286
|
+
let pool = [];
|
|
287
|
+
const members = access.visibility === "private" ? [...new Set([access.createdBy, ...access.members])].filter(Boolean) : [];
|
|
288
|
+
if (members.length) {
|
|
289
|
+
pool = e.app.findRecordsByIds("users", members).filter((u) => !!u);
|
|
290
|
+
} else if (typed) {
|
|
291
|
+
const like = { h: `${typed.replace(/[%_\\]/g, "\\$&")}%`, k: `%${key.replace(/[%_\\]/g, "\\$&")}%` };
|
|
292
|
+
const rows = arrayOf(new DynamicModel({ id: "" }));
|
|
293
|
+
e.app
|
|
294
|
+
.db()
|
|
295
|
+
.newQuery(
|
|
296
|
+
"SELECT id FROM users WHERE banned = FALSE AND (handle LIKE {:h} ESCAPE '\\' OR name_key LIKE {:k} ESCAPE '\\') ORDER BY handle LIMIT 200",
|
|
297
|
+
)
|
|
298
|
+
.bind(like)
|
|
299
|
+
.all(rows);
|
|
300
|
+
// With those who wrote lately, whom a short query may match among many more.
|
|
301
|
+
pool = e.app.findRecordsByIds("users", [...new Set([...recent, ...rows.map((r) => r.id)])]).filter((u) => !!u);
|
|
302
|
+
} else if (recent.length) {
|
|
303
|
+
pool = e.app.findRecordsByIds("users", recent).filter((u) => !!u);
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/** @param {core.Record} u */
|
|
307
|
+
const score = (u) => {
|
|
308
|
+
const handle = u.getString("handle");
|
|
309
|
+
const name = nameKey(u.getString("name"));
|
|
310
|
+
if (!typed) return 0;
|
|
311
|
+
if (handle.startsWith(typed)) return 0;
|
|
312
|
+
if (name.startsWith(key) || name.split(/[\s_\-.]+/).some((/** @type {string} */ w) => w.startsWith(key))) return 1;
|
|
313
|
+
if (handle.includes(typed) || name.includes(key)) return 2;
|
|
314
|
+
return 3;
|
|
315
|
+
};
|
|
316
|
+
const found = pool
|
|
317
|
+
.filter((u) => u.id !== me.id && u.getString("handle") !== "" && !u.getBool("banned") && canSee(access, u.id) && score(u) < 3)
|
|
318
|
+
.sort(
|
|
319
|
+
(a, b) =>
|
|
320
|
+
score(a) - score(b) ||
|
|
321
|
+
(rank.get(a.id) ?? 1e9) - (rank.get(b.id) ?? 1e9) ||
|
|
322
|
+
a.getString("handle").localeCompare(b.getString("handle")),
|
|
323
|
+
)
|
|
324
|
+
.slice(0, SUGGESTIONS);
|
|
325
|
+
return e.json(
|
|
326
|
+
200,
|
|
327
|
+
found.map((u) => ({
|
|
328
|
+
id: u.id,
|
|
329
|
+
name: u.getString("name"),
|
|
330
|
+
handle: u.getString("handle"),
|
|
331
|
+
avatar: u.getString("avatar"),
|
|
332
|
+
instance: u.getString("instance"),
|
|
333
|
+
})),
|
|
334
|
+
);
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
module.exports = { HANDLE, MENTION, handleFrom, freeHandle, setHandle, handlesIn, mentionsOf, setMentions, mentionable, normalHandle };
|