chirkle 0.4.1 → 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 (229) hide show
  1. package/README.md +56 -202
  2. package/bin/release/darwin-amd64/chirkle-server +2 -2
  3. package/bin/release/darwin-arm64/chirkle-server +0 -0
  4. package/bin/release/linux-amd64/chirkle-server +0 -0
  5. package/bin/release/linux-arm64/chirkle-server +0 -0
  6. package/package.json +18 -5
  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/collections.js +5 -3
  11. package/pb_hooks/lib/files.js +36 -0
  12. package/pb_hooks/lib/handles.js +24 -2
  13. package/pb_hooks/lib/http.js +2 -2
  14. package/pb_hooks/lib/inbox.js +6 -5
  15. package/pb_hooks/lib/media.js +16 -3
  16. package/pb_hooks/lib/messages.js +16 -6
  17. package/pb_hooks/lib/pins.js +199 -0
  18. package/pb_hooks/lib/rooms.js +4 -0
  19. package/pb_hooks/lib/users.js +33 -2
  20. package/pb_hooks/main.pb.js +17 -3
  21. package/pb_hooks/telegram/inbound.js +187 -16
  22. package/pb_hooks/telegram/links.js +12 -1
  23. package/pb_hooks/telegram/outbound.js +153 -12
  24. package/pb_hooks/telegram/worker.js +3 -1
  25. package/pb_migrations/1760000057_reactions_seen.js +17 -0
  26. package/pb_migrations/1760000058_users_kind_public.js +20 -0
  27. package/pb_migrations/1760000059_telegram_media_edits.js +37 -0
  28. package/pb_migrations/1760000060_pins.js +23 -0
  29. package/pb_public/assets/{access-UK3L54NR.js → access-23A7N3OD.js} +2 -2
  30. package/pb_public/assets/access-23A7N3OD.js.br +0 -0
  31. package/pb_public/assets/access-23A7N3OD.js.gz +0 -0
  32. package/pb_public/assets/access-XGNXIUR5.css +2 -0
  33. package/pb_public/assets/access-XGNXIUR5.css.br +0 -0
  34. package/pb_public/assets/access-XGNXIUR5.css.gz +0 -0
  35. package/pb_public/assets/access-XGNXIUR5.css.map +7 -0
  36. package/pb_public/assets/account-EBCPOLWT.css +2 -0
  37. package/pb_public/assets/account-EBCPOLWT.css.br +0 -0
  38. package/pb_public/assets/account-EBCPOLWT.css.gz +0 -0
  39. package/pb_public/assets/account-EBCPOLWT.css.map +7 -0
  40. package/pb_public/assets/account-api-J6A6IYVX.js.br +0 -0
  41. package/pb_public/assets/account-api-J6A6IYVX.js.gz +0 -0
  42. package/pb_public/assets/app-7VYWTXX4.js +3 -0
  43. package/pb_public/assets/app-7VYWTXX4.js.br +0 -0
  44. package/pb_public/assets/app-7VYWTXX4.js.gz +0 -0
  45. package/pb_public/assets/app-7VYWTXX4.js.map +7 -0
  46. package/pb_public/assets/app-LDOYFRVQ.css +2 -0
  47. package/pb_public/assets/app-LDOYFRVQ.css.br +0 -0
  48. package/pb_public/assets/app-LDOYFRVQ.css.gz +0 -0
  49. package/pb_public/assets/app-LDOYFRVQ.css.map +7 -0
  50. package/pb_public/assets/chunk-AG73QNUN.js.br +0 -0
  51. package/pb_public/assets/chunk-AG73QNUN.js.gz +0 -0
  52. package/pb_public/assets/chunk-DC4TJ7HF.js +2 -0
  53. package/pb_public/assets/chunk-DC4TJ7HF.js.br +0 -0
  54. package/pb_public/assets/chunk-DC4TJ7HF.js.gz +0 -0
  55. package/pb_public/assets/chunk-DC4TJ7HF.js.map +7 -0
  56. package/pb_public/assets/chunk-DCLJRQ53.js.br +0 -0
  57. package/pb_public/assets/chunk-DCLJRQ53.js.gz +0 -0
  58. package/pb_public/assets/chunk-RPCBA7VF.js.br +0 -0
  59. package/pb_public/assets/chunk-RPCBA7VF.js.gz +0 -0
  60. package/pb_public/assets/chunk-RYZHXNLF.js +2 -0
  61. package/pb_public/assets/chunk-RYZHXNLF.js.br +0 -0
  62. package/pb_public/assets/chunk-RYZHXNLF.js.gz +0 -0
  63. package/pb_public/assets/chunk-RYZHXNLF.js.map +7 -0
  64. package/pb_public/assets/chunk-SM542ZXL.js +2 -0
  65. package/pb_public/assets/chunk-SM542ZXL.js.br +0 -0
  66. package/pb_public/assets/chunk-SM542ZXL.js.gz +0 -0
  67. package/pb_public/assets/chunk-SM542ZXL.js.map +7 -0
  68. package/pb_public/assets/chunk-SZMAZMR4.js +2 -0
  69. package/pb_public/assets/chunk-SZMAZMR4.js.br +0 -0
  70. package/pb_public/assets/chunk-SZMAZMR4.js.gz +0 -0
  71. package/pb_public/assets/chunk-SZMAZMR4.js.map +7 -0
  72. package/pb_public/assets/chunk-UZDXAORM.js.br +0 -0
  73. package/pb_public/assets/chunk-UZDXAORM.js.gz +0 -0
  74. package/pb_public/assets/chunk-VSHXXDW4.js +2 -0
  75. package/pb_public/assets/chunk-VSHXXDW4.js.br +0 -0
  76. package/pb_public/assets/chunk-VSHXXDW4.js.gz +0 -0
  77. package/pb_public/assets/chunk-VSHXXDW4.js.map +7 -0
  78. package/pb_public/assets/chunk-VTOUI25E.js.br +0 -0
  79. package/pb_public/assets/chunk-VTOUI25E.js.gz +0 -0
  80. package/pb_public/assets/chunk-WDXT4S4J.js +2 -0
  81. package/pb_public/assets/chunk-WDXT4S4J.js.br +0 -0
  82. package/pb_public/assets/chunk-WDXT4S4J.js.gz +0 -0
  83. package/pb_public/assets/chunk-WDXT4S4J.js.map +7 -0
  84. package/pb_public/assets/collections-FZB6G4W4.css +2 -0
  85. package/pb_public/assets/collections-FZB6G4W4.css.br +0 -0
  86. package/pb_public/assets/collections-FZB6G4W4.css.gz +0 -0
  87. package/pb_public/assets/collections-FZB6G4W4.css.map +7 -0
  88. package/pb_public/assets/emoji-IHRUMGCY.css +2 -0
  89. package/pb_public/assets/emoji-IHRUMGCY.css.br +0 -0
  90. package/pb_public/assets/emoji-IHRUMGCY.css.gz +0 -0
  91. package/pb_public/assets/emoji-IHRUMGCY.css.map +7 -0
  92. package/pb_public/assets/{emoji-picker-K6JTK2GV.js → emoji-picker-K4DOKYL3.js} +2 -2
  93. package/pb_public/assets/emoji-picker-K4DOKYL3.js.br +0 -0
  94. package/pb_public/assets/emoji-picker-K4DOKYL3.js.gz +0 -0
  95. package/pb_public/assets/{emoji-picker-K6JTK2GV.js.map → emoji-picker-K4DOKYL3.js.map} +2 -2
  96. package/pb_public/assets/forward-OR7S3EHR.js +2 -0
  97. package/pb_public/assets/forward-OR7S3EHR.js.br +0 -0
  98. package/pb_public/assets/forward-OR7S3EHR.js.gz +0 -0
  99. package/pb_public/assets/forward-OR7S3EHR.js.map +7 -0
  100. package/pb_public/assets/inbox-2AXY3INA.css +2 -0
  101. package/pb_public/assets/inbox-2AXY3INA.css.br +0 -0
  102. package/pb_public/assets/inbox-2AXY3INA.css.gz +0 -0
  103. package/pb_public/assets/inbox-2AXY3INA.css.map +7 -0
  104. package/pb_public/assets/{inbox-CLMYESNI.js → inbox-A46J7ZU2.js} +2 -2
  105. package/pb_public/assets/inbox-A46J7ZU2.js.br +0 -0
  106. package/pb_public/assets/inbox-A46J7ZU2.js.gz +0 -0
  107. package/pb_public/assets/{inbox-CLMYESNI.js.map → inbox-A46J7ZU2.js.map} +2 -2
  108. package/pb_public/assets/{invite-OGT5E2MZ.js → invite-VGT2DI2L.js} +2 -2
  109. package/pb_public/assets/invite-VGT2DI2L.js.br +0 -0
  110. package/pb_public/assets/invite-VGT2DI2L.js.gz +0 -0
  111. package/pb_public/assets/invite-api-7G7XPXQW.js.br +0 -0
  112. package/pb_public/assets/invite-api-7G7XPXQW.js.gz +0 -0
  113. package/pb_public/assets/lazy-OVEJT5CP.js +2 -0
  114. package/pb_public/assets/lazy-OVEJT5CP.js.br +0 -0
  115. package/pb_public/assets/lazy-OVEJT5CP.js.gz +0 -0
  116. package/pb_public/assets/lazy-OVEJT5CP.js.map +7 -0
  117. package/pb_public/assets/{login-TK6K4WGB.js → login-TN6R7N2U.js} +2 -2
  118. package/pb_public/assets/login-TN6R7N2U.js.br +0 -0
  119. package/pb_public/assets/login-TN6R7N2U.js.gz +0 -0
  120. package/pb_public/assets/media-BCKZQR2R.css +2 -0
  121. package/pb_public/assets/media-BCKZQR2R.css.br +0 -0
  122. package/pb_public/assets/media-BCKZQR2R.css.gz +0 -0
  123. package/pb_public/assets/media-BCKZQR2R.css.map +7 -0
  124. package/pb_public/assets/{media-WZ4653L5.js → media-VCJWBQJZ.js} +2 -2
  125. package/pb_public/assets/media-VCJWBQJZ.js.br +0 -0
  126. package/pb_public/assets/media-VCJWBQJZ.js.gz +0 -0
  127. package/pb_public/assets/{mention-suggest-ODJD2IC5.js → mention-suggest-K3UUHR4D.js} +2 -2
  128. package/pb_public/assets/mention-suggest-K3UUHR4D.js.br +0 -0
  129. package/pb_public/assets/mention-suggest-K3UUHR4D.js.gz +0 -0
  130. package/pb_public/assets/notify-EPDM772N.js.br +0 -0
  131. package/pb_public/assets/notify-EPDM772N.js.gz +0 -0
  132. package/pb_public/assets/pins-6NQUEU3U.js +2 -0
  133. package/pb_public/assets/pins-6NQUEU3U.js.br +0 -0
  134. package/pb_public/assets/pins-6NQUEU3U.js.gz +0 -0
  135. package/pb_public/assets/pins-6NQUEU3U.js.map +7 -0
  136. package/pb_public/assets/pins-6ZVYPBB5.css +2 -0
  137. package/pb_public/assets/pins-6ZVYPBB5.css.br +0 -0
  138. package/pb_public/assets/pins-6ZVYPBB5.css.gz +0 -0
  139. package/pb_public/assets/pins-6ZVYPBB5.css.map +7 -0
  140. package/pb_public/assets/profile-NQ6QCQIB.js +2 -0
  141. package/pb_public/assets/profile-NQ6QCQIB.js.br +0 -0
  142. package/pb_public/assets/profile-NQ6QCQIB.js.gz +0 -0
  143. package/pb_public/assets/profile-NQ6QCQIB.js.map +7 -0
  144. package/pb_public/assets/rooms-forms-NYMPXVUQ.js +2 -0
  145. package/pb_public/assets/rooms-forms-NYMPXVUQ.js.br +0 -0
  146. package/pb_public/assets/rooms-forms-NYMPXVUQ.js.gz +0 -0
  147. package/pb_public/assets/rooms-forms-NYMPXVUQ.js.map +7 -0
  148. package/pb_public/assets/search-DRQHBOXE.js +2 -0
  149. package/pb_public/assets/search-DRQHBOXE.js.br +0 -0
  150. package/pb_public/assets/search-DRQHBOXE.js.gz +0 -0
  151. package/pb_public/assets/search-DRQHBOXE.js.map +7 -0
  152. package/pb_public/assets/search-QYHX6XDT.css +2 -0
  153. package/pb_public/assets/search-QYHX6XDT.css.br +0 -0
  154. package/pb_public/assets/search-QYHX6XDT.css.gz +0 -0
  155. package/pb_public/assets/search-QYHX6XDT.css.map +7 -0
  156. package/pb_public/assets/sidebar-forms-ETSRVSPY.css +2 -0
  157. package/pb_public/assets/sidebar-forms-ETSRVSPY.css.br +0 -0
  158. package/pb_public/assets/sidebar-forms-ETSRVSPY.css.gz +0 -0
  159. package/pb_public/assets/sidebar-forms-ETSRVSPY.css.map +7 -0
  160. package/pb_public/assets/stats-5GSWDHZI.css +2 -0
  161. package/pb_public/assets/stats-5GSWDHZI.css.br +0 -0
  162. package/pb_public/assets/stats-5GSWDHZI.css.gz +0 -0
  163. package/pb_public/assets/stats-5GSWDHZI.css.map +7 -0
  164. package/pb_public/assets/{stats-GTO2H6PG.js → stats-Y3LIXAZR.js} +2 -2
  165. package/pb_public/assets/stats-Y3LIXAZR.js.br +0 -0
  166. package/pb_public/assets/stats-Y3LIXAZR.js.gz +0 -0
  167. package/pb_public/assets/stats-Y3LIXAZR.js.map +7 -0
  168. package/pb_public/assets/switcher-TFSO45KV.js.br +0 -0
  169. package/pb_public/assets/switcher-TFSO45KV.js.gz +0 -0
  170. package/pb_public/assets/user-search-GUNMIBSB.js +2 -0
  171. package/pb_public/assets/user-search-GUNMIBSB.js.br +0 -0
  172. package/pb_public/assets/user-search-GUNMIBSB.js.gz +0 -0
  173. package/pb_public/assets/{viewer-2Y5FJBW4.js → viewer-BHKVAADP.js} +2 -2
  174. package/pb_public/assets/viewer-BHKVAADP.js.br +0 -0
  175. package/pb_public/assets/viewer-BHKVAADP.js.gz +0 -0
  176. package/pb_public/assets/viewer-JBZU46HP.css +2 -0
  177. package/pb_public/assets/viewer-JBZU46HP.css.br +0 -0
  178. package/pb_public/assets/viewer-JBZU46HP.css.gz +0 -0
  179. package/pb_public/assets/{viewer-P7GYCBYM.css.map → viewer-JBZU46HP.css.map} +2 -2
  180. package/pb_public/index.html +9 -8
  181. package/pb_public/stats.html +3 -3
  182. package/scripts/service.mjs +1 -1
  183. package/scripts/start.mjs +2 -1
  184. package/pb_public/assets/access-GPRLOZOO.css +0 -2
  185. package/pb_public/assets/access-GPRLOZOO.css.map +0 -7
  186. package/pb_public/assets/account-CT2BVMAX.css +0 -2
  187. package/pb_public/assets/account-CT2BVMAX.css.map +0 -7
  188. package/pb_public/assets/app-HB3NZHQ2.js +0 -3
  189. package/pb_public/assets/app-HB3NZHQ2.js.map +0 -7
  190. package/pb_public/assets/app-XJ73EU5O.css +0 -2
  191. package/pb_public/assets/app-XJ73EU5O.css.map +0 -7
  192. package/pb_public/assets/chunk-56ACD3V5.js +0 -2
  193. package/pb_public/assets/chunk-56ACD3V5.js.map +0 -7
  194. package/pb_public/assets/chunk-DZC4SY4M.js +0 -2
  195. package/pb_public/assets/chunk-DZC4SY4M.js.map +0 -7
  196. package/pb_public/assets/chunk-N2OFGBCZ.js +0 -2
  197. package/pb_public/assets/chunk-N2OFGBCZ.js.map +0 -7
  198. package/pb_public/assets/chunk-OKIIBH7O.js +0 -2
  199. package/pb_public/assets/chunk-OKIIBH7O.js.map +0 -7
  200. package/pb_public/assets/chunk-WR25F7FU.js +0 -2
  201. package/pb_public/assets/chunk-WR25F7FU.js.map +0 -7
  202. package/pb_public/assets/collections-DHJEOLHW.css +0 -2
  203. package/pb_public/assets/collections-DHJEOLHW.css.map +0 -7
  204. package/pb_public/assets/emoji-WWNPWCF3.css +0 -2
  205. package/pb_public/assets/emoji-WWNPWCF3.css.map +0 -7
  206. package/pb_public/assets/forward-267HRNPY.js +0 -2
  207. package/pb_public/assets/forward-267HRNPY.js.map +0 -7
  208. package/pb_public/assets/inbox-3FSOPY2T.css +0 -2
  209. package/pb_public/assets/inbox-3FSOPY2T.css.map +0 -7
  210. package/pb_public/assets/lazy-H3KIJVB5.js +0 -2
  211. package/pb_public/assets/lazy-H3KIJVB5.js.map +0 -7
  212. package/pb_public/assets/media-7TCBG7WM.css +0 -2
  213. package/pb_public/assets/media-7TCBG7WM.css.map +0 -7
  214. package/pb_public/assets/profile-3R6S5QYS.js +0 -2
  215. package/pb_public/assets/profile-3R6S5QYS.js.map +0 -7
  216. package/pb_public/assets/search-WCHOGAJQ.js +0 -2
  217. package/pb_public/assets/search-WCHOGAJQ.js.map +0 -7
  218. package/pb_public/assets/stats-A2TBRUI6.css +0 -2
  219. package/pb_public/assets/stats-A2TBRUI6.css.map +0 -7
  220. package/pb_public/assets/stats-GTO2H6PG.js.map +0 -7
  221. package/pb_public/assets/user-search-3HQOCQWL.js +0 -2
  222. package/pb_public/assets/viewer-P7GYCBYM.css +0 -2
  223. /package/pb_public/assets/{access-UK3L54NR.js.map → access-23A7N3OD.js.map} +0 -0
  224. /package/pb_public/assets/{invite-OGT5E2MZ.js.map → invite-VGT2DI2L.js.map} +0 -0
  225. /package/pb_public/assets/{login-TK6K4WGB.js.map → login-TN6R7N2U.js.map} +0 -0
  226. /package/pb_public/assets/{media-WZ4653L5.js.map → media-VCJWBQJZ.js.map} +0 -0
  227. /package/pb_public/assets/{mention-suggest-ODJD2IC5.js.map → mention-suggest-K3UUHR4D.js.map} +0 -0
  228. /package/pb_public/assets/{user-search-3HQOCQWL.js.map → user-search-GUNMIBSB.js.map} +0 -0
  229. /package/pb_public/assets/{viewer-2Y5FJBW4.js.map → viewer-BHKVAADP.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));
@@ -336,6 +365,11 @@ function bringOver(app, link, room, msgs, mode = "live") {
336
365
  // one message comes as several: the first with the files and the reply, the rest after it.
337
366
  const save = (/** @type {boolean} */ withReply) =>
338
367
  app.runInTransaction((tx) => {
368
+ // Brought over meanwhile: Telegram sent it again while this one was downloading its files (a webhook retry
369
+ // after a slow answer). Checked again here, where writes go one at a time: the forgetStale below would
370
+ // otherwise take the first one's mappings for stale, and the worker, finding it from nowhere, would send the
371
+ // first one back to the group (QA BUG-291).
372
+ if (msgs.some((m) => partsMapped(tx, chatId, m.message_id, m.date).length)) return;
339
373
  const pieces = split(textOf(withReply));
340
374
  const ids = orderedIds(pieces.length);
341
375
  const rec = new Record(tx.findCollectionByNameOrId("messages"));
@@ -346,9 +380,11 @@ function bringOver(app, link, room, msgs, mode = "live") {
346
380
  if (files.length) require(`${__hooks}/lib/files.js`).attachUploads(tx, rec, files);
347
381
  if (withReply && known && reply) rec.set("reply_to", reply.id);
348
382
  tx.save(rec);
383
+ const names = rec.getStringSlice("files"); // in the order of `files`
349
384
  msgs.forEach((m, i) => {
350
385
  forgetStale(tx, chatId, m.message_id);
351
- 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);
352
388
  });
353
389
  for (let i = 1; i < pieces.length; i++) {
354
390
  const part = savePart(tx, room.id, author.id, pieces[i], ids[i]);
@@ -364,7 +400,107 @@ function bringOver(app, link, room, msgs, mode = "live") {
364
400
  }
365
401
 
366
402
  /**
367
- * 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).
368
504
  * @param {core.App} app
369
505
  * @param {any} msg
370
506
  */
@@ -374,14 +510,20 @@ function editOver(app, msg) {
374
510
  const rec = rows[0]?.getInt("part") === 0 ? findMessage(app, rows[0].getString("message")) : null;
375
511
  if (!rec) return editWaiting(app, chatId, msg);
376
512
  if (rec.getBool("deleted") || rec.getString("forwarded_from")) return;
513
+ const item = rows[0].getString("kind") === "media";
377
514
  const quoted = quoteLines(msg, !!rec.getString("reply_to"));
378
- 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;
379
519
  const lines = [forwardLine(msg), ...quoted, text, ...notes].filter(Boolean);
380
- const pieces = split(lines.join("\n"));
381
- 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;
382
524
  // The parts still in the room get the pieces in order: a shorter text deletes the parts left over, a longer one adds
383
525
  // parts (after what came since). A deleted message can't come back, so a part deleted meanwhile is passed over.
384
- const parts = /** @type {core.Record[]} */ (
526
+ const later = /** @type {core.Record[]} */ (
385
527
  rows
386
528
  .slice(1)
387
529
  .map((r) => findMessage(app, r.getString("message")))
@@ -389,16 +531,45 @@ function editOver(app, msg) {
389
531
  );
390
532
  const next = rows.length ? rows[rows.length - 1].getInt("part") + 1 : 1;
391
533
  app.runInTransaction((tx) => {
392
- [rec, ...parts].forEach((part, i) => {
393
- if (i >= pieces.length) part.set("deleted", true);
394
- else if (pieces[i] === part.getString("text")) return;
395
- 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]);
396
567
  tx.save(part);
397
568
  });
398
569
  const ids = orderedIds(pieces.length);
399
- for (let i = parts.length + 1; i < pieces.length; i++) {
570
+ for (let i = later.length + 1; i < pieces.length; i++) {
400
571
  const part = savePart(tx, rec.getString("room"), rec.getString("author"), pieces[i], ids[i]);
401
- 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);
402
573
  }
403
574
  });
404
575
  }
@@ -155,4 +155,15 @@ function tellLinkChange(app, link, was, now, why = "") {
155
155
  if (now) tellRoom(app, now, `${groupName(link)} was connected to this room.`);
156
156
  }
157
157
 
158
- module.exports = { linkOfChat, activeLink, linksOfRoom, ensureLink, moveLink, beforeLinkSave, linkedRoom, tellLinkChange };
158
+ module.exports = {
159
+ linkOfChat,
160
+ activeLink,
161
+ linksOfRoom,
162
+ ensureLink,
163
+ moveLink,
164
+ beforeLinkSave,
165
+ linkedRoom,
166
+ tellLinkChange,
167
+ groupName,
168
+ tellRoom,
169
+ };
@@ -5,7 +5,8 @@
5
5
 
6
6
  const { roomName, sourceName } = require(`${__hooks}/lib/anonymous.js`);
7
7
  const { asTelegram, call, transferTimeout } = require(`${__hooks}/telegram/api.js`);
8
- const { linkOfChat, linksOfRoom } = require(`${__hooks}/telegram/links.js`);
8
+ const { groupName, linkOfChat, linksOfRoom, tellRoom } = require(`${__hooks}/telegram/links.js`);
9
+ const { tidy } = require(`${__hooks}/lib/text.js`);
9
10
 
10
11
  /** Telegram's limits: a caption's length, and the largest photo it takes as a photo (bigger ones go as files). */
11
12
  const MAX_CAPTION = 1024;
@@ -24,12 +25,14 @@ const STREAM = { supports_streaming: true };
24
25
  * @param {string} op
25
26
  * @param {string} messageId
26
27
  * @param {string} chatId
28
+ * @param {Record<string, unknown>} [payload]
27
29
  */
28
- function enqueue(app, op, messageId, chatId) {
30
+ function enqueue(app, op, messageId, chatId, payload) {
29
31
  const row = new Record(app.findCollectionByNameOrId("tg_queue"));
30
32
  row.set("op", op);
31
33
  row.set("message", messageId);
32
34
  row.set("chat_id", chatId);
35
+ if (payload) row.set("payload", payload);
33
36
  app.save(row);
34
37
  }
35
38
 
@@ -50,11 +53,13 @@ function queueCreate(app, rec) {
50
53
  * change (§26.9).
51
54
  * @param {core.App} app
52
55
  * @param {core.Record} rec
53
- * @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"}
54
58
  */
55
59
  function changeOf(app, rec) {
56
60
  const orig = rec.original();
57
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";
58
63
  if (!rec.getBool("deleted") && rec.getString("text") !== orig.getString("text")) return "edit";
59
64
  if (rec.getString("reactions") !== orig.getString("reactions")) {
60
65
  const { botReaction } = require(`${__hooks}/telegram/reactions.js`);
@@ -68,14 +73,15 @@ function changeOf(app, rec) {
68
73
  * for a group isn't queued again: it sends the message's reactions as they are when it goes.
69
74
  * @param {core.App} app
70
75
  * @param {core.Record} rec
71
- * @param {"" | "edit" | "delete" | "react"} change
76
+ * @param {"" | "edit" | "delete" | "react" | "media"} change
77
+ * @param {string[]} [was] for "media": its attachments before (stored names)
72
78
  */
73
- function queueUpdate(app, rec, change) {
79
+ function queueUpdate(app, rec, change, was = []) {
74
80
  if (!change || !rec.getString("author")) return; // a service message never went to Telegram
75
81
  for (const link of linksOfRoom(app, rec.getString("room"))) {
76
82
  const chatId = link.getString("chat_id");
77
83
  if (change === "react" && waiting(app, rec.id, chatId)) continue;
78
- enqueue(app, change, rec.id, chatId);
84
+ enqueue(app, change, rec.id, chatId, change === "media" ? { was } : undefined);
79
85
  }
80
86
  }
81
87
 
@@ -192,8 +198,9 @@ function mappings(app, messageId, chatId, filter = "") {
192
198
  * @param {string} chatId
193
199
  * @param {any} sent Telegram's Message
194
200
  * @param {"text" | "caption" | "media"} kind
201
+ * @param {string[]} [files] the attachments it holds (stored names), which a media edit finds it by (editMedia)
195
202
  */
196
- function remember(app, messageId, chatId, sent, kind) {
203
+ function remember(app, messageId, chatId, sent, kind, files = []) {
197
204
  try {
198
205
  app.runInTransaction((tx) => {
199
206
  for (const old of tx.findRecordsByFilter("tg_messages", "chat_id = {:chat} && tg_message_id = {:id}", "", 0, 0, {
@@ -208,6 +215,7 @@ function remember(app, messageId, chatId, sent, kind) {
208
215
  row.set("tg_message_id", sent.message_id);
209
216
  row.set("direction", "out");
210
217
  row.set("kind", kind);
218
+ if (files.length) row.set("files", files);
211
219
  tx.save(row);
212
220
  });
213
221
  } catch (err) {
@@ -237,7 +245,7 @@ function filesOf(app, fsys, source) {
237
245
  const kind = sticker ? "sticker" : PHOTO_EXT.has(ext) && size <= MAX_PHOTO ? "photo" : VIDEO_EXT.has(ext) ? "video" : "document";
238
246
  const file = fsys.getReuploadableFile(key, true);
239
247
  file.name = names[name] || name.replace(/_[a-z0-9]{10}(\.[^.]*)?$/i, "$1");
240
- return { kind, file, size };
248
+ return { kind, file, size, name };
241
249
  });
242
250
  }
243
251
 
@@ -306,7 +314,7 @@ function send(app, messageId, chatId, done = 0, sent = () => {}) {
306
314
  * @param {core.App} app
307
315
  * @param {string} messageId
308
316
  * @param {string} chatId
309
- * @param {{ kind: string, file: any, size: number }[]} group
317
+ * @param {{ kind: string, file: any, size: number, name: string }[]} group
310
318
  * @param {Record<string, unknown> | null} caption
311
319
  * @param {Record<string, unknown>} reply
312
320
  */
@@ -320,7 +328,7 @@ function sendGroup(app, messageId, chatId, group, caption, reply) {
320
328
  { [f.kind]: f.file },
321
329
  timeout,
322
330
  );
323
- remember(app, messageId, chatId, sent, caption ? "caption" : "media");
331
+ remember(app, messageId, chatId, sent, caption ? "caption" : "media", [f.name]);
324
332
  return;
325
333
  }
326
334
  /** @type {Record<string, any>} */
@@ -335,7 +343,9 @@ function sendGroup(app, messageId, chatId, group, caption, reply) {
335
343
  };
336
344
  });
337
345
  const sent = call("sendMediaGroup", { chat_id: chatId, media, ...reply }, attach, timeout);
338
- 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
+ }
339
349
  }
340
350
 
341
351
  /**
@@ -361,6 +371,84 @@ function edit(app, messageId, chatId) {
361
371
  }
362
372
  }
363
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
+
364
452
  /**
365
453
  * Pass a delete on: delete the Telegram messages. Bots can delete their own only for 48 hours (and others' only as an
366
454
  * admin): one that stays says it was deleted instead.
@@ -390,4 +478,57 @@ function remove(app, messageId, chatId) {
390
478
  }
391
479
  }
392
480
 
393
- module.exports = { queueCreate, queueUpdate, changeOf, send, edit, remove };
481
+ /** A group's notices of undelivered messages: one in this long at most, so a group that refuses everything doesn't flood the room. */
482
+ const UNDELIVERED_GAP_MS = 5 * 60_000;
483
+ /** How much of the message's text the notice quotes, in characters. */
484
+ const UNDELIVERED_QUOTE = 40;
485
+
486
+ /**
487
+ * Why a send failed, for the room: what Telegram said ("Bad Request: chat not found", without the method), or that
488
+ * it didn't answer. Never the request itself (api.js keeps the bot's token out of its errors anyway).
489
+ * @param {unknown} err
490
+ */
491
+ function failureOf(err) {
492
+ const tg = asTelegram(err);
493
+ if (!tg) return "an error on this server";
494
+ if (tg.status === 0) return "Telegram didn't answer";
495
+ const said = tidy(tg.message.replace(/^[A-Za-z]+: /, ""));
496
+ return said ? [...said].slice(0, 200).join("") : `Telegram refused it (${tg.status})`;
497
+ }
498
+
499
+ /**
500
+ * The worker dropped a send (§26.7): the room is told, in a service message, that the message didn't reach the group
501
+ * (or only partly, or may not have), naming its author (not in an anonymous message) and quoting its text. Not when it was
502
+ * deleted meanwhile or the link no longer passes this room's messages, and once per group in UNDELIVERED_GAP_MS.
503
+ * A failure here is logged: the send is dropped whatever happens.
504
+ * @param {core.App} app
505
+ * @param {string} messageId
506
+ * @param {string} chatId
507
+ * @param {unknown} err
508
+ * @param {boolean} unsure it may have been sent (no answer, §26.7)
509
+ * @param {boolean} [partly] some of its steps were sent (its text, an album) before the one that failed
510
+ */
511
+ function tellUndelivered(app, messageId, chatId, err, unsure, partly = false) {
512
+ try {
513
+ const msg = findMessage(app, messageId);
514
+ if (!msg || msg.getBool("deleted")) return;
515
+ const link = linkOfChat(app, chatId);
516
+ if (!link?.getBool("enabled") || link.getString("room") !== msg.getString("room")) return;
517
+ const key = `telegram.undelivered.${chatId}`;
518
+ const last = Number(app.store().get(key) || 0);
519
+ if (Date.now() - last < UNDELIVERED_GAP_MS) return;
520
+ app.store().set(key, Date.now());
521
+
522
+ const author = msg.getBool("anonymous") ? "" : tidy(userName(app, msg.getString("author")));
523
+ const text = tidy(msg.getString("text"));
524
+ const chars = [...text];
525
+ const quote = chars.length ? ` ("${chars.slice(0, UNDELIVERED_QUOTE).join("")}${chars.length > UNDELIVERED_QUOTE ? "…" : ""}")` : "";
526
+ const what = `A message${author ? ` from ${author}` : ""}${quote}`;
527
+ const verb = unsure ? "may not have reached" : partly ? "only partly reached" : "wasn't delivered to";
528
+ tellRoom(app, msg.getString("room"), `${what} ${verb} ${groupName(link).replace(/^A /, "a ")}: ${failureOf(err)}.`);
529
+ } catch (e) {
530
+ app.logger().error("telegram: undelivered notice", "message", messageId, "chat", chatId, "error", String(e));
531
+ }
532
+ }
533
+
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 } = 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);
@@ -144,6 +145,7 @@ function drain(app, renew) {
144
145
  app.logger().warn(`telegram: ${op}`, "message", message, "chat", chat, "try", tries, "error", String(err));
145
146
  if (!transient || tries >= MAX_TRIES || unsure > MAX_UNSURE) {
146
147
  if (unsure > MAX_UNSURE) app.logger().warn(`telegram: ${op} dropped, it may have been sent`, "message", message, "chat", chat);
148
+ if (op === "send") tellUndelivered(app, message, chat, err, unsure > MAX_UNSURE, (payload.done || 0) > 0);
147
149
  app.delete(row);
148
150
  continue;
149
151
  }
@@ -0,0 +1,17 @@
1
+ /// <reference path="../types/pocketbase.d.ts" />
2
+ // Reactions seen in their room (DESIGN.md §41.4, 2026-11-22, user: "when reading room, new reactions should be marked
3
+ // as seen in mentions & replies"): room_reads.reactions_seen_at, when the caller last read the room (wall clock, set by
4
+ // POST /api/chat/reads). A reaction to a message read there that came before it is not new in the inbox.
5
+
6
+ migrate(
7
+ (app) => {
8
+ const reads = app.findCollectionByNameOrId("room_reads");
9
+ reads.fields.add(new DateField({ name: "reactions_seen_at" }));
10
+ app.save(reads);
11
+ },
12
+ (app) => {
13
+ const reads = app.findCollectionByNameOrId("room_reads");
14
+ reads.fields.removeByName("reactions_seen_at");
15
+ app.save(reads);
16
+ },
17
+ );
@@ -0,0 +1,20 @@
1
+ /// <reference path="../types/pocketbase.d.ts" />
2
+ // What kind of account a user is, said to clients (DESIGN.md §5.1, 2026-11-25, user: "clicking on telegram user names
3
+ // should do nothing, not show dropdown with "ban" as only option"): `users.kind` is no longer hidden, so the apps can
4
+ // tell a stand-in (a Telegram sender's, a deleted account) from a person who takes no DMs, and offer no Ban on it (the
5
+ // server refuses one, §36). Still set by hooks only (the create/update rules of migration 51).
6
+
7
+ migrate(
8
+ (app) => {
9
+ const users = app.findCollectionByNameOrId("users");
10
+ const kind = users.fields.getByName("kind");
11
+ if (kind) kind.hidden = false;
12
+ app.save(users);
13
+ },
14
+ (app) => {
15
+ const users = app.findCollectionByNameOrId("users");
16
+ const kind = users.fields.getByName("kind");
17
+ if (kind) kind.hidden = true;
18
+ app.save(users);
19
+ },
20
+ );