chirkle 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. package/README.md +21 -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 +2 -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-7VYWTXX4.js +3 -0
  25. package/pb_public/assets/app-7VYWTXX4.js.br +0 -0
  26. package/pb_public/assets/app-7VYWTXX4.js.gz +0 -0
  27. package/pb_public/assets/app-7VYWTXX4.js.map +7 -0
  28. package/pb_public/assets/app-LDOYFRVQ.css +2 -0
  29. package/pb_public/assets/app-LDOYFRVQ.css.br +0 -0
  30. package/pb_public/assets/app-LDOYFRVQ.css.gz +0 -0
  31. package/pb_public/assets/app-LDOYFRVQ.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-6NQUEU3U.js +2 -0
  61. package/pb_public/assets/pins-6NQUEU3U.js.br +0 -0
  62. package/pb_public/assets/pins-6NQUEU3U.js.gz +0 -0
  63. package/pb_public/assets/pins-6NQUEU3U.js.map +7 -0
  64. package/pb_public/assets/pins-6ZVYPBB5.css +2 -0
  65. package/pb_public/assets/pins-6ZVYPBB5.css.br +0 -0
  66. package/pb_public/assets/pins-6ZVYPBB5.css.gz +0 -0
  67. package/pb_public/assets/pins-6ZVYPBB5.css.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/assets/search-DRQHBOXE.js +2 -0
  75. package/pb_public/assets/search-DRQHBOXE.js.br +0 -0
  76. package/pb_public/assets/search-DRQHBOXE.js.gz +0 -0
  77. package/pb_public/assets/search-DRQHBOXE.js.map +7 -0
  78. package/pb_public/assets/search-QYHX6XDT.css +2 -0
  79. package/pb_public/assets/search-QYHX6XDT.css.br +0 -0
  80. package/pb_public/assets/search-QYHX6XDT.css.gz +0 -0
  81. package/pb_public/assets/search-QYHX6XDT.css.map +7 -0
  82. package/pb_public/index.html +6 -6
  83. package/pb_public/assets/access-KVSI7EFH.js.br +0 -0
  84. package/pb_public/assets/access-KVSI7EFH.js.gz +0 -0
  85. package/pb_public/assets/app-5JOOV6JX.js +0 -3
  86. package/pb_public/assets/app-5JOOV6JX.js.br +0 -0
  87. package/pb_public/assets/app-5JOOV6JX.js.gz +0 -0
  88. package/pb_public/assets/app-5JOOV6JX.js.map +0 -7
  89. package/pb_public/assets/app-7OMYYLCI.css +0 -2
  90. package/pb_public/assets/app-7OMYYLCI.css.br +0 -0
  91. package/pb_public/assets/app-7OMYYLCI.css.gz +0 -0
  92. package/pb_public/assets/app-7OMYYLCI.css.map +0 -7
  93. package/pb_public/assets/chunk-5PKDEWJS.js +0 -2
  94. package/pb_public/assets/chunk-5PKDEWJS.js.br +0 -0
  95. package/pb_public/assets/chunk-5PKDEWJS.js.gz +0 -0
  96. package/pb_public/assets/chunk-5PKDEWJS.js.map +0 -7
  97. package/pb_public/assets/chunk-EO3AMXJN.js.br +0 -0
  98. package/pb_public/assets/chunk-EO3AMXJN.js.gz +0 -0
  99. package/pb_public/assets/chunk-LDZPNZ2E.js.br +0 -0
  100. package/pb_public/assets/chunk-LDZPNZ2E.js.gz +0 -0
  101. package/pb_public/assets/chunk-Y5MCBN66.js +0 -2
  102. package/pb_public/assets/chunk-Y5MCBN66.js.br +0 -0
  103. package/pb_public/assets/chunk-Y5MCBN66.js.gz +0 -0
  104. package/pb_public/assets/chunk-Y5MCBN66.js.map +0 -7
  105. package/pb_public/assets/emoji-picker-W27IJER2.js.br +0 -0
  106. package/pb_public/assets/forward-5TJEYGEV.js +0 -2
  107. package/pb_public/assets/forward-5TJEYGEV.js.br +0 -0
  108. package/pb_public/assets/forward-5TJEYGEV.js.gz +0 -0
  109. package/pb_public/assets/forward-5TJEYGEV.js.map +0 -7
  110. package/pb_public/assets/invite-6BCBF4KV.js.br +0 -0
  111. package/pb_public/assets/invite-6BCBF4KV.js.gz +0 -0
  112. package/pb_public/assets/login-FZY6GOMF.js.br +0 -0
  113. package/pb_public/assets/login-FZY6GOMF.js.gz +0 -0
  114. package/pb_public/assets/profile-7KMXLX5U.js.br +0 -0
  115. package/pb_public/assets/profile-7KMXLX5U.js.gz +0 -0
  116. package/pb_public/assets/rooms-forms-IADHTHBZ.js.br +0 -0
  117. package/pb_public/assets/rooms-forms-IADHTHBZ.js.gz +0 -0
  118. package/pb_public/assets/search-HOPAWIMQ.js +0 -2
  119. package/pb_public/assets/search-HOPAWIMQ.js.br +0 -0
  120. package/pb_public/assets/search-HOPAWIMQ.js.gz +0 -0
  121. package/pb_public/assets/search-HOPAWIMQ.js.map +0 -7
  122. /package/pb_public/assets/{access-KVSI7EFH.js.map → access-23A7N3OD.js.map} +0 -0
  123. /package/pb_public/assets/{chunk-LDZPNZ2E.js.map → chunk-SM542ZXL.js.map} +0 -0
  124. /package/pb_public/assets/{chunk-EO3AMXJN.js.map → chunk-WDXT4S4J.js.map} +0 -0
  125. /package/pb_public/assets/{invite-6BCBF4KV.js.map → invite-VGT2DI2L.js.map} +0 -0
  126. /package/pb_public/assets/{login-FZY6GOMF.js.map → login-TN6R7N2U.js.map} +0 -0
  127. /package/pb_public/assets/{profile-7KMXLX5U.js.map → profile-NQ6QCQIB.js.map} +0 -0
  128. /package/pb_public/assets/{rooms-forms-IADHTHBZ.js.map → rooms-forms-NYMPXVUQ.js.map} +0 -0
@@ -78,20 +78,24 @@ function quoteLines(msg, known) {
78
78
  /**
79
79
  * A Telegram message's text (its caption, or a rich message's blocks as text), its files (that can be brought over),
80
80
  * and lines for what can't be: files over the download limit, and things that aren't files (a location, a poll…).
81
+ * `uids`: the file_unique_ids of all its files, brought over or not, which tell a media edit from a caption's.
81
82
  * @param {any} msg
82
- * @returns {{ text: string, files: { id: string, name: string, size: number }[], notes: string[] }}
83
+ * @returns {{ text: string, files: { id: string, name: string, size: number }[], notes: string[], uids: string[] }}
83
84
  */
84
85
  function partsOf(msg) {
85
86
  /** @type {{ id: string, name: string, size: number }[]} */
86
87
  const files = [];
87
88
  /** @type {string[]} */
88
89
  const notes = [];
90
+ /** @type {string[]} */
91
+ const uids = [];
89
92
  const n = msg.message_id;
90
93
  /**
91
94
  * @param {any} f
92
95
  * @param {string} name
93
96
  */
94
97
  const add = (f, name) => {
98
+ uids.push(String(f.file_unique_id || f.file_id));
95
99
  if (f.file_size && f.file_size > MAX_FILE) notes.push(`[${name}, ${mb(f.file_size)}: too large to bring over from Telegram]`);
96
100
  else files.push({ id: f.file_id, name, size: f.file_size || 0 });
97
101
  };
@@ -118,7 +122,7 @@ function partsOf(msg) {
118
122
  if (msg.dice) notes.push(`[${msg.dice.emoji} ${msg.dice.value}]`);
119
123
  // A rich message (Bot API 10.1) has neither text nor caption: without this it was taken for a service message.
120
124
  const text = msg.text || msg.caption || (msg.rich_message ? richText(msg.rich_message, n, add, notes) : "");
121
- return { text, files, notes };
125
+ return { text, files, notes, uids };
122
126
  }
123
127
 
124
128
  /**
@@ -227,8 +231,10 @@ function forgetStale(tx, chatId, tgId) {
227
231
  * @param {number} tgId
228
232
  * @param {"text" | "media"} kind
229
233
  * @param {number} part
234
+ * @param {{ files: string[], ids: string[] }} [media] the first part's: the attachments it brought (stored names), and
235
+ * the file_unique_ids of all its files (partsOf `uids`), which a media edit goes by (editOver)
230
236
  */
231
- function rememberIn(tx, messageId, chatId, tgId, kind, part) {
237
+ function rememberIn(tx, messageId, chatId, tgId, kind, part, media) {
232
238
  const row = new Record(tx.findCollectionByNameOrId("tg_messages"));
233
239
  row.set("message", messageId);
234
240
  row.set("chat_id", chatId);
@@ -236,9 +242,28 @@ function rememberIn(tx, messageId, chatId, tgId, kind, part) {
236
242
  row.set("direction", "in");
237
243
  row.set("kind", kind);
238
244
  row.set("part", part);
245
+ if (media) {
246
+ row.set("files", media.files);
247
+ row.set("file_ids", media.ids);
248
+ }
239
249
  tx.save(row);
240
250
  }
241
251
 
252
+ /**
253
+ * A JSON list of strings a tg_messages row keeps (`files`, `file_ids`), or null for a row from before it kept them.
254
+ * @param {core.Record} row
255
+ * @param {string} field
256
+ * @returns {string[] | null}
257
+ */
258
+ function listOf(row, field) {
259
+ try {
260
+ const list = JSON.parse(row.getString(field) || "null");
261
+ return Array.isArray(list) ? list.map(String) : null;
262
+ } catch {
263
+ return null;
264
+ }
265
+ }
266
+
242
267
  /**
243
268
  * A further part of a long Telegram message: its text, under the same stand-in, after the first.
244
269
  * @param {core.App} tx
@@ -308,13 +333,17 @@ function bringOver(app, link, room, msgs, mode = "live") {
308
333
  if (!notes.length && !parts.some((p) => p.files.length) && !parts.some((p) => p.text.trim())) return;
309
334
  /** @type {any[]} */
310
335
  const files = [];
311
- for (const f of parts.flatMap((p) => p.files)) {
336
+ /** Which of `msgs` each of `files` came from. */
337
+ /** @type {number[]} */
338
+ const owners = [];
339
+ for (const [f, owner] of parts.flatMap((p, i) => p.files.map((f) => /** @type {const} */ ([f, i])))) {
312
340
  if (files.length >= MAX_FILES) {
313
341
  notes.push(`[${f.name}: more files than a message holds]`);
314
342
  continue;
315
343
  }
316
344
  try {
317
345
  files.push(download(f.id, f.name, f.size));
346
+ owners.push(owner);
318
347
  } catch (err) {
319
348
  const later = mode !== "last" && !!asTelegram(err)?.transient;
320
349
  app.logger().warn("telegram: download", "chat", chatId, "message", first.message_id, "later", later, "error", String(err));
@@ -351,9 +380,11 @@ function bringOver(app, link, room, msgs, mode = "live") {
351
380
  if (files.length) require(`${__hooks}/lib/files.js`).attachUploads(tx, rec, files);
352
381
  if (withReply && known && reply) rec.set("reply_to", reply.id);
353
382
  tx.save(rec);
383
+ const names = rec.getStringSlice("files"); // in the order of `files`
354
384
  msgs.forEach((m, i) => {
355
385
  forgetStale(tx, chatId, m.message_id);
356
- rememberIn(tx, rec.id, chatId, m.message_id, i === 0 ? "text" : "media", 0);
386
+ const media = { files: names.filter((_, k) => owners[k] === i), ids: parts[i].uids };
387
+ rememberIn(tx, rec.id, chatId, m.message_id, i === 0 ? "text" : "media", 0, media);
357
388
  });
358
389
  for (let i = 1; i < pieces.length; i++) {
359
390
  const part = savePart(tx, room.id, author.id, pieces[i], ids[i]);
@@ -369,7 +400,107 @@ function bringOver(app, link, room, msgs, mode = "live") {
369
400
  }
370
401
 
371
402
  /**
372
- * A Telegram edit: the chat message gets the new text.
403
+ * Which of a chat message's attachments a Telegram message brought: where they start in its `files`, and their stored
404
+ * names; null when that can't be told. `album`: the message's Telegram messages (part 0), by tg_message_id. A row
405
+ * from before rows kept their files says nothing: a lone Telegram message brought them all, and an album's items
406
+ * one each when there are as many (each item is one photo, video or file).
407
+ * @param {core.Record} rec
408
+ * @param {core.Record} row the Telegram message's
409
+ * @param {core.Record[]} album
410
+ * @returns {{ pos: number, names: string[] } | null}
411
+ */
412
+ function heldBy(rec, row, album) {
413
+ const files = rec.getStringSlice("files");
414
+ const i = album.findIndex((r) => r.id === row.id);
415
+ const lists = album.map((r) => listOf(r, "files"));
416
+ const own = lists[i];
417
+ if (own) {
418
+ if (own.length) {
419
+ const pos = files.indexOf(own[0]);
420
+ return pos >= 0 && own.every((n, k) => files[pos + k] === n) ? { pos, names: own } : null;
421
+ }
422
+ // It brought none (a file too large then): the new ones go after those of the items before it.
423
+ const before = lists.slice(0, i);
424
+ if (before.some((l) => !l)) return null;
425
+ return { pos: before.reduce((n, l) => n + (l?.length || 0), 0), names: [] };
426
+ }
427
+ if (album.length <= 1) return { pos: 0, names: files };
428
+ return files.length === album.length && i >= 0 ? { pos: i, names: [files[i]] } : null;
429
+ }
430
+
431
+ /**
432
+ * Stored size of a shared file (§37), -1 when unknown.
433
+ * @param {core.App} app
434
+ * @param {filesystem.System} fsys
435
+ * @param {string} name
436
+ */
437
+ function storedSize(app, fsys, name) {
438
+ const shared = require(`${__hooks}/lib/files.js`);
439
+ const row = shared.byName(app, name);
440
+ if (!row) return -1;
441
+ try {
442
+ return fsys.attributes(shared.keyOf(row)).size;
443
+ } catch {
444
+ return -1;
445
+ }
446
+ }
447
+
448
+ /**
449
+ * Has the Telegram message's media been replaced (editMessageMedia), or is it only its caption that changed? By the
450
+ * file_unique_ids it brought; a row from before it kept them, by the files' sizes, when Telegram gives them.
451
+ * @param {core.App} app
452
+ * @param {core.Record} row
453
+ * @param {ReturnType<typeof partsOf>} parts
454
+ * @param {string[]} held
455
+ */
456
+ function mediaReplaced(app, row, parts, held) {
457
+ const ids = listOf(row, "file_ids");
458
+ if (ids) return ids.join("\n") !== parts.uids.join("\n");
459
+ if (parts.files.length !== held.length) return parts.files.length > 0;
460
+ const fsys = app.newFilesystem();
461
+ try {
462
+ return parts.files.some((f, k) => {
463
+ const size = storedSize(app, fsys, held[k]);
464
+ return f.size > 0 && size >= 0 && f.size !== size;
465
+ });
466
+ } finally {
467
+ fsys.close();
468
+ }
469
+ }
470
+
471
+ /**
472
+ * A Telegram media edit's new files, downloaded (before any transaction: a download is slow), with what replaces what.
473
+ * Null when its media wasn't replaced, can't be placed, or its new files don't come for now (logged): the message
474
+ * then keeps the ones it has, and only its text changes.
475
+ * @param {core.App} app
476
+ * @param {string} chatId
477
+ * @param {any} msg
478
+ * @param {core.Record} rec
479
+ * @param {core.Record} row the Telegram message's
480
+ * @param {ReturnType<typeof partsOf>} parts
481
+ */
482
+ function newMedia(app, chatId, msg, rec, row, parts) {
483
+ const album = app
484
+ .findRecordsByFilter("tg_messages", "message = {:m} && direction = 'in' && part = 0", "tg_message_id", 0, 0, { m: rec.id })
485
+ .filter((r) => !!r);
486
+ const held = heldBy(rec, row, album);
487
+ if (!held || !mediaReplaced(app, row, parts, held.names)) return null;
488
+ const room = MAX_FILES - (rec.getStringSlice("files").length - held.names.length);
489
+ /** @type {any[]} */
490
+ const uploads = [];
491
+ try {
492
+ for (const f of parts.files.slice(0, Math.max(0, room))) uploads.push(download(f.id, f.name, f.size));
493
+ } catch (err) {
494
+ app.logger().warn("telegram: media edit download", "chat", chatId, "message", msg.message_id, "error", String(err));
495
+ return null;
496
+ }
497
+ return { ...held, uploads, ids: parts.uids };
498
+ }
499
+
500
+ /**
501
+ * A Telegram edit: the chat message gets the new text, and the new media when they were replaced (§26.4): only those
502
+ * the Telegram message brought, an album's item its own. An album's item but its first, which holds no text, changes
503
+ * the text only when it has some (its caption added).
373
504
  * @param {core.App} app
374
505
  * @param {any} msg
375
506
  */
@@ -379,14 +510,20 @@ function editOver(app, msg) {
379
510
  const rec = rows[0]?.getInt("part") === 0 ? findMessage(app, rows[0].getString("message")) : null;
380
511
  if (!rec) return editWaiting(app, chatId, msg);
381
512
  if (rec.getBool("deleted") || rec.getString("forwarded_from")) return;
513
+ const item = rows[0].getString("kind") === "media";
382
514
  const quoted = quoteLines(msg, !!rec.getString("reply_to"));
383
- const { text, notes } = partsOf(msg);
515
+ const parts = partsOf(msg);
516
+ const { text, notes } = parts;
517
+ const media = newMedia(app, chatId, msg, rec, rows[0], parts);
518
+ const files = media ? rec.getStringSlice("files").length - media.names.length + media.uploads.length : rec.getStringSlice("files").length;
384
519
  const lines = [forwardLine(msg), ...quoted, text, ...notes].filter(Boolean);
385
- const pieces = split(lines.join("\n"));
386
- if (!pieces[0] && !rec.getStringSlice("files").length) return;
520
+ // An item without a caption leaves the text as it is: the album's caption is its first item's.
521
+ const pieces = item && !text.trim() && !notes.length ? null : split(lines.join("\n"));
522
+ if (pieces && !pieces[0] && !files) return;
523
+ if (!pieces && !media) return;
387
524
  // The parts still in the room get the pieces in order: a shorter text deletes the parts left over, a longer one adds
388
525
  // parts (after what came since). A deleted message can't come back, so a part deleted meanwhile is passed over.
389
- const parts = /** @type {core.Record[]} */ (
526
+ const later = /** @type {core.Record[]} */ (
390
527
  rows
391
528
  .slice(1)
392
529
  .map((r) => findMessage(app, r.getString("message")))
@@ -394,16 +531,45 @@ function editOver(app, msg) {
394
531
  );
395
532
  const next = rows.length ? rows[rows.length - 1].getInt("part") + 1 : 1;
396
533
  app.runInTransaction((tx) => {
397
- [rec, ...parts].forEach((part, i) => {
398
- if (i >= pieces.length) part.set("deleted", true);
399
- else if (pieces[i] === part.getString("text")) return;
400
- else part.set("text", pieces[i]);
534
+ const fresh = findMessage(tx, rec.id);
535
+ if (!fresh || fresh.getBool("deleted")) return;
536
+ let replaced = false;
537
+ if (media) {
538
+ const shared = require(`${__hooks}/lib/files.js`);
539
+ const names = fresh.getStringSlice("files");
540
+ // Changed meanwhile (another edit of it, saved while this one downloaded): this one's media are stale.
541
+ if (media.names.every((n, k) => names[media.pos + k] === n)) {
542
+ const added = shared.fromUploads(tx, media.uploads);
543
+ const kept = shared.byNames(tx, names);
544
+ const list = [
545
+ ...names.slice(0, media.pos).map((n) => kept.get(n)),
546
+ ...added,
547
+ ...names.slice(media.pos + media.names.length).map((n) => kept.get(n)),
548
+ ].filter((r) => !!r);
549
+ shared.replaceMessageFiles(tx, fresh, /** @type {core.Record[]} */ (list));
550
+ replaced = true;
551
+ const row = tx.findRecordById("tg_messages", rows[0].id);
552
+ row.set(
553
+ "files",
554
+ added.map((/** @type {core.Record} */ r) => r.getString("file")),
555
+ );
556
+ row.set("file_ids", media.ids);
557
+ tx.save(row);
558
+ }
559
+ }
560
+ if (pieces) fresh.set("text", pieces[0]);
561
+ if (replaced || fresh.getString("text") !== fresh.original().getString("text")) tx.save(fresh);
562
+ if (!pieces) return;
563
+ later.forEach((part, i) => {
564
+ if (i + 1 >= pieces.length) part.set("deleted", true);
565
+ else if (pieces[i + 1] === part.getString("text")) return;
566
+ else part.set("text", pieces[i + 1]);
401
567
  tx.save(part);
402
568
  });
403
569
  const ids = orderedIds(pieces.length);
404
- for (let i = parts.length + 1; i < pieces.length; i++) {
570
+ for (let i = later.length + 1; i < pieces.length; i++) {
405
571
  const part = savePart(tx, rec.getString("room"), rec.getString("author"), pieces[i], ids[i]);
406
- rememberIn(tx, part.id, chatId, msg.message_id, "text", next + i - parts.length - 1);
572
+ rememberIn(tx, part.id, chatId, msg.message_id, "text", next + i - later.length - 1);
407
573
  }
408
574
  });
409
575
  }
@@ -25,12 +25,14 @@ const STREAM = { supports_streaming: true };
25
25
  * @param {string} op
26
26
  * @param {string} messageId
27
27
  * @param {string} chatId
28
+ * @param {Record<string, unknown>} [payload]
28
29
  */
29
- function enqueue(app, op, messageId, chatId) {
30
+ function enqueue(app, op, messageId, chatId, payload) {
30
31
  const row = new Record(app.findCollectionByNameOrId("tg_queue"));
31
32
  row.set("op", op);
32
33
  row.set("message", messageId);
33
34
  row.set("chat_id", chatId);
35
+ if (payload) row.set("payload", payload);
34
36
  app.save(row);
35
37
  }
36
38
 
@@ -51,11 +53,13 @@ function queueCreate(app, rec) {
51
53
  * change (§26.9).
52
54
  * @param {core.App} app
53
55
  * @param {core.Record} rec
54
- * @returns {"" | "edit" | "delete" | "react"}
56
+ * "media" when its attachments were replaced (lib/files.js replaceMessageFiles), its text edited too or not.
57
+ * @returns {"" | "edit" | "delete" | "react" | "media"}
55
58
  */
56
59
  function changeOf(app, rec) {
57
60
  const orig = rec.original();
58
61
  if (rec.getBool("deleted") && !orig.getBool("deleted")) return "delete";
62
+ if (!rec.getBool("deleted") && rec.getStringSlice("files").join("/") !== orig.getStringSlice("files").join("/")) return "media";
59
63
  if (!rec.getBool("deleted") && rec.getString("text") !== orig.getString("text")) return "edit";
60
64
  if (rec.getString("reactions") !== orig.getString("reactions")) {
61
65
  const { botReaction } = require(`${__hooks}/telegram/reactions.js`);
@@ -69,14 +73,15 @@ function changeOf(app, rec) {
69
73
  * for a group isn't queued again: it sends the message's reactions as they are when it goes.
70
74
  * @param {core.App} app
71
75
  * @param {core.Record} rec
72
- * @param {"" | "edit" | "delete" | "react"} change
76
+ * @param {"" | "edit" | "delete" | "react" | "media"} change
77
+ * @param {string[]} [was] for "media": its attachments before (stored names)
73
78
  */
74
- function queueUpdate(app, rec, change) {
79
+ function queueUpdate(app, rec, change, was = []) {
75
80
  if (!change || !rec.getString("author")) return; // a service message never went to Telegram
76
81
  for (const link of linksOfRoom(app, rec.getString("room"))) {
77
82
  const chatId = link.getString("chat_id");
78
83
  if (change === "react" && waiting(app, rec.id, chatId)) continue;
79
- enqueue(app, change, rec.id, chatId);
84
+ enqueue(app, change, rec.id, chatId, change === "media" ? { was } : undefined);
80
85
  }
81
86
  }
82
87
 
@@ -193,8 +198,9 @@ function mappings(app, messageId, chatId, filter = "") {
193
198
  * @param {string} chatId
194
199
  * @param {any} sent Telegram's Message
195
200
  * @param {"text" | "caption" | "media"} kind
201
+ * @param {string[]} [files] the attachments it holds (stored names), which a media edit finds it by (editMedia)
196
202
  */
197
- function remember(app, messageId, chatId, sent, kind) {
203
+ function remember(app, messageId, chatId, sent, kind, files = []) {
198
204
  try {
199
205
  app.runInTransaction((tx) => {
200
206
  for (const old of tx.findRecordsByFilter("tg_messages", "chat_id = {:chat} && tg_message_id = {:id}", "", 0, 0, {
@@ -209,6 +215,7 @@ function remember(app, messageId, chatId, sent, kind) {
209
215
  row.set("tg_message_id", sent.message_id);
210
216
  row.set("direction", "out");
211
217
  row.set("kind", kind);
218
+ if (files.length) row.set("files", files);
212
219
  tx.save(row);
213
220
  });
214
221
  } catch (err) {
@@ -238,7 +245,7 @@ function filesOf(app, fsys, source) {
238
245
  const kind = sticker ? "sticker" : PHOTO_EXT.has(ext) && size <= MAX_PHOTO ? "photo" : VIDEO_EXT.has(ext) ? "video" : "document";
239
246
  const file = fsys.getReuploadableFile(key, true);
240
247
  file.name = names[name] || name.replace(/_[a-z0-9]{10}(\.[^.]*)?$/i, "$1");
241
- return { kind, file, size };
248
+ return { kind, file, size, name };
242
249
  });
243
250
  }
244
251
 
@@ -307,7 +314,7 @@ function send(app, messageId, chatId, done = 0, sent = () => {}) {
307
314
  * @param {core.App} app
308
315
  * @param {string} messageId
309
316
  * @param {string} chatId
310
- * @param {{ kind: string, file: any, size: number }[]} group
317
+ * @param {{ kind: string, file: any, size: number, name: string }[]} group
311
318
  * @param {Record<string, unknown> | null} caption
312
319
  * @param {Record<string, unknown>} reply
313
320
  */
@@ -321,7 +328,7 @@ function sendGroup(app, messageId, chatId, group, caption, reply) {
321
328
  { [f.kind]: f.file },
322
329
  timeout,
323
330
  );
324
- remember(app, messageId, chatId, sent, caption ? "caption" : "media");
331
+ remember(app, messageId, chatId, sent, caption ? "caption" : "media", [f.name]);
325
332
  return;
326
333
  }
327
334
  /** @type {Record<string, any>} */
@@ -336,7 +343,9 @@ function sendGroup(app, messageId, chatId, group, caption, reply) {
336
343
  };
337
344
  });
338
345
  const sent = call("sendMediaGroup", { chat_id: chatId, media, ...reply }, attach, timeout);
339
- for (let i = 0; i < sent.length; i++) remember(app, messageId, chatId, sent[i], i === 0 && caption ? "caption" : "media");
346
+ for (let i = 0; i < sent.length; i++) {
347
+ remember(app, messageId, chatId, sent[i], i === 0 && caption ? "caption" : "media", group[i] ? [group[i].name] : []);
348
+ }
340
349
  }
341
350
 
342
351
  /**
@@ -362,6 +371,84 @@ function edit(app, messageId, chatId) {
362
371
  }
363
372
  }
364
373
 
374
+ /**
375
+ * The attachment (stored name) each of a message's Telegram messages holding files holds, in their order, "" where
376
+ * it isn't known. Those sent before they said (remember's `files`) went in the order send() sent them, photos and
377
+ * videos first and documents after: `was` (the attachments then) in that order, when there are as many.
378
+ * @param {core.Record[]} rows tg_messages, by tg_message_id
379
+ * @param {string[]} was
380
+ */
381
+ function heldFiles(rows, was) {
382
+ const recorded = rows.map((r) => {
383
+ try {
384
+ const list = JSON.parse(r.getString("files") || "null");
385
+ return Array.isArray(list) && typeof list[0] === "string" ? list[0] : "";
386
+ } catch {
387
+ return "";
388
+ }
389
+ });
390
+ if (recorded.every(Boolean)) return recorded;
391
+ const shown = (/** @type {string} */ n) => {
392
+ const ext = n.slice(n.lastIndexOf(".") + 1).toLowerCase();
393
+ return PHOTO_EXT.has(ext) || VIDEO_EXT.has(ext);
394
+ };
395
+ const order = [...was.filter(shown), ...was.filter((n) => !shown(n))];
396
+ return order.length === rows.length ? order : recorded;
397
+ }
398
+
399
+ /**
400
+ * Pass replaced attachments on (lib/files.js replaceMessageFiles: a Telegram media edit in another group, §26.4, or a
401
+ * linked instance's, §33.6): each Telegram message sent from here that holds one replaced gets the new one in its
402
+ * place (editMessageMedia), keeping its caption; then the text, as an edit. `was`: the attachments before, which
403
+ * the new ones replace position by position (a Telegram media edit keeps their number; when it changed, only the text
404
+ * goes). What Telegram refuses (a sticker, a document into an album of photos) keeps the old one, and is logged.
405
+ * @param {core.App} app
406
+ * @param {string} messageId
407
+ * @param {string} chatId
408
+ * @param {string[]} was
409
+ */
410
+ function editMedia(app, messageId, chatId, was) {
411
+ const msg = findMessage(app, messageId);
412
+ if (!msg || msg.getBool("deleted")) return;
413
+ const content = contentOf(app, msg, !!linkOfChat(app, chatId)?.getBool("anonymous"));
414
+ const now = content.source.getStringSlice("files");
415
+ const rows = mappings(app, messageId, chatId, " && direction = 'out' && kind != 'text'");
416
+ if (rows.length && was.length === now.length) {
417
+ const held = heldFiles(rows, was);
418
+ const fsys = app.newFilesystem();
419
+ try {
420
+ const files = new Map(filesOf(app, fsys, content.source).map((f) => [f.name, f]));
421
+ rows.forEach((row, i) => {
422
+ const pos = held[i] ? was.indexOf(held[i]) : -1;
423
+ const name = pos >= 0 ? now[pos] : "";
424
+ const f = name && name !== held[i] ? files.get(name) : undefined;
425
+ if (!f) return; // the same, or done by an earlier try (it holds the new one now)
426
+ const type = f.kind === "sticker" ? "photo" : f.kind; // there is no sticker to edit into
427
+ const media = {
428
+ type,
429
+ media: "attach://file0",
430
+ ...(type === "video" ? STREAM : {}),
431
+ ...(row.getString("kind") === "caption" ? { caption: captionOf(content), parse_mode: "HTML" } : {}),
432
+ };
433
+ try {
434
+ const params = { chat_id: chatId, message_id: row.getInt("tg_message_id"), media };
435
+ call("editMessageMedia", params, { file0: f.file }, transferTimeout(f.size));
436
+ } catch (err) {
437
+ const tg = asTelegram(err);
438
+ if (!tg || tg.transient) throw err;
439
+ app.logger().warn("telegram: media edit refused", "message", messageId, "chat", chatId, "error", String(err));
440
+ return;
441
+ }
442
+ row.set("files", [name]);
443
+ app.save(row);
444
+ });
445
+ } finally {
446
+ fsys.close();
447
+ }
448
+ }
449
+ edit(app, messageId, chatId);
450
+ }
451
+
365
452
  /**
366
453
  * Pass a delete on: delete the Telegram messages. Bots can delete their own only for 48 hours (and others' only as an
367
454
  * admin): one that stays says it was deleted instead.
@@ -444,4 +531,4 @@ function tellUndelivered(app, messageId, chatId, err, unsure, partly = false) {
444
531
  }
445
532
  }
446
533
 
447
- module.exports = { queueCreate, queueUpdate, changeOf, send, edit, remove, tellUndelivered };
534
+ module.exports = { queueCreate, queueUpdate, changeOf, send, edit, editMedia, remove, tellUndelivered };
@@ -6,7 +6,7 @@
6
6
 
7
7
  const { asTelegram, call, config, UPDATES } = require(`${__hooks}/telegram/api.js`);
8
8
  const { fetchOver, flushAlbums, handleUpdate } = require(`${__hooks}/telegram/inbound.js`);
9
- const { edit, remove, send, tellUndelivered } = require(`${__hooks}/telegram/outbound.js`);
9
+ const { edit, editMedia, remove, send, tellUndelivered } = require(`${__hooks}/telegram/outbound.js`);
10
10
 
11
11
  const LOCK = "telegram.worker";
12
12
  const OFFSET = "telegram.offset";
@@ -133,6 +133,7 @@ function drain(app, renew) {
133
133
  update(app, row.id, (r) => r.set("payload", payload));
134
134
  });
135
135
  } else if (op === "edit") edit(app, message, chat);
136
+ else if (op === "media") editMedia(app, message, chat, Array.isArray(payload.was) ? payload.was : []);
136
137
  else if (op === "delete") remove(app, message, chat);
137
138
  else if (op === "react") require(`${__hooks}/telegram/reactions.js`).react(app, message, chat);
138
139
  else if (op === "fetch") fetchOver(app, row, tries >= MAX_TRIES);
@@ -0,0 +1,37 @@
1
+ /// <reference path="../types/pocketbase.d.ts" />
2
+ // Telegram media edits (DESIGN.md §26.4, §26.6): a Telegram message whose photo, video or file is replaced changes the
3
+ // chat message's attachment, and a chat message whose attachments the bridge or a linked instance replaced changes the
4
+ // Telegram messages that hold them.
5
+ // - tg_messages.files: the stored names (messages.files) a Telegram message holds, either way: which attachment an
6
+ // album item is, and which Telegram message to edit for one.
7
+ // - tg_messages.file_ids: the file_unique_ids of what a Telegram message brought over: an edit with the same ones only
8
+ // changes its caption.
9
+ // - tg_queue op "media": pass replaced attachments on to a group (payload.was: the stored names before).
10
+
11
+ /**
12
+ * @param {MigrationApp} app
13
+ * @param {string[]} values
14
+ */
15
+ function setOps(app, values) {
16
+ const queue = app.findCollectionByNameOrId("tg_queue");
17
+ /** @type {any} */ (queue.fields.getByName("op")).values = values;
18
+ app.save(queue);
19
+ }
20
+
21
+ migrate(
22
+ (app) => {
23
+ const tg = app.findCollectionByNameOrId("tg_messages");
24
+ tg.fields.add(new JSONField({ name: "files", maxSize: 4000 }));
25
+ tg.fields.add(new JSONField({ name: "file_ids", maxSize: 4000 }));
26
+ app.save(tg);
27
+ setOps(app, ["send", "edit", "delete", "album", "react", "fetch", "media"]);
28
+ },
29
+ (app) => {
30
+ app.db().newQuery("DELETE FROM tg_queue WHERE op = 'media'").execute();
31
+ setOps(app, ["send", "edit", "delete", "album", "react", "fetch"]);
32
+ const tg = app.findCollectionByNameOrId("tg_messages");
33
+ tg.fields.removeByName("files");
34
+ tg.fields.removeByName("file_ids");
35
+ app.save(tg);
36
+ },
37
+ );
@@ -0,0 +1,23 @@
1
+ /// <reference path="../types/pocketbase.d.ts" />
2
+ // Pinned messages (DESIGN.md §45): `rooms.pins`, newest first, each { message, by, at, text }: the message's id, who
3
+ // pinned it, when, and the start of its text (kept up to date by the messages hooks, so the room's pin bar needs no
4
+ // request). Only POST /api/chat/pins changes it (lib/pins.js); no client sets it through the records API.
5
+
6
+ const C_NO_PINS = "@request.body.pins:isset = false";
7
+
8
+ migrate(
9
+ (app) => {
10
+ const rooms = app.findCollectionByNameOrId("rooms");
11
+ rooms.fields.add(new JSONField({ name: "pins", maxSize: 20000 }));
12
+ rooms.createRule = `${rooms.createRule} && ${C_NO_PINS}`;
13
+ rooms.updateRule = `${rooms.updateRule} && ${C_NO_PINS}`;
14
+ app.save(rooms);
15
+ },
16
+ (app) => {
17
+ const rooms = app.findCollectionByNameOrId("rooms");
18
+ rooms.fields.removeByName("pins");
19
+ rooms.createRule = (rooms.createRule ?? "").replace(` && ${C_NO_PINS}`, "");
20
+ rooms.updateRule = (rooms.updateRule ?? "").replace(` && ${C_NO_PINS}`, "");
21
+ app.save(rooms);
22
+ },
23
+ );
@@ -1,2 +1,2 @@
1
- import{b as Ce,c as xe}from"./chunk-VSHXXDW4.js";import{a as ge}from"./chunk-RPCBA7VF.js";import{a as Ee}from"./chunk-UZDXAORM.js";import{l as Z,m as ue,o as ve,s as fe}from"./chunk-5PKDEWJS.js";import{c as F,d as me,g as be,i as ye}from"./chunk-Y5MCBN66.js";import{a as he}from"./chunk-DCLJRQ53.js";import{a as t,b as pe}from"./chunk-VTOUI25E.js";var we=i=>`Only ${i?"you and the people you add":"its creator and the people added"} will see this room. Everyone else loses it from their list.`;var ee=(i,s)=>`A room can have up to ${i} ${s?"members":"people who post"}.`,_e=(i,s)=>`Shared with ${i.join(", ")}: its messages are kept there too.${s?` Add people there by their address, like ann@${i[0]}.`:""}`;var ke=i=>i===1?"1 day":`${i} days`;var Se=(i,s)=>`Works until ${i} \xB7 ${s===0?"nobody has joined by it yet":s===1?"1 person joined by it":`${s} people joined by it`}`;var te=null;function He(i){return te??=new Promise(s=>{let x=i("link",{rel:"stylesheet",href:"/assets/access-XGNXIUR5.css",on:{load:()=>s(),error:()=>{x.remove(),te=null,s()}}});document.head.append(x)}),te}var Ve=["private","public","open"],Ae={private:"ic i-lock",open:"ic i-globe",everyone:"ic i-users",selected:"ic i-check"},Ye={everyone:{label:"Everyone who can see it",icon:"",hint:"Guests of an Open Air room only read."},selected:{label:"Only people you choose",icon:"",hint:"Everyone else reads and reacts, but can't post."}};function Ke(i,s,S){return i===s?"":s==="open"?"Everything ever written here, and everything to come, becomes readable by anyone on the web.":i==="private"?"Everyone with an account will be able to read the whole history.":s==="private"?we(S):"People without an account won't see this room any more."}function Xe(i){let{signal:s}=i,S=Ee.roomMembers,x=pe("access"),j=t("h2",{id:`${x}-title`}),ne=t("p",{class:"dialog-sub"});function oe(e,n,o){let c=t("legend",{}),h=new Map;return{el:t("fieldset",{class:"vis-choices"},[c,...e.map(a=>{let f=t("input",{type:"radio",name:`${x}-${e[0]}`,value:a,"aria-labelledby":`${x}-${a}-label`,"aria-describedby":`${x}-${a}-hint`,on:{change:()=>o(a)},signal:s});return h.set(a,f),t("label",{class:`vis-choice vis-${a}`},[f,t("span",{class:`vis-icon ${Ae[a]??""}`,"aria-hidden":"true"},Ae[a]?"":n[a].icon),t("span",{class:"vis-text"},[t("span",{id:`${x}-${a}-label`,class:"vis-label"},n[a].label),t("span",{id:`${x}-${a}-hint`,class:"vis-hint"},n[a].hint)])])})]),legend:c,radios:h}}let N=oe(Ve,be,e=>{C=e,ae()});N.legend.textContent="Who can see it";let D=oe(["everyone","selected"],Ye,e=>{P=e,ae()});D.legend.textContent="Who can post";function se(e,n,o){let c=t("h3",{}),h=t("ul",{class:"member-list","aria-label":e}),l=t("button",{type:"button",class:"add-member ic i-plus",on:{click:()=>O(g)},signal:s},"Add people"),a=t("div",{class:"member-search"}),f=t("section",{class:n},[t("div",{class:"people-head"},[c,l]),a,h]),g={el:f,addBtn:l,slot:a,pickable:o,list:[],render(){let T=f.hidden?[]:g.list.filter(re);c.textContent=`${e} \xB7 ${T.length}`;let E=g.list.length>=S;l.hidden=!b||_?.p===g,l.disabled=E,l.title=E?ee(S,g===m):"",h.replaceChildren(...T.map(y=>{let L=y.id===r?.created_by;return t("li",{class:"member",dataset:{userId:y.id}},[ge(y,32,i.avatarUrl),t("span",{class:"member-name"},[y.name,y.id===V?t("span",{}," (you)"):null]),L?t("span",{class:"member-role"},"Creator"):null,y.instance?t("span",{class:"member-role"},y.instance):null,b&&!L?t("button",{type:"button",class:"remove-member","aria-label":`Remove ${y.name}`,on:{click:()=>Re(g,y.id)},signal:s},"Remove"):null])}))}};return g}let m=se("Members","members",()=>!0),v=se("Who can post","writers",e=>C!=="private"||Y(m,e)),G=Ne(),ie=t("p",{class:"access-warning",role:"status"}),q=t("p",{class:"access-shared"}),A=t("p",{class:"field-error",role:"alert"}),R=t("button",{type:"button",class:"cancel",on:{click:()=>U()},signal:s},"Cancel"),H=t("button",{type:"button",class:"primary save",on:{click:()=>{Ue()}},signal:s},"Save"),Ie=t("div",{class:"dialog-actions"},[R,H]),J=t("button",{type:"button",class:"icon-button ic i-x",tabindex:"-1","aria-hidden":"true",on:{click:()=>U()},signal:s}),Oe=t("div",{class:"dialog-head"},[t("div",{},[j,ne]),J]),Te=t("div",{class:"access-body"},[q,N.el,m.el,G.el,D.el,v.el,ie,A]),w=t("dialog",{class:"access","aria-labelledby":j.id},[Oe,Te,Ie]),r=null,V,b=!1,C="public",P="everyone",Y=(e,n)=>e.list.some(o=>o.id===n.id),re=e=>!e.no_dms||!!e.instance,le=()=>r?.shared?.with??[],_=null,K=!1;function Ne(){let e=t("h3",{},"Invite link"),n=t("p",{class:"vis-hint"},"Anyone with the link who has an account here can join as a member."),o=t("input",{type:"text",readOnly:!0,class:"invite-url","aria-label":"Invite link",on:{focus:()=>o.select()},signal:s}),c=t("p",{class:"invite-meta"}),h=t("select",{signal:s},he.map(d=>t("option",{value:String(d),selected:d===7},ke(d)))),l=(d,u,k="")=>t("button",{type:"button",class:k,on:{click:u},signal:s},d),a=l("Copy link",()=>{We()},"primary"),f=l("Create link",()=>{X(d=>d.make(r.id,Number(h.value)))},"primary"),g=l("New link",()=>{X(d=>d.make(r.id,Number(h.value)))}),T=l("Revoke",()=>{X(async d=>(await d.revoke(r.id),null))}),E=t("p",{class:"invite-status",role:"status"}),y=t("div",{class:"invite-shown"},[t("div",{class:"invite-row"},[o,a]),c]),L=t("label",{class:"invite-days"},["Works for",h]),Le=t("div",{class:"invite-actions"},[L,f,g,T]),z=t("section",{class:"invite"},[e,n,y,Le,E]),p,$=null,Q=null,W=!1,de=()=>(Q??=i.invites().catch(d=>{throw Q=null,d}),Q),$e=()=>!!r&&!!i.invites&&b&&C==="private"&&F(r)==="private"&&!r.shared?.home;async function X(d){if(W||!r)return;let u=r,k=!!p;W=!0,E.textContent="",M();try{let B=await d(await de());if(s.aborted||r!==u)return;p=B,E.textContent=B?k?"A new link is ready. The old one no longer works.":"The link is ready to share.":"The link no longer works."}catch(B){r===u&&(E.textContent=`Couldn't change the link: ${Z(B)}`)}finally{W=!1,M()}}async function We(){o.select();try{await navigator.clipboard.writeText(o.value),E.textContent="Copied."}catch{E.textContent="Press Ctrl+C to copy it."}}function Me(){let d=r;if(!d)return;$=new AbortController;let u=$;s.addEventListener("abort",()=>u.abort(),{once:!0}),de().then(k=>k.get(d.id,u.signal)).then(k=>{u.signal.aborted||r!==d||(p=k,M())},k=>{u.signal.aborted||r!==d||(p=null,E.textContent=`Couldn't load the invite link: ${Z(k)}`,M())})}function M(){if(z.hidden=!$e(),z.hidden)return;p===void 0&&!$&&Me();let d=!!p,u=!!r?.archived;n.textContent=u?"The room is archived: its link doesn't work until the room is unarchived.":"Anyone with the link who has an account here can join as a member.",y.hidden=!d||u,L.hidden=u,f.hidden=d||u,g.hidden=!d||u,T.hidden=!d,f.disabled=g.disabled=T.disabled=W||p===void 0,p&&(o.value=i.inviteUrl?i.inviteUrl(p.token):p.token,c.textContent=Se(fe(ve(p.expires)),p.uses))}return{el:z,render:M,reset(){$?.abort(),$=null,p=void 0,W=!1,E.textContent=""}}}function ae(){A.textContent="",C==="private"&&(v.list=v.list.filter(e=>Y(m,e))),I()}function I(){if(!r)return;for(let[n,o]of N.radios)o.checked=n===C;for(let[n,o]of D.radios)o.checked=n===P;N.el.hidden=D.el.hidden=!b,m.el.hidden=C!=="private",v.el.hidden=P!=="selected",m.render(),v.render(),G.render(),ie.textContent=b?Ke(F(r),C,r.created_by===V):"";let e=le();q.hidden=!e.length,q.textContent=e.length?r.shared?.home?`This room's home is ${r.shared.home}: who is in it is decided there.`:_e(e,b):"",H.hidden=!b,R.textContent=b?"Cancel":"Close"}function Re(e,n){let o=e.el.querySelector("ul"),c=[...o.children].findIndex(l=>l.dataset.userId===n);e.list=e.list.filter(l=>l.id!==n),e===m&&(v.list=v.list.filter(l=>l.id!==n)),I();let h=[...o.querySelectorAll("button.remove-member")];(h[Math.min(c-1,h.length-1)]??e.addBtn).focus()}function Pe(e,n){if(Y(e,n))e.list=e.list.filter(o=>o.id!==n.id),e===m&&(v.list=v.list.filter(o=>o.id!==n.id));else if(e.list.length>=S){A.textContent=ee(S,e===m);return}else e.list=[...e.list,n];A.textContent="",I(),_?.ui.mark()}function O(e){if(e!==(_?.p??null))if(_?.ac.abort(),_?.p.slot.replaceChildren(),_=null,e){let n=new AbortController;s.addEventListener("abort",()=>n.abort(),{once:!0});let o=xe({search:async(c,h)=>{if(!ye(c)||!r||!le().length||!i.remoteUser)return(await i.searchUsers(c,h)).filter(l=>re(l)&&e.pickable(l));try{let l=await i.remoteUser(c,r.id);return e.pickable(l)?[l]:[]}catch(l){throw new Ce(ue(l))}},avatarUrl:i.avatarUrl,onPick:c=>Pe(e,c),isPicked:c=>Y(e,c),label:e===m?"Find someone to add as a member":"Find someone who can post",onClose:()=>{O(null),e.addBtn.focus()},signal:n.signal});_={ac:n,ui:o,p:e},e.slot.replaceChildren(o.el),I(),o.focus(),e.el.firstElementChild?.scrollIntoView?.({block:"start"})}else I()}async function Ue(){if(K||!r||!b)return;K=!0,H.disabled=R.disabled=J.disabled=!0,A.textContent="";let e=o=>o.list.map(c=>c.id),n=await i.onSave(C,e(m),P,e(v));if(K=!1,H.disabled=R.disabled=J.disabled=!1,!s.aborted){if(n===null)return U();A.textContent=n,w.open||w.showModal()}}function U(){O(null),w.open&&w.close()}w.addEventListener("cancel",e=>{if(K)e.preventDefault();else if(_){e.preventDefault();let n=_.p;O(null),n.addBtn.focus()}},{signal:s}),w.addEventListener("close",()=>O(null),{signal:s}),s.addEventListener("abort",U,{once:!0});function ce(e,n,o,c){let h=new Map([...e.expand?.members??[],...o??[]].map(a=>[a.id,a]));return c&&!h.has(c.id)&&h.set(c.id,c),[...new Set(n.length?n:[e.created_by,V||e.created_by])].map(a=>h.get(a)??{id:a,name:"Unknown"}).sort((a,f)=>+(f.id===e.created_by)-+(a.id===e.created_by))}return{el:w,open(e,n,o){r=e,V=o?.id,b=n,C=F(e),P=me(e),m.list=ce(e,e.members??[],void 0,o),v.list=ce(e,e.writers??[],e.expand?.writers,o),j.textContent=b?"Room access":"Members",ne.textContent=`#${e.name}`,A.textContent="",O(null),G.reset(),I(),He(t).then(()=>{s.aborted||r!==e||(w.open||w.showModal(),(b?N.radios.get(C):R)?.focus())})},close:U}}export{Xe as createAccessDialog};
2
- //# sourceMappingURL=access-KVSI7EFH.js.map
1
+ import{b as Ce,c as xe}from"./chunk-VSHXXDW4.js";import{a as ge}from"./chunk-RPCBA7VF.js";import{a as Ee}from"./chunk-UZDXAORM.js";import{l as Z,m as ue,o as ve,s as fe}from"./chunk-DC4TJ7HF.js";import{c as F,d as me,i as be,k as ye}from"./chunk-SZMAZMR4.js";import{a as he}from"./chunk-DCLJRQ53.js";import{a as t,b as pe}from"./chunk-VTOUI25E.js";var we=i=>`Only ${i?"you and the people you add":"its creator and the people added"} will see this room. Everyone else loses it from their list.`;var ee=(i,s)=>`A room can have up to ${i} ${s?"members":"people who post"}.`,_e=(i,s)=>`Shared with ${i.join(", ")}: its messages are kept there too.${s?` Add people there by their address, like ann@${i[0]}.`:""}`;var ke=i=>i===1?"1 day":`${i} days`;var Se=(i,s)=>`Works until ${i} \xB7 ${s===0?"nobody has joined by it yet":s===1?"1 person joined by it":`${s} people joined by it`}`;var te=null;function He(i){return te??=new Promise(s=>{let x=i("link",{rel:"stylesheet",href:"/assets/access-XGNXIUR5.css",on:{load:()=>s(),error:()=>{x.remove(),te=null,s()}}});document.head.append(x)}),te}var Ve=["private","public","open"],Ae={private:"ic i-lock",open:"ic i-globe",everyone:"ic i-users",selected:"ic i-check"},Ye={everyone:{label:"Everyone who can see it",icon:"",hint:"Guests of an Open Air room only read."},selected:{label:"Only people you choose",icon:"",hint:"Everyone else reads and reacts, but can't post."}};function Ke(i,s,S){return i===s?"":s==="open"?"Everything ever written here, and everything to come, becomes readable by anyone on the web.":i==="private"?"Everyone with an account will be able to read the whole history.":s==="private"?we(S):"People without an account won't see this room any more."}function Xe(i){let{signal:s}=i,S=Ee.roomMembers,x=pe("access"),j=t("h2",{id:`${x}-title`}),ne=t("p",{class:"dialog-sub"});function oe(e,n,o){let c=t("legend",{}),h=new Map;return{el:t("fieldset",{class:"vis-choices"},[c,...e.map(a=>{let f=t("input",{type:"radio",name:`${x}-${e[0]}`,value:a,"aria-labelledby":`${x}-${a}-label`,"aria-describedby":`${x}-${a}-hint`,on:{change:()=>o(a)},signal:s});return h.set(a,f),t("label",{class:`vis-choice vis-${a}`},[f,t("span",{class:`vis-icon ${Ae[a]??""}`,"aria-hidden":"true"},Ae[a]?"":n[a].icon),t("span",{class:"vis-text"},[t("span",{id:`${x}-${a}-label`,class:"vis-label"},n[a].label),t("span",{id:`${x}-${a}-hint`,class:"vis-hint"},n[a].hint)])])})]),legend:c,radios:h}}let N=oe(Ve,be,e=>{C=e,ae()});N.legend.textContent="Who can see it";let D=oe(["everyone","selected"],Ye,e=>{P=e,ae()});D.legend.textContent="Who can post";function se(e,n,o){let c=t("h3",{}),h=t("ul",{class:"member-list","aria-label":e}),l=t("button",{type:"button",class:"add-member ic i-plus",on:{click:()=>O(g)},signal:s},"Add people"),a=t("div",{class:"member-search"}),f=t("section",{class:n},[t("div",{class:"people-head"},[c,l]),a,h]),g={el:f,addBtn:l,slot:a,pickable:o,list:[],render(){let T=f.hidden?[]:g.list.filter(re);c.textContent=`${e} \xB7 ${T.length}`;let E=g.list.length>=S;l.hidden=!b||_?.p===g,l.disabled=E,l.title=E?ee(S,g===m):"",h.replaceChildren(...T.map(y=>{let L=y.id===r?.created_by;return t("li",{class:"member",dataset:{userId:y.id}},[ge(y,32,i.avatarUrl),t("span",{class:"member-name"},[y.name,y.id===V?t("span",{}," (you)"):null]),L?t("span",{class:"member-role"},"Creator"):null,y.instance?t("span",{class:"member-role"},y.instance):null,b&&!L?t("button",{type:"button",class:"remove-member","aria-label":`Remove ${y.name}`,on:{click:()=>Re(g,y.id)},signal:s},"Remove"):null])}))}};return g}let m=se("Members","members",()=>!0),v=se("Who can post","writers",e=>C!=="private"||Y(m,e)),G=Ne(),ie=t("p",{class:"access-warning",role:"status"}),q=t("p",{class:"access-shared"}),A=t("p",{class:"field-error",role:"alert"}),R=t("button",{type:"button",class:"cancel",on:{click:()=>U()},signal:s},"Cancel"),H=t("button",{type:"button",class:"primary save",on:{click:()=>{Ue()}},signal:s},"Save"),Ie=t("div",{class:"dialog-actions"},[R,H]),J=t("button",{type:"button",class:"icon-button ic i-x",tabindex:"-1","aria-hidden":"true",on:{click:()=>U()},signal:s}),Oe=t("div",{class:"dialog-head"},[t("div",{},[j,ne]),J]),Te=t("div",{class:"access-body"},[q,N.el,m.el,G.el,D.el,v.el,ie,A]),w=t("dialog",{class:"access","aria-labelledby":j.id},[Oe,Te,Ie]),r=null,V,b=!1,C="public",P="everyone",Y=(e,n)=>e.list.some(o=>o.id===n.id),re=e=>!e.no_dms||!!e.instance,le=()=>r?.shared?.with??[],_=null,K=!1;function Ne(){let e=t("h3",{},"Invite link"),n=t("p",{class:"vis-hint"},"Anyone with the link who has an account here can join as a member."),o=t("input",{type:"text",readOnly:!0,class:"invite-url","aria-label":"Invite link",on:{focus:()=>o.select()},signal:s}),c=t("p",{class:"invite-meta"}),h=t("select",{signal:s},he.map(d=>t("option",{value:String(d),selected:d===7},ke(d)))),l=(d,u,k="")=>t("button",{type:"button",class:k,on:{click:u},signal:s},d),a=l("Copy link",()=>{We()},"primary"),f=l("Create link",()=>{X(d=>d.make(r.id,Number(h.value)))},"primary"),g=l("New link",()=>{X(d=>d.make(r.id,Number(h.value)))}),T=l("Revoke",()=>{X(async d=>(await d.revoke(r.id),null))}),E=t("p",{class:"invite-status",role:"status"}),y=t("div",{class:"invite-shown"},[t("div",{class:"invite-row"},[o,a]),c]),L=t("label",{class:"invite-days"},["Works for",h]),Le=t("div",{class:"invite-actions"},[L,f,g,T]),z=t("section",{class:"invite"},[e,n,y,Le,E]),p,$=null,Q=null,W=!1,de=()=>(Q??=i.invites().catch(d=>{throw Q=null,d}),Q),$e=()=>!!r&&!!i.invites&&b&&C==="private"&&F(r)==="private"&&!r.shared?.home;async function X(d){if(W||!r)return;let u=r,k=!!p;W=!0,E.textContent="",M();try{let B=await d(await de());if(s.aborted||r!==u)return;p=B,E.textContent=B?k?"A new link is ready. The old one no longer works.":"The link is ready to share.":"The link no longer works."}catch(B){r===u&&(E.textContent=`Couldn't change the link: ${Z(B)}`)}finally{W=!1,M()}}async function We(){o.select();try{await navigator.clipboard.writeText(o.value),E.textContent="Copied."}catch{E.textContent="Press Ctrl+C to copy it."}}function Me(){let d=r;if(!d)return;$=new AbortController;let u=$;s.addEventListener("abort",()=>u.abort(),{once:!0}),de().then(k=>k.get(d.id,u.signal)).then(k=>{u.signal.aborted||r!==d||(p=k,M())},k=>{u.signal.aborted||r!==d||(p=null,E.textContent=`Couldn't load the invite link: ${Z(k)}`,M())})}function M(){if(z.hidden=!$e(),z.hidden)return;p===void 0&&!$&&Me();let d=!!p,u=!!r?.archived;n.textContent=u?"The room is archived: its link doesn't work until the room is unarchived.":"Anyone with the link who has an account here can join as a member.",y.hidden=!d||u,L.hidden=u,f.hidden=d||u,g.hidden=!d||u,T.hidden=!d,f.disabled=g.disabled=T.disabled=W||p===void 0,p&&(o.value=i.inviteUrl?i.inviteUrl(p.token):p.token,c.textContent=Se(fe(ve(p.expires)),p.uses))}return{el:z,render:M,reset(){$?.abort(),$=null,p=void 0,W=!1,E.textContent=""}}}function ae(){A.textContent="",C==="private"&&(v.list=v.list.filter(e=>Y(m,e))),I()}function I(){if(!r)return;for(let[n,o]of N.radios)o.checked=n===C;for(let[n,o]of D.radios)o.checked=n===P;N.el.hidden=D.el.hidden=!b,m.el.hidden=C!=="private",v.el.hidden=P!=="selected",m.render(),v.render(),G.render(),ie.textContent=b?Ke(F(r),C,r.created_by===V):"";let e=le();q.hidden=!e.length,q.textContent=e.length?r.shared?.home?`This room's home is ${r.shared.home}: who is in it is decided there.`:_e(e,b):"",H.hidden=!b,R.textContent=b?"Cancel":"Close"}function Re(e,n){let o=e.el.querySelector("ul"),c=[...o.children].findIndex(l=>l.dataset.userId===n);e.list=e.list.filter(l=>l.id!==n),e===m&&(v.list=v.list.filter(l=>l.id!==n)),I();let h=[...o.querySelectorAll("button.remove-member")];(h[Math.min(c-1,h.length-1)]??e.addBtn).focus()}function Pe(e,n){if(Y(e,n))e.list=e.list.filter(o=>o.id!==n.id),e===m&&(v.list=v.list.filter(o=>o.id!==n.id));else if(e.list.length>=S){A.textContent=ee(S,e===m);return}else e.list=[...e.list,n];A.textContent="",I(),_?.ui.mark()}function O(e){if(e!==(_?.p??null))if(_?.ac.abort(),_?.p.slot.replaceChildren(),_=null,e){let n=new AbortController;s.addEventListener("abort",()=>n.abort(),{once:!0});let o=xe({search:async(c,h)=>{if(!ye(c)||!r||!le().length||!i.remoteUser)return(await i.searchUsers(c,h)).filter(l=>re(l)&&e.pickable(l));try{let l=await i.remoteUser(c,r.id);return e.pickable(l)?[l]:[]}catch(l){throw new Ce(ue(l))}},avatarUrl:i.avatarUrl,onPick:c=>Pe(e,c),isPicked:c=>Y(e,c),label:e===m?"Find someone to add as a member":"Find someone who can post",onClose:()=>{O(null),e.addBtn.focus()},signal:n.signal});_={ac:n,ui:o,p:e},e.slot.replaceChildren(o.el),I(),o.focus(),e.el.firstElementChild?.scrollIntoView?.({block:"start"})}else I()}async function Ue(){if(K||!r||!b)return;K=!0,H.disabled=R.disabled=J.disabled=!0,A.textContent="";let e=o=>o.list.map(c=>c.id),n=await i.onSave(C,e(m),P,e(v));if(K=!1,H.disabled=R.disabled=J.disabled=!1,!s.aborted){if(n===null)return U();A.textContent=n,w.open||w.showModal()}}function U(){O(null),w.open&&w.close()}w.addEventListener("cancel",e=>{if(K)e.preventDefault();else if(_){e.preventDefault();let n=_.p;O(null),n.addBtn.focus()}},{signal:s}),w.addEventListener("close",()=>O(null),{signal:s}),s.addEventListener("abort",U,{once:!0});function ce(e,n,o,c){let h=new Map([...e.expand?.members??[],...o??[]].map(a=>[a.id,a]));return c&&!h.has(c.id)&&h.set(c.id,c),[...new Set(n.length?n:[e.created_by,V||e.created_by])].map(a=>h.get(a)??{id:a,name:"Unknown"}).sort((a,f)=>+(f.id===e.created_by)-+(a.id===e.created_by))}return{el:w,open(e,n,o){r=e,V=o?.id,b=n,C=F(e),P=me(e),m.list=ce(e,e.members??[],void 0,o),v.list=ce(e,e.writers??[],e.expand?.writers,o),j.textContent=b?"Room access":"Members",ne.textContent=`#${e.name}`,A.textContent="",O(null),G.reset(),I(),He(t).then(()=>{s.aborted||r!==e||(w.open||w.showModal(),(b?N.radios.get(C):R)?.focus())})},close:U}}export{Xe as createAccessDialog};
2
+ //# sourceMappingURL=access-23A7N3OD.js.map