chirkle 0.5.0 → 0.5.4

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 (116) hide show
  1. package/README.md +3 -1
  2. package/bin/release/darwin-amd64/chirkle-server +1 -1
  3. package/bin/release/darwin-arm64/chirkle-server +0 -0
  4. package/bin/release/linux-amd64/chirkle-server +1 -1
  5. package/bin/release/linux-arm64/chirkle-server +0 -0
  6. package/package.json +1 -1
  7. package/pb_hooks/federation/inbox.js +2 -0
  8. package/pb_hooks/federation/messages.js +40 -2
  9. package/pb_hooks/federation/worker.js +7 -3
  10. package/pb_hooks/lib/files.js +36 -0
  11. package/pb_hooks/lib/media.js +14 -1
  12. package/pb_hooks/lib/messages.js +16 -6
  13. package/pb_hooks/lib/pins.js +199 -0
  14. package/pb_hooks/lib/rooms.js +4 -0
  15. package/pb_hooks/main.pb.js +16 -3
  16. package/pb_hooks/telegram/inbound.js +182 -16
  17. package/pb_hooks/telegram/outbound.js +98 -11
  18. package/pb_hooks/telegram/worker.js +2 -1
  19. package/pb_migrations/1760000059_telegram_media_edits.js +37 -0
  20. package/pb_migrations/1760000060_pins.js +23 -0
  21. package/pb_public/assets/{access-KVSI7EFH.js → access-23A7N3OD.js} +2 -2
  22. package/pb_public/assets/access-23A7N3OD.js.br +0 -0
  23. package/pb_public/assets/access-23A7N3OD.js.gz +0 -0
  24. package/pb_public/assets/app-A7HBI65K.js +3 -0
  25. package/pb_public/assets/app-A7HBI65K.js.br +0 -0
  26. package/pb_public/assets/app-A7HBI65K.js.gz +0 -0
  27. package/pb_public/assets/app-A7HBI65K.js.map +7 -0
  28. package/pb_public/assets/app-HMWQXURS.css +2 -0
  29. package/pb_public/assets/app-HMWQXURS.css.br +0 -0
  30. package/pb_public/assets/app-HMWQXURS.css.gz +0 -0
  31. package/pb_public/assets/app-HMWQXURS.css.map +7 -0
  32. package/pb_public/assets/chunk-DC4TJ7HF.js +2 -0
  33. package/pb_public/assets/chunk-DC4TJ7HF.js.br +0 -0
  34. package/pb_public/assets/chunk-DC4TJ7HF.js.gz +0 -0
  35. package/pb_public/assets/chunk-DC4TJ7HF.js.map +7 -0
  36. package/pb_public/assets/{chunk-LDZPNZ2E.js → chunk-SM542ZXL.js} +2 -2
  37. package/pb_public/assets/chunk-SM542ZXL.js.br +0 -0
  38. package/pb_public/assets/chunk-SM542ZXL.js.gz +0 -0
  39. package/pb_public/assets/chunk-SZMAZMR4.js +2 -0
  40. package/pb_public/assets/chunk-SZMAZMR4.js.br +0 -0
  41. package/pb_public/assets/chunk-SZMAZMR4.js.gz +0 -0
  42. package/pb_public/assets/chunk-SZMAZMR4.js.map +7 -0
  43. package/pb_public/assets/{chunk-EO3AMXJN.js → chunk-WDXT4S4J.js} +2 -2
  44. package/pb_public/assets/chunk-WDXT4S4J.js.br +0 -0
  45. package/pb_public/assets/chunk-WDXT4S4J.js.gz +0 -0
  46. package/pb_public/assets/{emoji-picker-W27IJER2.js → emoji-picker-K4DOKYL3.js} +2 -2
  47. package/pb_public/assets/emoji-picker-K4DOKYL3.js.br +0 -0
  48. package/pb_public/assets/{emoji-picker-W27IJER2.js.gz → emoji-picker-K4DOKYL3.js.gz} +0 -0
  49. package/pb_public/assets/{emoji-picker-W27IJER2.js.map → emoji-picker-K4DOKYL3.js.map} +2 -2
  50. package/pb_public/assets/forward-OR7S3EHR.js +2 -0
  51. package/pb_public/assets/forward-OR7S3EHR.js.br +0 -0
  52. package/pb_public/assets/forward-OR7S3EHR.js.gz +0 -0
  53. package/pb_public/assets/forward-OR7S3EHR.js.map +7 -0
  54. package/pb_public/assets/{invite-6BCBF4KV.js → invite-VGT2DI2L.js} +2 -2
  55. package/pb_public/assets/invite-VGT2DI2L.js.br +0 -0
  56. package/pb_public/assets/invite-VGT2DI2L.js.gz +0 -0
  57. package/pb_public/assets/{login-FZY6GOMF.js → login-TN6R7N2U.js} +2 -2
  58. package/pb_public/assets/login-TN6R7N2U.js.br +0 -0
  59. package/pb_public/assets/login-TN6R7N2U.js.gz +0 -0
  60. package/pb_public/assets/pins-DSUFB5EW.css +2 -0
  61. package/pb_public/assets/pins-DSUFB5EW.css.br +0 -0
  62. package/pb_public/assets/pins-DSUFB5EW.css.gz +0 -0
  63. package/pb_public/assets/pins-DSUFB5EW.css.map +7 -0
  64. package/pb_public/assets/pins-XWBYZN4P.js +2 -0
  65. package/pb_public/assets/pins-XWBYZN4P.js.br +0 -0
  66. package/pb_public/assets/pins-XWBYZN4P.js.gz +0 -0
  67. package/pb_public/assets/pins-XWBYZN4P.js.map +7 -0
  68. package/pb_public/assets/{profile-7KMXLX5U.js → profile-NQ6QCQIB.js} +2 -2
  69. package/pb_public/assets/profile-NQ6QCQIB.js.br +0 -0
  70. package/pb_public/assets/profile-NQ6QCQIB.js.gz +0 -0
  71. package/pb_public/assets/{rooms-forms-IADHTHBZ.js → rooms-forms-NYMPXVUQ.js} +2 -2
  72. package/pb_public/assets/rooms-forms-NYMPXVUQ.js.br +0 -0
  73. package/pb_public/assets/rooms-forms-NYMPXVUQ.js.gz +0 -0
  74. package/pb_public/index.html +6 -6
  75. package/pb_public/assets/access-KVSI7EFH.js.br +0 -0
  76. package/pb_public/assets/access-KVSI7EFH.js.gz +0 -0
  77. package/pb_public/assets/app-5JOOV6JX.js +0 -3
  78. package/pb_public/assets/app-5JOOV6JX.js.br +0 -0
  79. package/pb_public/assets/app-5JOOV6JX.js.gz +0 -0
  80. package/pb_public/assets/app-5JOOV6JX.js.map +0 -7
  81. package/pb_public/assets/app-7OMYYLCI.css +0 -2
  82. package/pb_public/assets/app-7OMYYLCI.css.br +0 -0
  83. package/pb_public/assets/app-7OMYYLCI.css.gz +0 -0
  84. package/pb_public/assets/app-7OMYYLCI.css.map +0 -7
  85. package/pb_public/assets/chunk-5PKDEWJS.js +0 -2
  86. package/pb_public/assets/chunk-5PKDEWJS.js.br +0 -0
  87. package/pb_public/assets/chunk-5PKDEWJS.js.gz +0 -0
  88. package/pb_public/assets/chunk-5PKDEWJS.js.map +0 -7
  89. package/pb_public/assets/chunk-EO3AMXJN.js.br +0 -0
  90. package/pb_public/assets/chunk-EO3AMXJN.js.gz +0 -0
  91. package/pb_public/assets/chunk-LDZPNZ2E.js.br +0 -0
  92. package/pb_public/assets/chunk-LDZPNZ2E.js.gz +0 -0
  93. package/pb_public/assets/chunk-Y5MCBN66.js +0 -2
  94. package/pb_public/assets/chunk-Y5MCBN66.js.br +0 -0
  95. package/pb_public/assets/chunk-Y5MCBN66.js.gz +0 -0
  96. package/pb_public/assets/chunk-Y5MCBN66.js.map +0 -7
  97. package/pb_public/assets/emoji-picker-W27IJER2.js.br +0 -0
  98. package/pb_public/assets/forward-5TJEYGEV.js +0 -2
  99. package/pb_public/assets/forward-5TJEYGEV.js.br +0 -0
  100. package/pb_public/assets/forward-5TJEYGEV.js.gz +0 -0
  101. package/pb_public/assets/forward-5TJEYGEV.js.map +0 -7
  102. package/pb_public/assets/invite-6BCBF4KV.js.br +0 -0
  103. package/pb_public/assets/invite-6BCBF4KV.js.gz +0 -0
  104. package/pb_public/assets/login-FZY6GOMF.js.br +0 -0
  105. package/pb_public/assets/login-FZY6GOMF.js.gz +0 -0
  106. package/pb_public/assets/profile-7KMXLX5U.js.br +0 -0
  107. package/pb_public/assets/profile-7KMXLX5U.js.gz +0 -0
  108. package/pb_public/assets/rooms-forms-IADHTHBZ.js.br +0 -0
  109. package/pb_public/assets/rooms-forms-IADHTHBZ.js.gz +0 -0
  110. /package/pb_public/assets/{access-KVSI7EFH.js.map → access-23A7N3OD.js.map} +0 -0
  111. /package/pb_public/assets/{chunk-LDZPNZ2E.js.map → chunk-SM542ZXL.js.map} +0 -0
  112. /package/pb_public/assets/{chunk-EO3AMXJN.js.map → chunk-WDXT4S4J.js.map} +0 -0
  113. /package/pb_public/assets/{invite-6BCBF4KV.js.map → invite-VGT2DI2L.js.map} +0 -0
  114. /package/pb_public/assets/{login-FZY6GOMF.js.map → login-TN6R7N2U.js.map} +0 -0
  115. /package/pb_public/assets/{profile-7KMXLX5U.js.map → profile-NQ6QCQIB.js.map} +0 -0
  116. /package/pb_public/assets/{rooms-forms-IADHTHBZ.js.map → rooms-forms-NYMPXVUQ.js.map} +0 -0
package/README.md CHANGED
@@ -41,6 +41,8 @@ Mentions & replies, which load on first use).
41
41
  - What you were typing is kept per room, even across a reload; "Jump to latest" whenever you are scrolled up
42
42
  - Invite links for private rooms: share one link that adds whoever opens it (after logging in or signing up) as a
43
43
  member; it works for 1, 7 or 30 days and can be revoked or replaced at any time (web and Android)
44
+ - Pinned messages: up to 20 per room or DM, in a bar under its header; click to go to each, however far back. A room's
45
+ creator and moderators pin in rooms, either person in a DM; edits show in the pin, a deleted message is unpinned (web and the console client)
44
46
  - Moderators, chosen by the admin: they delete anyone's messages, change any room's access, archive rooms, and ban or
45
47
  unban people (a banned account can't log in); DMs and private rooms they aren't in stay out of their reach
46
48
  - Usage statistics at `/stats` for moderators and the admin: people online now, messages and active people over
@@ -69,7 +71,7 @@ Mentions & replies, which load on first use).
69
71
  **Documentation: [chirkle.com/docs](https://chirkle.com/docs/)**: installing and deploying, the user guide, administration, the
70
72
  Android app, linked servers, the Telegram bridge and the configuration reference.
71
73
 
72
- Design: [`docs/DESIGN.md`](docs/DESIGN.md) · Android app: [`docs/ANDROID.md`](docs/ANDROID.md) · QA: [`docs/QA.md`](docs/QA.md) · Refactoring plan: [`docs/REFACTOR.md`](docs/REFACTOR.md) · Archived plans: [MVP build](docs/history/BUILD_PLAN.md), [avatars, DMs, attachments](docs/history/NEXT_FEATURES_PLAN.md)
74
+ Design: [`docs/DESIGN.md`](docs/DESIGN.md) · Android app: [`docs/ANDROID.md`](docs/ANDROID.md) · Console client: [`docs/CLI.md`](docs/CLI.md) · QA: [`docs/QA.md`](docs/QA.md) · Refactoring plan: [`docs/REFACTOR.md`](docs/REFACTOR.md) · Archived plans: [MVP build](docs/history/BUILD_PLAN.md), [avatars, DMs, attachments](docs/history/NEXT_FEATURES_PLAN.md)
73
75
 
74
76
  ## Requirements
75
77
 
@@ -1,4 +1,4 @@
1
1
  [diffend] Oversized file quarantined before diffing.
2
2
  name: package/bin/release/darwin-amd64/chirkle-server
3
3
  size: 34443616 bytes
4
- sha256: 699ea474005e640f9ea524a65f4ffe9fa9fd20fc1829614da19e91c1a77d08c0
4
+ sha256: fe89a9f3e4779c62b10321994f892db8afb79fa3bbb0d78107af88e0d8b14832
@@ -1,4 +1,4 @@
1
1
  [diffend] Oversized file quarantined before diffing.
2
2
  name: package/bin/release/linux-amd64/chirkle-server
3
3
  size: 34058400 bytes
4
- sha256: 6f98184e19276f6ef979a9c220572ee1ec7bf8bf4e5fde4a88df5bdc6f8db78e
4
+ sha256: 93b5752575fff61bc065e312fa30e1134a12e60ff96abb4a907ba8efd7b75f50
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "chirkle",
3
- "version": "0.5.0",
3
+ "version": "0.5.4",
4
4
  "description": "A small, fast, real-time group chat: one PocketBase server, a vanilla TypeScript web app",
5
5
  "license": "GPL-3.0-or-later",
6
6
  "repository": {
@@ -54,6 +54,8 @@ function apply(app, peer, ev) {
54
54
  return fedMessages.applyMessage(app, peer, ev);
55
55
  case "edit":
56
56
  return fedMessages.applyEdit(app, peer, ev);
57
+ case "files":
58
+ return fedMessages.applyFiles(app, peer, ev);
57
59
  case "delete":
58
60
  return fedMessages.applyDelete(app, peer, ev);
59
61
  case "react":
@@ -141,7 +141,12 @@ function messageCreated(app, rec) {
141
141
  */
142
142
  function before(rec) {
143
143
  const orig = rec.original();
144
- return { text: orig.getString("text"), deleted: orig.getBool("deleted"), reactions: reactionsOf(orig) };
144
+ return {
145
+ text: orig.getString("text"),
146
+ files: orig.getStringSlice("files"),
147
+ deleted: orig.getBool("deleted"),
148
+ reactions: reactionsOf(orig),
149
+ };
145
150
  }
146
151
 
147
152
  /**
@@ -152,7 +157,8 @@ function before(rec) {
152
157
  */
153
158
  function checkMirrorChange(app, rec) {
154
159
  const orig = rec.original();
155
- if (rec.getString("text") === orig.getString("text") && rec.getBool("deleted") === orig.getBool("deleted")) return;
160
+ const sameFiles = rec.getStringSlice("files").join("/") === orig.getStringSlice("files").join("/");
161
+ if (rec.getString("text") === orig.getString("text") && sameFiles && rec.getBool("deleted") === orig.getBool("deleted")) return;
156
162
  if (originOf(app, rec.id)) return;
157
163
  let room;
158
164
  try {
@@ -202,6 +208,12 @@ function messageChanged(app, rec, was) {
202
208
  );
203
209
  }
204
210
  }
211
+ // Its attachments replaced (a Telegram media edit, §26.4): the new ones, which peers fetch from here (§33.8).
212
+ if (!rec.getBool("deleted") && rec.getStringSlice("files").join("/") !== was.files.join("/")) {
213
+ const names = jsonOf(rec, "file_names", {});
214
+ const files = rec.getStringSlice("files").map((f) => ({ path: `/api/fed/files/${rec.id}/${f}`, name: String(names[f] || f) }));
215
+ for (const peerId of audience(app, room, rec.id)) enqueue(app, peerId, { type: "files", room: rg, message: g, files });
216
+ }
205
217
  const now = reactionsOf(rec);
206
218
  if (deleted || JSON.stringify(now) === JSON.stringify(was.reactions)) return;
207
219
  if (isMirror(room)) {
@@ -396,6 +408,31 @@ function applyEdit(app, sender, ev) {
396
408
  saveFor(app, rec, sender);
397
409
  }
398
410
 
411
+ /**
412
+ * A `files` event: a message's attachments replaced where it came from (a Telegram media edit, §26.4). Like an edit,
413
+ * only from the author's own instance on the home, never our own people's on a mirror. The new files are fetched
414
+ * first (the worker, §33.8; `files`: the fetched ones, then); when none comes, the message keeps its own.
415
+ * @param {core.App} app
416
+ * @param {core.Record} sender
417
+ * @param {any} ev
418
+ * @param {any[]} [files] filesystem.File
419
+ */
420
+ function applyFiles(app, sender, ev, files) {
421
+ const rec = target(app, sender, ev, true);
422
+ if (!rec || rec.getBool("deleted") || rec.getString("forwarded_from")) return;
423
+ if (isMine(gidOf(app, rec.getString("author")))) throw refusal(403, "People of this instance change their messages here.");
424
+ const listed = (Array.isArray(ev.files) ? ev.files : []).slice(0, MAX_FILES);
425
+ if (!listed.length) return;
426
+ if (!files) {
427
+ enqueueWork(app, sender.id, "fetch", { event: ev });
428
+ return;
429
+ }
430
+ if (!files.length) return;
431
+ const shared = require(`${__hooks}/lib/files.js`);
432
+ shared.replaceMessageFiles(app, rec, shared.fromUploads(app, files));
433
+ saveFor(app, rec, sender);
434
+ }
435
+
399
436
  /**
400
437
  * A `delete` event. A message still being fetched is dropped from the queue.
401
438
  * @param {core.App} app
@@ -461,6 +498,7 @@ module.exports = {
461
498
  messageChanged,
462
499
  applyMessage,
463
500
  applyEdit,
501
+ applyFiles,
464
502
  applyDelete,
465
503
  applyReact,
466
504
  applyReactions,
@@ -7,7 +7,7 @@
7
7
 
8
8
  const { isActive, jsonOf, peerHost } = require(`${__hooks}/federation/config.js`);
9
9
  const { call, errorOf, jsonBody } = require(`${__hooks}/federation/net.js`);
10
- const { applyMessage, MAX_FILES } = require(`${__hooks}/federation/messages.js`);
10
+ const { applyFiles, applyMessage, MAX_FILES } = require(`${__hooks}/federation/messages.js`);
11
11
  const { setDown } = require(`${__hooks}/federation/rooms.js`);
12
12
  const { isLost } = require(`${__hooks}/lib/worker.js`);
13
13
 
@@ -226,7 +226,10 @@ function download(peer, path, max) {
226
226
  */
227
227
  function fetchMessage(app, peer, payload) {
228
228
  const ev = payload.event || {};
229
- const listed = (Array.isArray(ev.message?.files) ? ev.message.files : []).slice(0, MAX_FILES);
229
+ // A message's, or (a `files` event) a message's new attachments.
230
+ const refiled = ev.type === "files";
231
+ const src = refiled ? ev.files : ev.message?.files;
232
+ const listed = (Array.isArray(src) ? src : []).slice(0, MAX_FILES);
230
233
  /** @type {string[]} */
231
234
  const temps = [];
232
235
  try {
@@ -245,7 +248,8 @@ function fetchMessage(app, peer, payload) {
245
248
  uploads.push(up);
246
249
  }
247
250
  app.runInTransaction((tx) => {
248
- applyMessage(tx, peer, ev, uploads);
251
+ if (refiled) applyFiles(tx, peer, ev, uploads);
252
+ else applyMessage(tx, peer, ev, uploads);
249
253
  });
250
254
  } finally {
251
255
  for (const t of temps) {
@@ -270,6 +270,39 @@ function setMessageFiles(app, rec, rows, sources = {}, later = false) {
270
270
  /** A custom key (neither stored nor sent): the `files` rows a message's save is to link (setMessageFiles `later`). */
271
271
  const PENDING = "@link";
272
272
 
273
+ /**
274
+ * A custom key (neither stored nor sent): this save replaces the message's attachments (replaceMessageFiles), which
275
+ * nothing else may change (§17.1). Never taken from a request (lib/messages.js beforeMessageUpdateRequest).
276
+ */
277
+ const REPLACING = "@replace_files";
278
+
279
+ /**
280
+ * Replace the attachments of a message about to be saved, the server's doing only: a Telegram message's media
281
+ * replaced (§26.4), or a linked instance passing that on (§33.6). `rows` in order, those it keeps among them; what it
282
+ * no longer names is unlinked once saved (main.pb.js), and the new ones linked in the save. A kept file stays from
283
+ * the collection it was attached from.
284
+ * @param {core.App} app
285
+ * @param {core.Record} rec
286
+ * @param {core.Record[]} rows
287
+ */
288
+ function replaceMessageFiles(app, rec, rows) {
289
+ const was = /** @type {Record<string, string>} */ (parse(rec.original().getString("file_sources")) || {});
290
+ /** @type {Record<string, string>} */
291
+ const sources = {};
292
+ for (const row of rows) {
293
+ const name = row.getString("file");
294
+ if (was[name]) sources[name] = was[name];
295
+ }
296
+ setMessageFiles(app, rec, rows, sources, true);
297
+ rec.set(REPLACING, true);
298
+ }
299
+
300
+ /**
301
+ * Is this save of a message a replaceMessageFiles?
302
+ * @param {core.Record} rec
303
+ */
304
+ const replacing = (rec) => rec.get(REPLACING) === true;
305
+
273
306
  /**
274
307
  * Link what setMessageFiles left to the save of `rec` (main.pb.js, in the save's transaction).
275
308
  * @param {core.App} app
@@ -306,6 +339,9 @@ function attachUploads(app, rec, uploads) {
306
339
  module.exports = {
307
340
  discard,
308
341
  linkPending,
342
+ REPLACING,
343
+ replaceMessageFiles,
344
+ replacing,
309
345
  MAX_FILES,
310
346
  isImage,
311
347
  isVideo,
@@ -94,6 +94,19 @@ function drop(app, id) {
94
94
  app.db().newQuery("DELETE FROM media WHERE message = {:id} OR source = {:id}").bind({ id }).execute();
95
95
  }
96
96
 
97
+ /**
98
+ * A message's attachments replaced (lib/files.js replaceMessageFiles): its rows and its forwards' are made again.
99
+ * @param {core.App} app
100
+ * @param {core.Record} rec
101
+ */
102
+ function refile(app, rec) {
103
+ drop(app, rec.id);
104
+ add(app, rec);
105
+ for (const fwd of app.findRecordsByFilter("messages", "forward_of = {:id} && deleted = false", "", 0, 0, { id: rec.id })) {
106
+ if (fwd) add(app, fwd);
107
+ }
108
+ }
109
+
97
110
  // ---------------------------------------------------------------- the grid's page
98
111
 
99
112
  /**
@@ -594,4 +607,4 @@ function tick(e) {
594
607
  return e.noContent(204);
595
608
  }
596
609
 
597
- module.exports = { add, drop, list, run, wake, tick };
610
+ module.exports = { add, drop, refile, list, run, wake, tick };
@@ -365,18 +365,25 @@ function beforeMessageUpdate(e) {
365
365
  return;
366
366
  }
367
367
 
368
- rec.set("file_names", orig.get("file_names")); // never changed by an edit
369
- rec.set("file_sources", orig.get("file_sources")); // nor this (§31)
370
- // Only the create hook and the media worker set these; the worker's may be newer than the loaded record's.
371
- rec.set("file_dims", e.app.findRecordById("messages", rec.id).get("file_dims"));
368
+ // A replaceMessageFiles (the server's: a Telegram media edit, §26.4, or a linked instance's, §33.6) set them all.
369
+ const refiled = require(`${__hooks}/lib/files.js`).replacing(rec);
370
+ if (!refiled) {
371
+ rec.set("file_names", orig.get("file_names")); // never changed by an edit
372
+ rec.set("file_sources", orig.get("file_sources")); // nor this (§31)
373
+ // Only the create hook and the media worker set these; the worker's may be newer than the loaded record's.
374
+ rec.set("file_dims", e.app.findRecordById("messages", rec.id).get("file_dims"));
375
+ }
372
376
  // Reactions only change through POST /api/chat/reactions (§20.2). Any other save (an edit) keeps the ones stored
373
377
  // now, not the ones loaded with the record: a reaction added meanwhile would be lost. (Edits save in a transaction.)
374
378
  if (rec.getString("reactions") === orig.getString("reactions")) {
375
379
  rec.set("reactions", e.app.findRecordById("messages", rec.id).get("reactions"));
376
380
  }
377
- // Attachments are immutable after sending (backs up the update rule, as above).
381
+ // Attachments are immutable after sending (backs up the update rule, as above), but for the server's own replacing.
378
382
  const files = fileNames(rec);
379
- if (files.join("/") !== orig.getStringSlice("files").join("/")) throw fieldError("files", "Attachments can't be changed.");
383
+ const changed = files.join("/") !== orig.getStringSlice("files").join("/");
384
+ if (changed && !refiled) throw fieldError("files", "Attachments can't be changed.");
385
+ if (changed && orig.getString("forwarded_from") !== "") throw fieldError("files", "Forwarded messages can't be edited.");
386
+ if (changed) rec.set("edited_at", new DateTime());
380
387
  assertText(rec, files.length > 0 || isForward(rec));
381
388
  if (rec.getString("text") !== orig.getString("text")) {
382
389
  rec.set("previews", []); // the worker looks at the new text's links (§28)
@@ -398,6 +405,8 @@ function beforeMessageUpdate(e) {
398
405
  */
399
406
  function beforeMessageUpdateRequest(e) {
400
407
  const rec = recordOf(e);
408
+ // Only the server replaces attachments (lib/files.js replaceMessageFiles), never a request naming its key.
409
+ rec.set(require(`${__hooks}/lib/files.js`).REPLACING, null);
401
410
  // Uploads and modifiers aren't a file field's any more (§37), so the update rule doesn't see them all: refused
402
411
  // here, not dropped.
403
412
  const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body ?? {});
@@ -427,6 +436,7 @@ function changesForwards(rec) {
427
436
  const orig = rec.original();
428
437
  return (
429
438
  rec.getString("text") !== orig.getString("text") ||
439
+ rec.getStringSlice("files").join("/") !== orig.getStringSlice("files").join("/") ||
430
440
  rec.getBool("deleted") !== orig.getBool("deleted") ||
431
441
  rec.getString("previews") !== orig.getString("previews")
432
442
  );
@@ -0,0 +1,199 @@
1
+ /// <reference path="../../types/pocketbase.d.ts" />
2
+ // Pinned messages (DESIGN.md §45): POST /api/chat/pins pins or unpins a message in its room. The pins live on the room
3
+ // (`rooms.pins`), newest first, so they reach clients with it: the room list, realtime room updates and the room cache
4
+ // need nothing new. A pin keeps the start of its message's text, so the pin bar shows it without loading the message;
5
+ // the messages hooks keep that up to date (edits) and drop the pin when the message goes (deletes).
6
+
7
+ const { accessOf, sees, viewerOf } = require(`${__hooks}/lib/access.js`);
8
+ const { isService } = require(`${__hooks}/lib/messages.js`);
9
+ const { isDm } = require(`${__hooks}/lib/rooms.js`);
10
+
11
+ /** Most pins a room keeps. */
12
+ const MAX_PINS = 20;
13
+ /** How much of a message's text a pin keeps (characters). */
14
+ const PIN_TEXT = 200;
15
+
16
+ /**
17
+ * @typedef {{ message: string, by: string, at: string, text: string }} Pin
18
+ */
19
+
20
+ /**
21
+ * @param {string} field
22
+ * @param {string} message
23
+ */
24
+ const badRequest = (field, message) =>
25
+ new BadRequestError("Failed to update the pin.", { [field]: new ValidationError("validation_invalid_value", message) });
26
+
27
+ /**
28
+ * A room's pins, newest first. Anything malformed is dropped.
29
+ * @param {core.Record} room
30
+ * @returns {Pin[]}
31
+ */
32
+ function pinsOf(room) {
33
+ /** @type {unknown} */
34
+ let raw;
35
+ try {
36
+ raw = JSON.parse(room.getString("pins") || "[]");
37
+ } catch {
38
+ return [];
39
+ }
40
+ if (!Array.isArray(raw)) return [];
41
+ return raw
42
+ .filter((p) => p && typeof p.message === "string" && p.message)
43
+ .map((p) => ({
44
+ message: p.message,
45
+ by: typeof p.by === "string" ? p.by : "",
46
+ at: typeof p.at === "string" ? p.at : "",
47
+ text: typeof p.text === "string" ? p.text : "",
48
+ }));
49
+ }
50
+
51
+ /**
52
+ * The start of a message's text, on one line, as a pin keeps it.
53
+ * @param {string} text
54
+ */
55
+ function pinText(text) {
56
+ const line = text.replace(/\s+/g, " ").trim();
57
+ if (line.length <= PIN_TEXT) return line;
58
+ // Not between the two halves of an emoji (a surrogate pair), which would be stored as "�".
59
+ let end = PIN_TEXT - 1;
60
+ const last = line.charCodeAt(end - 1);
61
+ if (last >= 0xd800 && last <= 0xdbff) end--;
62
+ return `${line.slice(0, end)}…`;
63
+ }
64
+
65
+ /**
66
+ * May `user` pin and unpin messages in `room`? Either member of a DM; in any other room its creator or a moderator
67
+ * (as for its access and archiving, §36). Never in an archived room: it is read-only.
68
+ * @param {core.Record} room
69
+ * @param {core.Record | null | undefined} user
70
+ */
71
+ function canPin(room, user) {
72
+ if (!user || room.getBool("archived")) return false;
73
+ if (isDm(room)) return room.getStringSlice("members").includes(user.id);
74
+ const { canManage } = require(`${__hooks}/lib/moderation.js`);
75
+ return canManage(room, user);
76
+ }
77
+
78
+ /**
79
+ * `list` with `message` pinned (`on`, first, `text` its text) or unpinned; null when that changes nothing.
80
+ * @param {Pin[]} list
81
+ * @param {string} message
82
+ * @param {boolean} on
83
+ * @param {{ by: string, at: string, text: string }} pin
84
+ * @returns {Pin[] | null}
85
+ */
86
+ function setPin(list, message, on, pin) {
87
+ const has = list.some((p) => p.message === message);
88
+ if (has === on) return null;
89
+ if (!on) return list.filter((p) => p.message !== message);
90
+ return [{ message, ...pin }, ...list];
91
+ }
92
+
93
+ /**
94
+ * POST /api/chat/pins { message, pin } → the room, as GET /api/collections/rooms/records/:id answers it (the same
95
+ * ?expand and ?fields apply): `message` is pinned in its room (`pin: true`) or not (`pin: false`). Idempotent, so a
96
+ * retry or a double click can't flip it back. Only on messages the caller can see, that aren't deleted, in rooms they
97
+ * may pin in (canPin).
98
+ * @param {core.RequestEvent} e
99
+ */
100
+ function pin(e) {
101
+ const me = e.auth;
102
+ if (!me) throw new UnauthorizedError("The request requires a logged-in user.");
103
+ const info = e.requestInfo();
104
+ const body = /** @type {Record<string, unknown>} */ (info.body);
105
+ const id = typeof body.message === "string" ? body.message : "";
106
+ const on = body.pin;
107
+ if (typeof on !== "boolean") throw badRequest("pin", "Must be true or false.");
108
+
109
+ // Someone else's DM gets the same answer as a message that doesn't exist.
110
+ const notFound = () => new NotFoundError("The message doesn't exist.");
111
+ let msg;
112
+ try {
113
+ msg = e.app.findRecordById("messages", id);
114
+ } catch {
115
+ throw notFound();
116
+ }
117
+ /** @type {core.Record} */
118
+ let room;
119
+ try {
120
+ room = e.app.findRecordById("rooms", msg.getString("room"));
121
+ } catch {
122
+ throw notFound();
123
+ }
124
+ if (!sees(viewerOf(me), accessOf(room))) throw notFound();
125
+ if (room.getBool("archived")) throw badRequest("message", "This room is archived and read-only.");
126
+ if (!canPin(room, me)) throw new ForbiddenError("Only the room's creator or a moderator can pin messages here.");
127
+ if (on && isService(msg)) throw badRequest("message", "Service messages can't be pinned.");
128
+
129
+ // Read and write in one transaction: two people pinning at once both count. (Errors are thrown after it, so they
130
+ // keep their status.)
131
+ let problem = "";
132
+ e.app.runInTransaction((tx) => {
133
+ const m = tx.findRecordById("messages", id);
134
+ const r = tx.findRecordById("rooms", m.getString("room"));
135
+ room = r;
136
+ if (on && m.getBool("deleted")) problem = "That message was deleted.";
137
+ if (problem) return;
138
+ const list = pinsOf(r);
139
+ if (on && list.length >= MAX_PINS && !list.some((p) => p.message === id)) {
140
+ problem = `A room can have at most ${MAX_PINS} pinned messages. Unpin one first.`;
141
+ return;
142
+ }
143
+ const next = setPin(list, id, on, { by: me.id, at: new Date().toISOString(), text: pinText(m.getString("text")) });
144
+ if (!next) return;
145
+ r.set("pins", next);
146
+ tx.save(r);
147
+ });
148
+ if (problem) throw badRequest("message", problem);
149
+ $apis.enrichRecord(e, room);
150
+ return e.json(200, room);
151
+ }
152
+
153
+ /**
154
+ * After a message was saved (messages onRecordUpdate): a deleted one is unpinned, and an edited one's pin shows its
155
+ * new text. Nothing to do for a message that isn't pinned (most saves: one read of its room).
156
+ * @param {core.App} app
157
+ * @param {core.Record} rec
158
+ */
159
+ function messageChanged(app, rec) {
160
+ const deleted = rec.getBool("deleted");
161
+ const edited = rec.getString("text") !== rec.original().getString("text");
162
+ if (!deleted && !edited) return;
163
+ dropOrRefresh(app, rec.getString("room"), rec.id, deleted ? null : pinText(rec.getString("text")));
164
+ }
165
+
166
+ /**
167
+ * A message deleted for good (messages onRecordDelete): unpinned.
168
+ * @param {core.App} app
169
+ * @param {core.Record} rec
170
+ */
171
+ function messageDeleted(app, rec) {
172
+ dropOrRefresh(app, rec.getString("room"), rec.id, null);
173
+ }
174
+
175
+ /**
176
+ * Unpin `message` from its room (`text` null), or give its pin `text`.
177
+ * @param {core.App} app
178
+ * @param {string} roomId
179
+ * @param {string} message
180
+ * @param {string | null} text
181
+ */
182
+ function dropOrRefresh(app, roomId, message, text) {
183
+ let room;
184
+ try {
185
+ room = app.findRecordById("rooms", roomId);
186
+ } catch {
187
+ return; // the room is going too
188
+ }
189
+ const list = pinsOf(room);
190
+ const at = list.findIndex((p) => p.message === message);
191
+ if (at < 0) return;
192
+ const pinned = list[at];
193
+ if (text !== null && pinned && pinned.text === text) return;
194
+ const next = text === null ? list.filter((_, i) => i !== at) : list.map((p, i) => (i === at ? { ...p, text } : p));
195
+ room.set("pins", next);
196
+ app.save(room);
197
+ }
198
+
199
+ module.exports = { MAX_PINS, PIN_TEXT, canPin, messageChanged, messageDeleted, pin, pinText, pinsOf, setPin };
@@ -107,6 +107,8 @@ function beforeRoomCreateRequest(e) {
107
107
  for (const f of DM_FIELDS.slice(1)) {
108
108
  if (dmValue(rec, f) !== "") throw fieldError(f, "This field can't be set.");
109
109
  }
110
+ // Only POST /api/chat/pins pins (§45).
111
+ if (!["", "null", "[]"].includes(rec.getString("pins"))) throw fieldError("pins", "This field can't be set.");
110
112
  }
111
113
 
112
114
  /**
@@ -120,6 +122,8 @@ function beforeRoomUpdateRequest(e) {
120
122
  if (f === "members" && !isDm(orig)) continue;
121
123
  if (dmValue(rec, f) !== dmValue(orig, f)) throw fieldError(f, "This field can't be changed.");
122
124
  }
125
+ // Only POST /api/chat/pins pins (§45).
126
+ if (rec.getString("pins") !== orig.getString("pins")) throw fieldError("pins", "This field can't be changed.");
123
127
  }
124
128
 
125
129
  /**
@@ -37,6 +37,7 @@ routerAdd("GET", "/api/{path...}", () => {
37
37
  routerAdd("POST", "/api/previews/tick", (e) => require(`${__hooks}/lib/previews.js`).tick(e), $apis.requireSuperuserAuth());
38
38
  routerAdd("POST", "/api/chat/dms", (e) => require(`${__hooks}/lib/dms.js`).openDm(e), $apis.requireAuth("users"));
39
39
  routerAdd("POST", "/api/chat/reactions", (e) => require(`${__hooks}/lib/reactions.js`).react(e), $apis.requireAuth("users"));
40
+ routerAdd("POST", "/api/chat/pins", (e) => require(`${__hooks}/lib/pins.js`).pin(e), $apis.requireAuth("users"));
40
41
  routerAdd("POST", "/api/chat/delete", (e) => require(`${__hooks}/lib/bulk.js`).deleteMessages(e), $apis.requireAuth("users"));
41
42
  routerAdd("POST", "/api/chat/ban", (e) => require(`${__hooks}/lib/moderation.js`).ban(e), $apis.requireAuth("users"));
42
43
  routerAdd("POST", "/api/chat/forward", (e) => require(`${__hooks}/lib/bulk.js`).forward(e), $apis.requireAuth("users"));
@@ -249,6 +250,8 @@ onRecordDelete((e) => {
249
250
  const names = e.record ? files.namedBy(e.app, "messages", e.record.id) : [];
250
251
  e.next();
251
252
  files.unlink(e.app, names);
253
+ // Gone for good: unpinned (§45).
254
+ if (e.record) require(`${__hooks}/lib/pins.js`).messageDeleted(e.app, e.record);
252
255
  }, "messages");
253
256
 
254
257
  onRecordCreate((e) => {
@@ -335,20 +338,30 @@ onRecordUpdate((e) => {
335
338
  const touch = messages.changesForwards(rec);
336
339
  const edited = rec.getString("text") !== rec.original().getString("text");
337
340
  const deleted = rec.getBool("deleted") && !rec.original().getBool("deleted");
341
+ const shared = require(`${__hooks}/lib/files.js`);
342
+ // Its attachments replaced (lib/files.js replaceMessageFiles: a Telegram media edit, §26.4, a linked instance's, §33.6).
343
+ const refiled = !deleted && rec.getStringSlice("files").join("/") !== rec.original().getStringSlice("files").join("/");
338
344
  // As stored, not as loaded: another delete of it may have been committed since (QA BUG-223).
339
- const files = deleted ? require(`${__hooks}/lib/files.js`).namedBy(e.app, "messages", rec.id) : [];
345
+ const files = deleted || refiled ? shared.namedBy(e.app, "messages", rec.id) : [];
340
346
  const tg = features.telegram();
341
347
  const change = tg ? tg.outbound.changeOf(e.app, rec) : "";
348
+ if (refiled) shared.linkPending(e.app, rec); // the new ones, in this save's transaction (the caller's)
342
349
  e.next();
350
+ rec.set(shared.REPLACING, null);
343
351
  // Saved: mentions, replies and reactions told or taken back (§41).
344
352
  inbox.messageChanged(e.app, rec, told);
345
- if (tg) tg.outbound.queueUpdate(e.app, rec, change);
353
+ if (tg) tg.outbound.queueUpdate(e.app, rec, change, files);
346
354
  // Saved: a deleted message's media leave the grid, its forwards' too (§30.1), and its files are named once less (§37).
347
355
  if (deleted) require(`${__hooks}/lib/media.js`).drop(e.app, rec.id);
348
- if (deleted) require(`${__hooks}/lib/files.js`).unlink(e.app, files);
356
+ if (deleted) shared.unlink(e.app, files);
357
+ // Saved with other attachments: the old ones are named once less, and the grid shows the new ones, its forwards' too.
358
+ if (refiled) shared.unlink(e.app, files);
359
+ if (refiled) require(`${__hooks}/lib/media.js`).refile(e.app, rec);
349
360
  // Saved: forwards of it tell their readers (§21.3).
350
361
  if (touch) messages.touchForwards(e.app, rec);
351
362
  if (edited) require(`${__hooks}/lib/previews.js`).queue(e.app, rec);
363
+ // Saved: a deleted message is unpinned, an edited one's pin shows its new text (§45).
364
+ if (edited || deleted) require(`${__hooks}/lib/pins.js`).messageChanged(e.app, rec);
352
365
  if (fed && was) fed.messages.messageChanged(e.app, rec, was);
353
366
  }, "messages");
354
367