chirkle 0.0.0-stage → 0.2.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 (139) hide show
  1. package/LICENSE +674 -0
  2. package/README.md +326 -2
  3. package/package.json +76 -4
  4. package/pb_hooks/federation/config.js +276 -0
  5. package/pb_hooks/federation/inbox.js +316 -0
  6. package/pb_hooks/federation/messages.js +420 -0
  7. package/pb_hooks/federation/mirror.js +277 -0
  8. package/pb_hooks/federation/net.js +247 -0
  9. package/pb_hooks/federation/peers.js +490 -0
  10. package/pb_hooks/federation/people.js +376 -0
  11. package/pb_hooks/federation/rooms.js +552 -0
  12. package/pb_hooks/federation/worker.js +413 -0
  13. package/pb_hooks/federation.pb.js +141 -0
  14. package/pb_hooks/lib/access.js +102 -0
  15. package/pb_hooks/lib/account.js +31 -0
  16. package/pb_hooks/lib/anonymous.js +189 -0
  17. package/pb_hooks/lib/bulk.js +187 -0
  18. package/pb_hooks/lib/collections.js +587 -0
  19. package/pb_hooks/lib/dms.js +123 -0
  20. package/pb_hooks/lib/emoji.js +28 -0
  21. package/pb_hooks/lib/enrich.js +75 -0
  22. package/pb_hooks/lib/features.js +31 -0
  23. package/pb_hooks/lib/files.js +375 -0
  24. package/pb_hooks/lib/http.js +146 -0
  25. package/pb_hooks/lib/images.js +160 -0
  26. package/pb_hooks/lib/keepalive.js +31 -0
  27. package/pb_hooks/lib/lists.js +173 -0
  28. package/pb_hooks/lib/media.js +635 -0
  29. package/pb_hooks/lib/messages.js +519 -0
  30. package/pb_hooks/lib/moderation.js +128 -0
  31. package/pb_hooks/lib/outbound.js +116 -0
  32. package/pb_hooks/lib/pages.js +171 -0
  33. package/pb_hooks/lib/previews.js +346 -0
  34. package/pb_hooks/lib/reactions.js +110 -0
  35. package/pb_hooks/lib/reads.js +181 -0
  36. package/pb_hooks/lib/records.js +77 -0
  37. package/pb_hooks/lib/rooms.js +148 -0
  38. package/pb_hooks/lib/site.js +102 -0
  39. package/pb_hooks/lib/text.js +110 -0
  40. package/pb_hooks/lib/users.js +81 -0
  41. package/pb_hooks/lib/worker.js +159 -0
  42. package/pb_hooks/main.pb.js +324 -0
  43. package/pb_hooks/telegram/api.js +129 -0
  44. package/pb_hooks/telegram/inbound.js +553 -0
  45. package/pb_hooks/telegram/links.js +157 -0
  46. package/pb_hooks/telegram/outbound.js +352 -0
  47. package/pb_hooks/telegram/people.js +166 -0
  48. package/pb_hooks/telegram/reactions.js +137 -0
  49. package/pb_hooks/telegram/rich.js +192 -0
  50. package/pb_hooks/telegram/worker.js +182 -0
  51. package/pb_hooks/telegram.pb.js +47 -0
  52. package/pb_migrations/1760000000_init.js +150 -0
  53. package/pb_migrations/1760000001_qa_fixes.js +69 -0
  54. package/pb_migrations/1760000002_avatars.js +39 -0
  55. package/pb_migrations/1760000003_direct_messages.js +142 -0
  56. package/pb_migrations/1760000004_attachments.js +28 -0
  57. package/pb_migrations/1760000005_file_names.js +16 -0
  58. package/pb_migrations/1760000006_room_reads.js +41 -0
  59. package/pb_migrations/1760000007_replies.js +23 -0
  60. package/pb_migrations/1760000008_lowercase_emails.js +24 -0
  61. package/pb_migrations/1760000009_reactions.js +32 -0
  62. package/pb_migrations/1760000010_fit_thumbs.js +18 -0
  63. package/pb_migrations/1760000011_forwarding.js +39 -0
  64. package/pb_migrations/1760000012_accounts.js +55 -0
  65. package/pb_migrations/1760000013_qa_pass5.js +19 -0
  66. package/pb_migrations/1760000014_room_access.js +96 -0
  67. package/pb_migrations/1760000015_site.js +46 -0
  68. package/pb_migrations/1760000016_forward_refs.js +43 -0
  69. package/pb_migrations/1760000017_no_dms.js +18 -0
  70. package/pb_migrations/1760000018_attachment_limits.js +24 -0
  71. package/pb_migrations/1760000019_telegram.js +109 -0
  72. package/pb_migrations/1760000020_service_messages.js +21 -0
  73. package/pb_migrations/1760000021_forward_view_index.js +41 -0
  74. package/pb_migrations/1760000022_link_previews.js +43 -0
  75. package/pb_migrations/1760000023_room_writers.js +49 -0
  76. package/pb_migrations/1760000024_message_search.js +51 -0
  77. package/pb_migrations/1760000025_search_dotted_i.js +16 -0
  78. package/pb_migrations/1760000026_push.js +67 -0
  79. package/pb_migrations/1760000027_push_tokens_per_user.js +31 -0
  80. package/pb_migrations/1760000028_media_grid_thumbs.js +18 -0
  81. package/pb_migrations/1760000029_media.js +71 -0
  82. package/pb_migrations/1760000030_collections.js +140 -0
  83. package/pb_migrations/1760000031_unread_limit.js +20 -0
  84. package/pb_migrations/1760000032_federation.js +227 -0
  85. package/pb_migrations/1760000033_federation_requests.js +44 -0
  86. package/pb_migrations/1760000034_telegram_parts.js +26 -0
  87. package/pb_migrations/1760000035_telegram_anonymous.js +16 -0
  88. package/pb_migrations/1760000036_chirkle.js +20 -0
  89. package/pb_migrations/1760000037_file_dims.js +35 -0
  90. package/pb_migrations/1760000038_drop_push.js +64 -0
  91. package/pb_migrations/1760000039_anonymous_rooms.js +40 -0
  92. package/pb_migrations/1760000040_moderators.js +42 -0
  93. package/pb_migrations/1760000041_shared_files.js +500 -0
  94. package/pb_migrations/1760000042_files_src.js +17 -0
  95. package/pb_migrations/1760000043_telegram_reactions.js +21 -0
  96. package/pb_public/assets/access-ALBW2MT2.js +2 -0
  97. package/pb_public/assets/access-ALBW2MT2.js.map +7 -0
  98. package/pb_public/assets/access-PB77EH4F.css +2 -0
  99. package/pb_public/assets/access-PB77EH4F.css.map +7 -0
  100. package/pb_public/assets/app-A3SXD3FF.css +2 -0
  101. package/pb_public/assets/app-A3SXD3FF.css.map +7 -0
  102. package/pb_public/assets/app-NDSIQW4L.js +3 -0
  103. package/pb_public/assets/app-NDSIQW4L.js.map +7 -0
  104. package/pb_public/assets/collections-DHJEOLHW.css +2 -0
  105. package/pb_public/assets/collections-DHJEOLHW.css.map +7 -0
  106. package/pb_public/assets/emoji-WSTVXAW5.css +2 -0
  107. package/pb_public/assets/emoji-WSTVXAW5.css.map +7 -0
  108. package/pb_public/assets/emoji-picker-QYRX6NYL.js +609 -0
  109. package/pb_public/assets/emoji-picker-QYRX6NYL.js.map +7 -0
  110. package/pb_public/assets/inter-cyrillic-JEOLYBOO.woff2 +0 -0
  111. package/pb_public/assets/inter-cyrillic-ext-IYF56FF6.woff2 +0 -0
  112. package/pb_public/assets/inter-greek-IRE366VL.woff2 +0 -0
  113. package/pb_public/assets/inter-latin-NRMW37G5.woff2 +0 -0
  114. package/pb_public/assets/inter-latin-ext-HA22NDSG.woff2 +0 -0
  115. package/pb_public/assets/lazy-4CXRBHHM.js +2 -0
  116. package/pb_public/assets/lazy-4CXRBHHM.js.map +7 -0
  117. package/pb_public/assets/media-7TCBG7WM.css +2 -0
  118. package/pb_public/assets/media-7TCBG7WM.css.map +7 -0
  119. package/pb_public/assets/media-FPRU2QH5.js +2 -0
  120. package/pb_public/assets/media-FPRU2QH5.js.map +7 -0
  121. package/pb_public/assets/notify-L6GERFNO.js +2 -0
  122. package/pb_public/assets/notify-L6GERFNO.js.map +7 -0
  123. package/pb_public/assets/search-3UT4HMES.js +2 -0
  124. package/pb_public/assets/search-3UT4HMES.js.map +7 -0
  125. package/pb_public/assets/switcher-CEUKRLEY.js +2 -0
  126. package/pb_public/assets/switcher-CEUKRLEY.js.map +7 -0
  127. package/pb_public/assets/viewer-DXT7SKOU.js +2 -0
  128. package/pb_public/assets/viewer-DXT7SKOU.js.map +7 -0
  129. package/pb_public/assets/viewer-P7GYCBYM.css +2 -0
  130. package/pb_public/assets/viewer-P7GYCBYM.css.map +7 -0
  131. package/pb_public/icons/apple-touch-icon.png +0 -0
  132. package/pb_public/icons/icon-192.png +0 -0
  133. package/pb_public/icons/icon-512.png +0 -0
  134. package/pb_public/icons/icon.svg +1 -0
  135. package/pb_public/icons/maskable-512.png +0 -0
  136. package/pb_public/index.html +21 -0
  137. package/pb_public/sw.js +1 -0
  138. package/scripts/fetch-pocketbase.sh +63 -0
  139. package/scripts/start.mjs +93 -0
@@ -0,0 +1,635 @@
1
+ /// <reference path="../../types/pocketbase.d.ts" />
2
+ // The media grid's server side (DESIGN.md §30.1).
3
+ //
4
+ // - The index: the `media` collection, one row per image or video a room shows (pb_migrations/1760000029_media.js).
5
+ // A new message adds its rows in the save's transaction (a forward, its original's files); a delete takes them out,
6
+ // with those of the message's forwards. Deleted for good (a room, a superuser): the relations cascade.
7
+ // - GET /api/chat/media/{room}: a page of a room's rows, newest first, checked against the room once. The grid used to
8
+ // page through the room's messages with the full list rule, expands and enrich hook, for a few tiles a page.
9
+ // - The worker (a cron job, like the previews'): makes each new file's thumbnails before anyone asks for them, and a
10
+ // poster frame for each video with ffmpeg, so the room (§17.5) and the grid show an image instead of loading every
11
+ // video. PocketBase otherwise makes a thumbnail on its first request: a grid opened over old images made dozens at
12
+ // once. Each file once, as a `files` row (§37), whichever messages and collection items name it. Then it records
13
+ // each video's shape (its poster's) on its row and in the `file_dims` of the messages that show it, and those of
14
+ // files sent before there were any (§17.5): a new image's the upload already has. Between the two, it moves the files
15
+ // the move to shared files (§37.5) left in the messages' and items' old folders to their own, and last, it deletes
16
+ // what is left in the old places (`storage_cleanup`).
17
+ // - GET /api/chat/posters/{message}/{file}: a video's poster, for whoever has the video's URL (§37.3).
18
+
19
+ const { gridAuthor } = require(`${__hooks}/lib/anonymous.js`);
20
+ const { visibleRoom } = require(`${__hooks}/lib/access.js`);
21
+ const { HEADER_BYTES, shownSize } = require(`${__hooks}/lib/images.js`);
22
+ const { cleanupLater, ext, homeKeyOf, isMedia, isVideo, keyOf, posterKeyOf, shownBy, thumbsDirOf } = require(`${__hooks}/lib/files.js`);
23
+
24
+ /** The images PocketBase makes thumbnails of (avif it serves as it is). */
25
+ const THUMB_EXT = ["jpg", "jpeg", "png", "gif", "webp"];
26
+ /** The grid's tiles (§30.1). */
27
+ const GRID_THUMB = "240x240";
28
+ /** ffmpeg's demuxer for each video type: never left to guess, so a "video" that is a playlist reads no other file. */
29
+ /** @type {Record<string, string>} */
30
+ const DEMUXER = { mp4: "mov", m4v: "mov", mov: "mov", webm: "matroska", ogv: "ogg" };
31
+ /** The poster fits in this (never enlarged), in the video's own shape: the room's large tile (§17.5, as "800x480f"). The grid crops it to its square. */
32
+ const POSTER_FIT = { w: 800, h: 480 };
33
+ const POSTER = "poster.jpg";
34
+ /** ffmpeg is stopped after this long (s): a file that takes longer gets no poster. */
35
+ const FFMPEG_SECONDS = 20;
36
+ /** A file this recent is still being read in the room: all of its thumbnails are made, not just the grid's. */
37
+ const RECENT_MS = 7 * 86_400_000;
38
+
39
+ const LOCK = "media.worker";
40
+ const STALE_MS = 120_000;
41
+ const BATCH = 10;
42
+
43
+ /** The grid's page, and the most a request may ask for. */
44
+ const PAGE = 60;
45
+ const MAX_PAGE = 100;
46
+
47
+ // ---------------------------------------------------------------- the index
48
+
49
+ /**
50
+ * A message just saved (created): its rows, in the save's transaction. A forward's are its original's files.
51
+ * @param {core.App} app
52
+ * @param {core.Record} rec
53
+ */
54
+ function add(app, rec) {
55
+ if (rec.getBool("deleted")) return;
56
+ const forward = rec.getString("forward_of");
57
+ let source = rec;
58
+ if (forward) {
59
+ try {
60
+ source = app.findRecordById("messages", forward);
61
+ } catch {
62
+ return;
63
+ }
64
+ if (source.getBool("deleted")) return;
65
+ }
66
+ source.getStringSlice("files").forEach((file, pos) => {
67
+ if (!isMedia(file)) return;
68
+ app
69
+ .db()
70
+ .newQuery(
71
+ `INSERT INTO media (id, room, message, source, file, pos, video, sent)
72
+ VALUES ({:id}, {:room}, {:message}, {:source}, {:file}, {:pos}, {:video}, {:sent})`,
73
+ )
74
+ .bind({
75
+ id: $security.randomStringWithAlphabet(15, "abcdefghijklmnopqrstuvwxyz0123456789"),
76
+ room: rec.getString("room"),
77
+ message: rec.id,
78
+ source: source.id,
79
+ file,
80
+ pos,
81
+ video: isVideo(file),
82
+ sent: rec.getString("created"),
83
+ })
84
+ .execute();
85
+ });
86
+ }
87
+
88
+ /**
89
+ * A message deleted (soft, §5.3): its rows go, and its forwards' (they show nothing now, §21.3).
90
+ * @param {core.App} app
91
+ * @param {string} id
92
+ */
93
+ function drop(app, id) {
94
+ app.db().newQuery("DELETE FROM media WHERE message = {:id} OR source = {:id}").bind({ id }).execute();
95
+ }
96
+
97
+ // ---------------------------------------------------------------- the grid's page
98
+
99
+ /**
100
+ * GET /api/chat/media/{room}?sent=&message=&pos=&limit=: the room's images and videos older than the one given (or the
101
+ * newest), newest first, a message's files last to first. 404 for a room you can't see.
102
+ * @param {core.RequestEvent} e
103
+ */
104
+ function list(e) {
105
+ const room = e.request?.pathValue("room") ?? "";
106
+ if (!visibleRoom(e.app, room, e.auth?.id ?? "")) throw new NotFoundError();
107
+ const q = e.request?.url?.query();
108
+ const sent = q?.get("sent") ?? "";
109
+ const limit = Math.min(MAX_PAGE, Math.max(1, Number.parseInt(q?.get("limit") ?? "", 10) || PAGE));
110
+ const before = sent
111
+ ? "AND (md.sent < {:sent} OR (md.sent = {:sent} AND (md.message < {:message} OR (md.message = {:message} AND md.pos < {:pos}))))"
112
+ : "";
113
+ const rows = arrayOf(
114
+ new DynamicModel({
115
+ message: "",
116
+ source: "",
117
+ file: "",
118
+ pos: 0,
119
+ video: false,
120
+ poster: false,
121
+ sent: "",
122
+ names: "",
123
+ author: "",
124
+ name: "",
125
+ anonymous: false,
126
+ }),
127
+ );
128
+ e.app
129
+ .db()
130
+ .newQuery(
131
+ `SELECT md.message, md.source, md.file, md.pos, md.video, COALESCE(f.poster, FALSE) AS poster, md.sent,
132
+ COALESCE(s.file_names, '') AS names, m.author, COALESCE(u.name, '') AS name, m.anonymous
133
+ FROM media md
134
+ JOIN messages m ON m.id = md.message
135
+ JOIN messages s ON s.id = md.source
136
+ LEFT JOIN files f ON f.file = md.file
137
+ LEFT JOIN users u ON u.id = m.author
138
+ WHERE md.room = {:room} ${before} AND m.deleted = FALSE AND s.deleted = FALSE
139
+ ORDER BY md.sent DESC, md.message DESC, md.pos DESC
140
+ LIMIT {:n}`,
141
+ )
142
+ .bind({ room, sent, message: q?.get("message") ?? "", pos: Number.parseInt(q?.get("pos") ?? "", 10) || 0, n: limit + 1 })
143
+ .all(rows);
144
+ const items = rows.slice(0, limit).map((r) => {
145
+ /** @type {Record<string, string>} */
146
+ let names = {};
147
+ try {
148
+ names = JSON.parse(r.names || "{}") ?? {};
149
+ } catch {
150
+ // older messages have none (QA BUG-28)
151
+ }
152
+ return {
153
+ message: r.message,
154
+ source: r.source,
155
+ file: r.file,
156
+ pos: r.pos,
157
+ name: typeof names[r.file] === "string" ? names[r.file] : "",
158
+ video: !!r.video,
159
+ poster: !!r.poster,
160
+ sent: r.sent,
161
+ author: gridAuthor(e, { author: r.author, name: r.name, anonymous: !!r.anonymous, room }),
162
+ };
163
+ });
164
+ return e.json(200, { items, more: rows.length > limit });
165
+ }
166
+
167
+ // ---------------------------------------------------------------- posters
168
+
169
+ /**
170
+ * GET /api/chat/posters/{message}/{file}: a video's poster frame, for whoever has the video's URL (§37.3): the message
171
+ * (or as a forward, its original) shows the file. A `token` is ignored. 404 for anything else, and until the worker
172
+ * has made it.
173
+ * @param {core.RequestEvent} e
174
+ */
175
+ function poster(e) {
176
+ servePoster(e, "messages", e.request?.pathValue("message") ?? "");
177
+ }
178
+
179
+ /**
180
+ * GET /api/chat/posters/items/{item}/{file}: a collection item's poster (§31), as the item's file is served.
181
+ * @param {core.RequestEvent} e
182
+ */
183
+ function itemPoster(e) {
184
+ servePoster(e, "collection_items", e.request?.pathValue("item") ?? "");
185
+ }
186
+
187
+ /**
188
+ * The poster of the video `file` that record `id` of `collection` shows.
189
+ * @param {core.RequestEvent} e
190
+ * @param {string} collection
191
+ * @param {string} id
192
+ */
193
+ function servePoster(e, collection, id) {
194
+ const file = e.request?.pathValue("file") ?? "";
195
+ const row = isVideo(file) ? shownBy(e.app, collection, id, file) : null;
196
+ if (!row) throw new NotFoundError();
197
+ const fs = e.app.newFilesystem();
198
+ try {
199
+ const key = posterKeyOf(row);
200
+ if (!fs.exists(key)) throw new NotFoundError();
201
+ // Never changes under one name: a new upload gets a new file name.
202
+ e.response.header().set("Cache-Control", "private, max-age=2592000");
203
+ fs.serve(e.response, /** @type {any} */ (e.request), key, POSTER);
204
+ } finally {
205
+ fs.close();
206
+ }
207
+ }
208
+
209
+ // ---------------------------------------------------------------- the worker
210
+
211
+ /** The ffmpeg command ("ffmpeg", or FFMPEG), "" when there is none (FFMPEG=off, not installed). Looked up once. */
212
+ function ffmpeg(/** @type {core.App} */ app) {
213
+ return /** @type {string} */ (
214
+ app.store().getOrSet("media.ffmpeg", () => {
215
+ const bin = $os.getenv("FFMPEG").trim() || "ffmpeg";
216
+ if (bin.toLowerCase() === "off") return "";
217
+ try {
218
+ $os.cmd("timeout", "10", bin, "-hide_banner", "-loglevel", "error", "-version").output();
219
+ return bin;
220
+ } catch {
221
+ app.logger().warn("media: no ffmpeg, videos get no poster", "command", bin);
222
+ return "";
223
+ }
224
+ })
225
+ );
226
+ }
227
+
228
+ /**
229
+ * A copy of a stored file in the temp folder, for ffmpeg: files kept in S3 have no path of their own. Copied by Go
230
+ * (`readFrom`), so the video never passes through JS. Returns its path; the caller removes it.
231
+ * @param {filesystem.System} fs
232
+ * @param {string} key
233
+ * @param {string} file
234
+ */
235
+ function tempCopy(fs, key, file) {
236
+ const dir = $os.tempDir();
237
+ const name = `chirkle-poster-${$security.randomString(16)}.${ext(file)}`;
238
+ const root = $os.openRoot(dir);
239
+ try {
240
+ const out = root.create(name);
241
+ try {
242
+ const reader = fs.getReader(key);
243
+ try {
244
+ out.readFrom(reader);
245
+ } finally {
246
+ reader.close();
247
+ }
248
+ } catch (err) {
249
+ out.close();
250
+ root.remove(name);
251
+ throw err;
252
+ }
253
+ out.close();
254
+ } finally {
255
+ root.close();
256
+ }
257
+ return `${dir}/${name}`;
258
+ }
259
+
260
+ /**
261
+ * A poster for a stored video, or null when it can't have one (no ffmpeg, ffmpeg failed). A video kept in S3 is
262
+ * downloaded to the temp folder first, and removed after.
263
+ * @param {core.App} app
264
+ * @param {filesystem.System} fs
265
+ * @param {string} key
266
+ * @param {string} file
267
+ */
268
+ function posterOf(app, fs, key, file) {
269
+ const bin = ffmpeg(app);
270
+ if (!bin) return null;
271
+ const s3 = app.settings().s3.enabled;
272
+ const path = s3 ? tempCopy(fs, key, file) : `${app.dataDir()}/storage/${key}`;
273
+ try {
274
+ return frame(bin, path, file);
275
+ } finally {
276
+ if (s3) $os.remove(path);
277
+ }
278
+ }
279
+
280
+ /**
281
+ * The first frame of the video at `path` (a local file), fitted in POSTER_FIT, as JPEG; null if ffmpeg gave nothing.
282
+ * @param {string} bin
283
+ * @param {string} path
284
+ * @param {string} file
285
+ */
286
+ function frame(bin, path, file) {
287
+ const { w, h } = POSTER_FIT;
288
+ // Its first frame, fitted, as JPEG on stdout. Only the local file: no protocols but `file`, no
289
+ // external references (the mov demuxer's drefs are off by default), the container's own demuxer, one thread.
290
+ const out = $os
291
+ .cmd(
292
+ "timeout",
293
+ String(FFMPEG_SECONDS),
294
+ bin,
295
+ "-nostdin",
296
+ "-hide_banner",
297
+ "-loglevel",
298
+ "error",
299
+ "-threads",
300
+ "1",
301
+ "-protocol_whitelist",
302
+ "file",
303
+ "-f",
304
+ DEMUXER[ext(file)] ?? "mov",
305
+ "-i",
306
+ `file:${path}`,
307
+ "-map",
308
+ "0:v:0",
309
+ "-frames:v",
310
+ "1",
311
+ "-an",
312
+ "-sn",
313
+ "-dn",
314
+ "-vf",
315
+ `scale=w='min(${w},iw)':h='min(${h},ih)':force_original_aspect_ratio=decrease`,
316
+ "-q:v",
317
+ "5",
318
+ "-f",
319
+ "image2",
320
+ "-c:v",
321
+ "mjpeg",
322
+ "pipe:1",
323
+ )
324
+ .output();
325
+ return out?.length ? out : null;
326
+ }
327
+
328
+ /**
329
+ * The thumbnails one file needs: the grid's, and for a recent file the room's too (§17.5); a video, its poster. Made
330
+ * only if missing.
331
+ * @param {core.App} app
332
+ * @param {filesystem.System} fs
333
+ * @param {core.Record} row a `files` row
334
+ */
335
+ function thumbs(app, fs, row) {
336
+ const file = row.getString("file");
337
+ const key = keyOf(row);
338
+ if (!fs.exists(key)) return; // deleted meanwhile
339
+ if (isVideo(file)) {
340
+ const target = posterKeyOf(row);
341
+ if (fs.exists(target)) return markPoster(app, row);
342
+ const bytes = posterOf(app, fs, key, file);
343
+ if (!bytes) return;
344
+ fs.uploadFile($filesystem.fileFromBytes(bytes, POSTER), target);
345
+ // Deleted while ffmpeg ran: PocketBase has already removed its folder, and would leave this one behind.
346
+ if (!fs.exists(key)) return fs.delete(target);
347
+ markPoster(app, row);
348
+ return;
349
+ }
350
+ if (!THUMB_EXT.includes(ext(file))) return;
351
+ const all = /** @type {any} */ (row.collection().fields.getByName("file")).thumbs ?? [];
352
+ const recent = Date.now() - new Date(row.getString("created").replace(" ", "T")).getTime() < RECENT_MS;
353
+ // A GIF shows itself in the room (§17.5): only the grid shows its thumbnail.
354
+ const sizes = recent && ext(file) !== "gif" ? all : all.filter((/** @type {string} */ s) => s === GRID_THUMB);
355
+ for (const size of sizes) {
356
+ const thumb = `${row.baseFilesPath()}/thumbs_${file}/${size}_${file}`;
357
+ if (!fs.exists(thumb)) fs.createThumb(key, thumb, size);
358
+ }
359
+ }
360
+
361
+ /**
362
+ * A file's poster is there: its row says so, and the collection items naming it; their collections are saved again
363
+ * (unchanged), so the room lists showing their tiles (GET /api/chat/collections' `preview`) hear of it live and ask
364
+ * again, as they do when an item is added (QA BUG-207).
365
+ * @param {core.App} app
366
+ * @param {core.Record} row
367
+ */
368
+ function markPoster(app, row) {
369
+ const file = row.getString("file");
370
+ app.db().newQuery("UPDATE files SET poster = TRUE WHERE id = {:id}").bind({ id: row.id }).execute();
371
+ app.db().newQuery("UPDATE collection_items SET poster = TRUE WHERE file = {:file}").bind({ file }).execute();
372
+ const ids = arrayOf(new DynamicModel({ collection: "" }));
373
+ app.db().newQuery("SELECT DISTINCT collection FROM collection_items WHERE file = {:file}").bind({ file }).all(ids);
374
+ for (const { collection } of ids) {
375
+ try {
376
+ app.save(app.findRecordById("collections", collection));
377
+ } catch (err) {
378
+ app.logger().warn("media: item poster", "collection", collection, "error", String(err));
379
+ }
380
+ }
381
+ }
382
+
383
+ /**
384
+ * One pass: the newest files not done yet (a new upload goes before the old ones). After each file the worker rests
385
+ * as long as it worked, so it never takes more than half of one CPU. `beat`, if given, is called after each one (the
386
+ * worker renews its lock). Returns how many it looked at.
387
+ * @param {core.App} app
388
+ * @param {() => void} [beat]
389
+ * @param {boolean} [rest]
390
+ */
391
+ function pass(app, beat, rest = true) {
392
+ // A file not moved yet (src) once it is: its thumbnails are made in its own folder.
393
+ const rows = app.findRecordsByFilter("files", "ready = false && src = ''", "-created", BATCH, 0);
394
+ if (!rows.length) return movePass(app, beat, rest) || sizePass(app, beat, rest) || cleanupPass(app, beat);
395
+ const fs = app.newFilesystem();
396
+ try {
397
+ for (const row of rows) {
398
+ if (!row) continue;
399
+ const start = Date.now();
400
+ try {
401
+ thumbs(app, fs, row);
402
+ } catch (err) {
403
+ app.logger().warn("media: thumbnails", "file", row.getString("file"), "error", String(err));
404
+ }
405
+ // Tried once: a file that fails now would fail again.
406
+ app.db().newQuery("UPDATE files SET ready = TRUE WHERE id = {:id}").bind({ id: row.id }).execute();
407
+ beat?.();
408
+ if (rest) sleep(Math.min(2000, Date.now() - start));
409
+ }
410
+ } finally {
411
+ fs.close();
412
+ }
413
+ return rows.length;
414
+ }
415
+
416
+ /**
417
+ * As pass, once the thumbnails are done: the shapes (§17.5) of videos, from their posters, and of files sent before
418
+ * messages kept them. Returns how many it looked at.
419
+ * @param {core.App} app
420
+ * @param {() => void} [beat]
421
+ * @param {boolean} [rest]
422
+ */
423
+ function sizePass(app, beat, rest = true) {
424
+ const rows = app.findRecordsByFilter("files", "sized = false && src = ''", "-created", BATCH, 0);
425
+ if (!rows.length) return 0;
426
+ const fs = app.newFilesystem();
427
+ try {
428
+ for (const row of rows) {
429
+ if (!row) continue;
430
+ const start = Date.now();
431
+ const file = row.getString("file");
432
+ try {
433
+ const size = isMedia(file) ? shapeOf(fs, isVideo(file) ? posterKeyOf(row) : keyOf(row)) : null;
434
+ if (size) setDims(app, row, size);
435
+ } catch (err) {
436
+ app.logger().warn("media: shape", "file", file, "error", String(err));
437
+ }
438
+ // Once: without a poster (no ffmpeg) or a readable header, the room shows it as before.
439
+ app.db().newQuery("UPDATE files SET sized = TRUE WHERE id = {:id}").bind({ id: row.id }).execute();
440
+ beat?.();
441
+ if (rest) sleep(Math.min(2000, Date.now() - start));
442
+ }
443
+ } finally {
444
+ fs.close();
445
+ }
446
+ return rows.length;
447
+ }
448
+
449
+ /**
450
+ * Files the move to shared files (§37.5) left where they were (`src`): each copied to its own folder with what is
451
+ * beside it (thumbnails, poster), then its row points there and the old place is left to cleanupPass. Until then it is
452
+ * served from where it is (lib/files.js serve). Returns how many it looked at.
453
+ * @param {core.App} app
454
+ * @param {() => void} [beat]
455
+ * @param {boolean} [rest]
456
+ */
457
+ function movePass(app, beat, rest = true) {
458
+ const rows = app.findRecordsByFilter("files", "src != ''", "created", BATCH, 0);
459
+ if (!rows.length) return 0;
460
+ const fs = app.newFilesystem();
461
+ try {
462
+ for (const row of rows) {
463
+ if (!row) continue;
464
+ const start = Date.now();
465
+ try {
466
+ move(app, fs, row);
467
+ } catch (err) {
468
+ app.logger().warn("media: move", "file", row.getString("file"), "from", row.getString("src"), "error", String(err));
469
+ }
470
+ beat?.();
471
+ if (rest) sleep(Math.min(2000, Date.now() - start));
472
+ }
473
+ } finally {
474
+ fs.close();
475
+ }
476
+ return rows.length;
477
+ }
478
+
479
+ /**
480
+ * One file's move (movePass). A file not there any more (gone before the move) is left as it is: its row keeps
481
+ * pointing at nothing, as the message's did. A file renamed by the migration (a name two records had) gets new
482
+ * thumbnails: those beside it carry the old name.
483
+ * @param {core.App} app
484
+ * @param {filesystem.System} fs
485
+ * @param {core.Record} row
486
+ */
487
+ function move(app, fs, row) {
488
+ const src = row.getString("src");
489
+ const home = homeKeyOf(row);
490
+ const renamed = src.slice(src.lastIndexOf("/") + 1) !== row.getString("file");
491
+ const there = fs.exists(src);
492
+ if (there) {
493
+ fs.copy(src, home);
494
+ if (!renamed) {
495
+ const from = thumbsDirOf(src);
496
+ const to = thumbsDirOf(home);
497
+ for (const obj of fs.list(from)) {
498
+ if (obj && !obj.key.endsWith(".attrs")) fs.copy(obj.key, to + obj.key.slice(from.length));
499
+ }
500
+ }
501
+ }
502
+ let moved = false;
503
+ app.runInTransaction((tx) => {
504
+ let now;
505
+ try {
506
+ now = tx.findRecordById("files", row.id);
507
+ } catch {
508
+ return; // deleted meanwhile: unlink left its old place to cleanupPass
509
+ }
510
+ if (now.getString("src") !== src) return;
511
+ tx.db()
512
+ .newQuery("UPDATE files SET src = '', ready = ready AND {:keep}, poster = poster AND {:keep} WHERE id = {:id}")
513
+ .bind({ id: row.id, keep: there && !renamed })
514
+ .execute();
515
+ if (there) cleanupLater(tx, src);
516
+ moved = true;
517
+ });
518
+ // Deleted while it was copied: PocketBase removed its folder before the copy was there.
519
+ if (!moved && there) fs.deletePrefix(`${home.slice(0, home.lastIndexOf("/"))}/`);
520
+ }
521
+
522
+ /**
523
+ * What the move to shared files (§37) left in the old places of messages' and collection items' files: deleted a
524
+ * few at a time, once the move is committed. A prefix is a record's folder, or a file (which goes with its
525
+ * thumbnails). Returns how many it looked at.
526
+ * @param {core.App} app
527
+ * @param {() => void} [beat]
528
+ */
529
+ function cleanupPass(app, beat) {
530
+ const rows = arrayOf(new DynamicModel({ id: "", prefix: "" }));
531
+ app.db().newQuery("SELECT id, prefix FROM storage_cleanup LIMIT {:n}").bind({ n: BATCH }).all(rows);
532
+ if (!rows.length) return 0;
533
+ const fs = app.newFilesystem();
534
+ try {
535
+ for (const row of rows) {
536
+ // A folder of its own (collection/record), never a shorter one; or one file in one.
537
+ if (/^[a-z0-9_]+\/[a-z0-9]+$/i.test(row.prefix)) {
538
+ const errs = fs.deletePrefix(`${row.prefix}/`);
539
+ for (const err of errs ?? []) if (err) app.logger().warn("media: cleanup", "prefix", row.prefix, "error", String(err));
540
+ } else if (/^[a-z0-9_]+\/[a-z0-9]+\/[^/]+$/i.test(row.prefix)) {
541
+ try {
542
+ if (fs.exists(row.prefix)) fs.delete(row.prefix);
543
+ const errs = fs.deletePrefix(thumbsDirOf(row.prefix));
544
+ for (const err of errs ?? []) if (err) app.logger().warn("media: cleanup", "prefix", row.prefix, "error", String(err));
545
+ // The record's old folder, once its last file has gone (an empty folder stays on a local disk).
546
+ const dir = `${row.prefix.slice(0, row.prefix.lastIndexOf("/"))}/`;
547
+ if (!fs.list(dir).length) fs.deletePrefix(dir);
548
+ } catch (err) {
549
+ app.logger().warn("media: cleanup", "prefix", row.prefix, "error", String(err));
550
+ }
551
+ }
552
+ app.db().newQuery("DELETE FROM storage_cleanup WHERE id = {:id}").bind({ id: row.id }).execute();
553
+ beat?.();
554
+ }
555
+ } finally {
556
+ fs.close();
557
+ }
558
+ return rows.length;
559
+ }
560
+
561
+ /**
562
+ * The shape the stored image at `key` is shown in, from its header; null if it isn't there or isn't readable.
563
+ * @param {filesystem.System} fs
564
+ * @param {string} key
565
+ */
566
+ function shapeOf(fs, key) {
567
+ if (!fs.exists(key)) return null;
568
+ const reader = fs.getReader(key);
569
+ try {
570
+ return shownSize(toBytes(reader, HEADER_BYTES));
571
+ } finally {
572
+ reader.close();
573
+ }
574
+ }
575
+
576
+ /**
577
+ * Record a file's shape on its row, and in the `file_dims` of every message that has it (the media index knows
578
+ * them). Not a save: no hooks, no realtime event, `updated` unchanged (clients have it from the next load; until then
579
+ * the tile takes its width once loaded, as before).
580
+ * @param {core.App} app
581
+ * @param {core.Record} row
582
+ * @param {[number, number]} size
583
+ */
584
+ function setDims(app, row, size) {
585
+ const file = row.getString("file");
586
+ app
587
+ .db()
588
+ .newQuery("UPDATE files SET dims = json_array({:w}, {:h}) WHERE id = {:id}")
589
+ .bind({ id: row.id, w: size[0], h: size[1] })
590
+ .execute();
591
+ app
592
+ .db()
593
+ .newQuery(
594
+ `UPDATE messages SET file_dims = json_set(
595
+ CASE WHEN json_valid(file_dims) THEN (CASE WHEN json_type(file_dims) = 'object' THEN file_dims ELSE '{}' END) ELSE '{}' END,
596
+ {:path}, json_array({:w}, {:h}))
597
+ WHERE id IN (SELECT DISTINCT source FROM media WHERE file = {:file})`,
598
+ )
599
+ .bind({ file, path: `$."${file}"`, w: size[0], h: size[1] })
600
+ .execute();
601
+ }
602
+
603
+ /**
604
+ * The cron job: passes until the minute is nearly over; with nothing to do, when a save wakes it (wake). One run at a
605
+ * time.
606
+ * @param {core.App} app
607
+ */
608
+ function run(app) {
609
+ require(`${__hooks}/lib/worker.js`).run(app, {
610
+ name: LOCK,
611
+ label: "media",
612
+ staleMs: STALE_MS,
613
+ wakes: true,
614
+ pass: (/** @type {() => void} */ renew) => pass(app, renew),
615
+ });
616
+ }
617
+
618
+ /**
619
+ * A message with files, or a collection item, was saved (committed): the worker looks at its files now.
620
+ * @param {core.App} app
621
+ */
622
+ function wake(app) {
623
+ require(`${__hooks}/lib/worker.js`).wake(app, LOCK);
624
+ }
625
+
626
+ /**
627
+ * POST /api/media/tick (superusers): every file not done yet, now (tests).
628
+ * @param {core.RequestEvent} e
629
+ */
630
+ function tick(e) {
631
+ while (pass(e.app, undefined, false) > 0);
632
+ return e.noContent(204);
633
+ }
634
+
635
+ module.exports = { add, drop, list, poster, itemPoster, run, wake, tick };