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,587 @@
1
+ /// <reference path="../../types/pocketbase.d.ts" />
2
+ // Media collections (DESIGN.md §31): pb_migrations/1760000030_collections.js has the data.
3
+ //
4
+ // - collections hooks: a clean name, unique among the owner's (case folded), at most MAX_COLLECTIONS each; when one
5
+ // turns private or public, its subscribers hear of it (their own collection_subs rows are saved again). When one
6
+ // turns private or public, is renamed or is deleted, every client listening to BADGES_TOPIC hears its id.
7
+ // - POST /api/chat/items: a message's image or video (or another collection's item) in a collection of yours, or
8
+ // (multipart { collection, file }) an image or video uploaded straight into one. DELETE
9
+ // /api/chat/items/{id}: the owner takes one out. GET /api/chat/saved?message=&file= (or ?item=): which of your
10
+ // collections have that file already.
11
+ // - Messages: a create may name collection items (`items`) whose files it attaches (itemsToAttach), and file_sources
12
+ // says which collection each came from.
13
+ // - GET /api/chat/collections: yours and the public ones you follow, with how many items are new in those.
14
+ // - GET /api/chat/badges?ids=: what a message's "from collection" badge may say about each collection.
15
+ // - POST /api/chat/subs { collection, on }: follow or stop following; POST /api/chat/subs/seen { collection, at? }:
16
+ // seen up to `at`, as POST /api/chat/reads does for a room (§18.2).
17
+ //
18
+ // Nothing is copied (§37): an item names the same `files` row as the message it was saved from, and a message the
19
+ // same as the item it attached (lib/files.js). An item's `origin` is its file's row: a file is in a collection once.
20
+
21
+ const { cleanName, fieldError, recordOf } = require(`${__hooks}/lib/records.js`);
22
+ const { clipFileName, nameKey, tidy, unescapeUploadName } = require(`${__hooks}/lib/text.js`);
23
+ const files = require(`${__hooks}/lib/files.js`);
24
+
25
+ const MAX_COLLECTIONS = 50;
26
+ const MAX_ITEMS = 2000;
27
+ const MAX_SUBS = 200;
28
+ /** As UNREAD_CAP (§18.2): the badge shows "99+" past 99. */
29
+ const NEW_CAP = 100;
30
+ /** How many of its newest items a collection's tile in the room list shows. */
31
+ const PREVIEW_ITEMS = 4;
32
+ /** The realtime topic that hears a collection's id when what its badge says may have changed (§31). */
33
+ const BADGES_TOPIC = "chat/badges";
34
+ const MAX_BADGES = 50;
35
+
36
+ /** @param {core.RequestEvent} e */
37
+ function me(e) {
38
+ if (!e.auth) throw new UnauthorizedError("The request requires a logged-in user.");
39
+ return e.auth;
40
+ }
41
+
42
+ /**
43
+ * @param {string} field
44
+ * @param {string} message
45
+ * @param {string} [what]
46
+ */
47
+ const badRequest = (field, message, what = "Failed to save to the collection.") =>
48
+ new BadRequestError(what, { [field]: new ValidationError("validation_invalid_value", message) });
49
+
50
+ /** @param {core.App} app @param {string} collection @param {string} id */
51
+ function find(app, collection, id) {
52
+ if (!id) return null;
53
+ try {
54
+ return app.findRecordById(collection, id);
55
+ } catch {
56
+ return null;
57
+ }
58
+ }
59
+
60
+ /**
61
+ * Can the request's user see `rec` by its collection's view rule? (A guest too: the rules decide.)
62
+ * @param {core.RequestEvent} e
63
+ * @param {core.Record} rec
64
+ */
65
+ function canView(e, rec) {
66
+ const rule = rec.collection().viewRule;
67
+ return rule !== null && rule !== undefined && e.app.canAccessRecord(rec, e.requestInfo(), rule);
68
+ }
69
+
70
+ // ---------------------------------------------------------------- collections
71
+
72
+ /**
73
+ * collections create and update: a clean name, unique among the owner's; at most MAX_COLLECTIONS each.
74
+ * @param {core.RecordEvent} e
75
+ */
76
+ function beforeCollectionSave(e) {
77
+ const rec = recordOf(e);
78
+ cleanName(rec);
79
+ const key = nameKey(rec.getString("name"));
80
+ rec.set("name_key", key);
81
+ const owner = rec.getString("owner");
82
+ if (rec.isNew()) {
83
+ rec.set("items", 0);
84
+ rec.set("last_added", "");
85
+ const n = e.app.countRecords("collections", $dbx.hashExp({ owner }));
86
+ if (n >= MAX_COLLECTIONS) throw fieldError("name", `You can have at most ${MAX_COLLECTIONS} collections.`);
87
+ } else if (owner !== rec.original().getString("owner")) {
88
+ throw fieldError("owner", "This field can't be changed.");
89
+ }
90
+ if (!key) return; // `required` reports it
91
+ let clash = null;
92
+ try {
93
+ clash = e.app.findFirstRecordByFilter("collections", "owner = {:owner} && name_key = {:key} && id != {:id}", {
94
+ owner,
95
+ key,
96
+ id: rec.id,
97
+ });
98
+ } catch {
99
+ clash = null;
100
+ }
101
+ if (clash) throw fieldError("name", "You already have a collection with this name.", "validation_not_unique");
102
+ }
103
+
104
+ /**
105
+ * A collection saved: if it turned private (or public again), its subscribers' rows are saved again, so their clients
106
+ * hear of it live (they can't hear of the collection itself once it is private).
107
+ * @param {core.App} app
108
+ * @param {core.Record} rec
109
+ * @param {boolean} wasPublic
110
+ */
111
+ function afterCollectionUpdate(app, rec, wasPublic) {
112
+ if (rec.getBool("public") === wasPublic) return;
113
+ for (const sub of app.findRecordsByFilter("collection_subs", "collection = {:id}", "", 0, 0, { id: rec.id })) {
114
+ if (sub) app.save(sub);
115
+ }
116
+ }
117
+
118
+ /**
119
+ * A collection's save is done: made public or private, or renamed, the badges of its files are told.
120
+ * @param {core.App} app
121
+ * @param {core.Record} rec
122
+ */
123
+ function afterCollectionSaved(app, rec) {
124
+ const was = rec.original();
125
+ if (rec.getBool("public") !== was.getBool("public") || rec.getString("name") !== was.getString("name")) {
126
+ tellBadges(app, rec.id);
127
+ }
128
+ }
129
+
130
+ /**
131
+ * What a collection's badge says may have changed (made public or private, renamed, deleted): every client listening
132
+ * to BADGES_TOPIC gets its id and asks /badges again if it shows one. A guest too: a public collection's badge is
133
+ * theirs as well. Only the id goes out; what each may see of the collection, /badges says. The collection's own record
134
+ * events wouldn't do: PocketBase sends a change only to those who can see the result, so no one but the owner would
135
+ * hear of one made private, and a client can't subscribe to a private one it may see once it is public.
136
+ * @param {core.App} app
137
+ * @param {string} id
138
+ */
139
+ function tellBadges(app, id) {
140
+ const data = JSON.stringify({ id });
141
+ const clients = app.subscriptionsBroker().clients();
142
+ for (const key of Object.keys(clients)) {
143
+ const client = clients[key];
144
+ if (!client || client.isDiscarded()) continue;
145
+ for (const name of Object.keys(client.subscriptions(BADGES_TOPIC))) {
146
+ client.send(new SubscriptionMessage({ name, data }));
147
+ }
148
+ }
149
+ }
150
+
151
+ /**
152
+ * GET /api/chat/collections → { mine: [...], subs: [...] }, each by name. A subscription's `new` is how many items
153
+ * were added after its `seen_at` (at most NEW_CAP). Subscriptions to collections that are private now are left out
154
+ * (kept: they come back if it is public again).
155
+ * @param {core.RequestEvent} e
156
+ */
157
+ function list(e) {
158
+ const user = me(e);
159
+ const mine = arrayOf(new DynamicModel({ id: "", name: "", public: false, items: 0, last_added: "" }));
160
+ e.app
161
+ .db()
162
+ .newQuery("SELECT id, name, public, items, last_added FROM collections WHERE owner = {:me} ORDER BY name_key, id")
163
+ .bind({ me: user.id })
164
+ .all(mine);
165
+ const subs = arrayOf(new DynamicModel({ id: "", name: "", items: 0, last_added: "", owner: "", owner_name: "", seen_at: "", n: 0 }));
166
+ e.app
167
+ .db()
168
+ .newQuery(
169
+ `SELECT c.id, c.name, c.items, c.last_added, c.owner, COALESCE(u.name, '') AS owner_name, s.seen_at, (
170
+ SELECT COUNT(*) FROM (
171
+ SELECT 1 FROM collection_items i WHERE i.collection = c.id AND i.created > s.seen_at LIMIT ${NEW_CAP}
172
+ )
173
+ ) AS n
174
+ FROM collection_subs s
175
+ JOIN collections c ON c.id = s.collection
176
+ LEFT JOIN users u ON u.id = c.owner
177
+ WHERE s.user = {:me} AND c.public = TRUE
178
+ ORDER BY c.name_key, c.id`,
179
+ )
180
+ .bind({ me: user.id })
181
+ .all(subs);
182
+ const previews = previewsOf(e.app, [...mine.map((c) => c.id), ...subs.map((c) => c.id)]);
183
+ return e.json(200, {
184
+ mine: mine.map((c) => ({
185
+ id: c.id,
186
+ name: c.name,
187
+ public: !!c.public,
188
+ items: c.items,
189
+ last_added: c.last_added,
190
+ preview: previews[c.id] ?? [],
191
+ })),
192
+ subs: subs.map((c) => ({
193
+ id: c.id,
194
+ name: c.name,
195
+ public: true,
196
+ items: c.items,
197
+ last_added: c.last_added,
198
+ owner: { id: c.owner, name: c.owner_name },
199
+ seen_at: c.seen_at,
200
+ new: c.n,
201
+ preview: previews[c.id] ?? [],
202
+ })),
203
+ });
204
+ }
205
+
206
+ /**
207
+ * The newest PREVIEW_ITEMS items of each of these collections, newest first, for their tiles in the room list: one index
208
+ * range of (collection, created) each. CROSS JOIN keeps SQLite from scanning every item and running the subquery for
209
+ * each one (which it otherwise plans).
210
+ * @param {core.App} app
211
+ * @param {string[]} ids
212
+ * @returns {Record<string, { id: string, file: string, video: boolean, poster: boolean }[]>}
213
+ */
214
+ function previewsOf(app, ids) {
215
+ /** @type {Record<string, { id: string, file: string, video: boolean, poster: boolean }[]>} */
216
+ const out = {};
217
+ if (ids.length === 0) return out;
218
+ const rows = arrayOf(new DynamicModel({ id: "", collection: "", file: "", video: false, poster: false }));
219
+ app
220
+ .db()
221
+ .newQuery(
222
+ `SELECT i.id, i.collection, i.file, i.video, i.poster
223
+ FROM json_each({:ids}) c
224
+ CROSS JOIN collection_items i ON i.id IN (
225
+ SELECT j.id FROM collection_items j WHERE j.collection = c.value ORDER BY j.created DESC, j.id DESC LIMIT ${PREVIEW_ITEMS}
226
+ )
227
+ ORDER BY i.created DESC, i.id DESC`,
228
+ )
229
+ .bind({ ids: JSON.stringify(ids) })
230
+ .all(rows);
231
+ for (const r of rows) {
232
+ if (!out[r.collection]) out[r.collection] = [];
233
+ out[r.collection].push({ id: r.id, file: r.file, video: !!r.video, poster: !!r.poster });
234
+ }
235
+ return out;
236
+ }
237
+
238
+ /**
239
+ * GET /api/chat/badges?ids=a,b → { a: { name, public, mine } | { private: true } | null }: what the badge of a file
240
+ * attached from collection `a` may say (§31). The name only for a public collection or your own; null for one that
241
+ * is gone.
242
+ * @param {core.RequestEvent} e
243
+ */
244
+ function badges(e) {
245
+ const raw = e.request?.url?.query().get("ids") ?? "";
246
+ const ids = [...new Set(raw.split(",").filter((id) => /^[a-z0-9]{15}$/.test(id)))].slice(0, MAX_BADGES);
247
+ const user = e.auth?.id ?? "";
248
+ /** @type {Record<string, unknown>} */
249
+ const out = {};
250
+ for (const id of ids) {
251
+ const c = find(e.app, "collections", id);
252
+ if (!c) out[id] = null;
253
+ else if (c.getBool("public") || (user && c.getString("owner") === user)) {
254
+ out[id] = { name: c.getString("name"), public: c.getBool("public"), mine: !!user && c.getString("owner") === user };
255
+ } else out[id] = { private: true };
256
+ }
257
+ return e.json(200, out);
258
+ }
259
+
260
+ // ---------------------------------------------------------------- items
261
+
262
+ /** What an item looks like to the client. @param {core.Record} item */
263
+ const itemOut = (item) => ({
264
+ id: item.id,
265
+ collectionId: item.collection().id,
266
+ collectionName: item.collection().name,
267
+ collection: item.getString("collection"),
268
+ file: item.getString("file"),
269
+ name: item.getString("name"),
270
+ video: item.getBool("video"),
271
+ poster: item.getBool("poster"),
272
+ created: item.getString("created"),
273
+ });
274
+
275
+ /**
276
+ * POST /api/chat/items { collection, message, file } or { collection, item } → the new item: a message's image or
277
+ * video (one you can see: a forward's original too, §21.3) or an item you can see, in a collection of yours, naming
278
+ * the same file (§37). 409 when that file is in it already. Multipart { collection, file }: the upload itself
279
+ * (addUpload).
280
+ * @param {core.RequestEvent} e
281
+ */
282
+ function saveItem(e) {
283
+ const user = me(e);
284
+ const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body);
285
+ const str = (/** @type {string} */ k) => (typeof body[k] === "string" ? /** @type {string} */ (body[k]) : "");
286
+ const coll = find(e.app, "collections", str("collection"));
287
+ if (!coll || !canView(e, coll)) throw new NotFoundError("The collection doesn't exist.");
288
+ if (coll.getString("owner") !== user.id) throw new ForbiddenError("You can only add to your own collections.");
289
+ if (coll.getInt("items") >= MAX_ITEMS) throw badRequest("collection", `A collection holds at most ${MAX_ITEMS} items.`);
290
+ const upload = uploaded(e);
291
+ if (upload) return e.json(200, itemOut(addUpload(e.app, coll, upload)));
292
+
293
+ /** @type {string} */
294
+ let name;
295
+ if (str("item")) {
296
+ const item = find(e.app, "collection_items", str("item"));
297
+ if (!item || !canView(e, item)) throw new NotFoundError("The item doesn't exist.");
298
+ name = item.getString("file");
299
+ } else {
300
+ const msg = find(e.app, "messages", str("message"));
301
+ if (!msg || !canView(e, msg)) throw new NotFoundError("The message doesn't exist.");
302
+ if (msg.getBool("deleted")) throw badRequest("message", "That message was deleted.");
303
+ name = str("file");
304
+ if (!msg.getStringSlice("files").includes(name) || !files.isMedia(name))
305
+ throw badRequest("file", "Only images and videos can be saved.");
306
+ }
307
+ const row = files.byName(e.app, name);
308
+ if (!row) throw new NotFoundError("The file doesn't exist.");
309
+ const taken = () => new ApiError(409, "This is in the collection already.", {});
310
+ if (e.app.countRecords("collection_items", $dbx.hashExp({ collection: coll.id, origin: row.id }))) throw taken();
311
+ const item = new Record(e.app.findCollectionByNameOrId("collection_items"));
312
+ try {
313
+ e.app.runInTransaction((tx) => addItem(tx, coll.id, item, row));
314
+ } catch (err) {
315
+ // Lost a race with another save of the same file: the unique (collection, origin) index kept it to one.
316
+ if (e.app.countRecords("collection_items", $dbx.hashExp({ collection: coll.id, origin: row.id }))) throw taken();
317
+ throw err;
318
+ }
319
+ return e.json(200, itemOut(item));
320
+ }
321
+
322
+ /**
323
+ * Save `item`, new, in collection `collection` naming file `row` (linked), and count it in the collection.
324
+ * @param {core.App} tx
325
+ * @param {string} collection
326
+ * @param {core.Record} item
327
+ * @param {core.Record} row
328
+ */
329
+ function addItem(tx, collection, item, row) {
330
+ // Found before the transaction: the message may have been deleted since, and the file with it.
331
+ if (!files.byName(tx, row.getString("file"))) throw new NotFoundError("The file doesn't exist.");
332
+ item.set("collection", collection);
333
+ item.set("file", row.getString("file"));
334
+ item.set("name", row.getString("name") || row.getString("file"));
335
+ item.set("video", row.getBool("video"));
336
+ // A video whose poster is made already (saved from a message that has one) shows it at once.
337
+ item.set("poster", row.getBool("poster"));
338
+ item.set("origin", row.id);
339
+ tx.save(item);
340
+ files.link(tx, [row.id]);
341
+ const c = tx.findRecordById("collections", collection);
342
+ c.set("items", c.getInt("items") + 1);
343
+ c.set("last_added", new DateTime());
344
+ tx.save(c);
345
+ }
346
+
347
+ /**
348
+ * The file of a multipart POST /api/chat/items (`file`), or null for a JSON one (a save).
349
+ * @param {core.RequestEvent} e
350
+ * @returns {filesystem.File | null}
351
+ */
352
+ function uploaded(e) {
353
+ if (!(e.request?.header.get("Content-Type") ?? "").startsWith("multipart/")) return null;
354
+ /** @type {(filesystem.File | undefined)[]} */
355
+ let list = [];
356
+ try {
357
+ list = e.findUploadedFiles("file");
358
+ } catch {
359
+ list = [];
360
+ }
361
+ if (list.length !== 1 || !list[0]) throw badRequest("file", "Upload one image or video.");
362
+ return list[0];
363
+ }
364
+
365
+ /**
366
+ * An image or video uploaded straight into a collection (§31.2): a new file (§37) and an item naming it. Its name is
367
+ * cleaned as an attachment's is (no bidi overrides, "cat‮gpj.exe"; capped in length with the extension kept, QA
368
+ * BUG-149): subscribers of a public collection see it. Held to an attachment's limits (20 MB; an image's size, QA
369
+ * BUG-140); the media worker makes its grid thumbnail or poster, as for any file.
370
+ * @param {core.App} app
371
+ * @param {core.Record} coll
372
+ * @param {filesystem.File} upload
373
+ */
374
+ function addUpload(app, coll, upload) {
375
+ const name = clipFileName(tidy(unescapeUploadName(upload.originalName))) || upload.name;
376
+ if (!files.isMedia(name) || !files.isMedia(upload.name)) throw badRequest("file", "Only images and videos can be added.");
377
+ const item = new Record(app.findCollectionByNameOrId("collection_items"));
378
+ app.runInTransaction((tx) => {
379
+ const [row] = files.fromUploads(tx, [upload], "file");
380
+ addItem(tx, coll.id, item, row);
381
+ });
382
+ return item;
383
+ }
384
+
385
+ /**
386
+ * GET /api/chat/saved?message=/**
387
+ * GET /api/chat/saved?message=&file= (or ?item=) → { "<collection id>": "<item id>" }: your collections that have the
388
+ * file (a message's, or an item's) already. The save menu ticks them.
389
+ * @param {core.RequestEvent} e
390
+ */
391
+ function saved(e) {
392
+ const user = me(e);
393
+ const q = e.request?.url?.query();
394
+ let origin = "";
395
+ const itemId = q?.get("item") ?? "";
396
+ if (itemId) {
397
+ const item = find(e.app, "collection_items", itemId);
398
+ if (item && canView(e, item)) origin = item.getString("origin");
399
+ } else {
400
+ // The message's file, which you can see (a forward's original's too, §21.3).
401
+ const msg = find(e.app, "messages", q?.get("message") ?? "");
402
+ const name = q?.get("file") ?? "";
403
+ if (msg && canView(e, msg) && !msg.getBool("deleted") && msg.getStringSlice("files").includes(name)) {
404
+ origin = files.byName(e.app, name)?.id ?? "";
405
+ }
406
+ }
407
+ // Not one you may see: in none of yours. An empty origin would match nothing anyway (QA BUG-148).
408
+ if (!origin) return e.json(200, {});
409
+ const rows = arrayOf(new DynamicModel({ collection: "", id: "" }));
410
+ e.app
411
+ .db()
412
+ .newQuery(
413
+ `SELECT i.collection, i.id FROM collections c JOIN collection_items i ON i.collection = c.id AND i.origin = {:origin}
414
+ WHERE c.owner = {:me}`,
415
+ )
416
+ .bind({ me: user.id, origin })
417
+ .all(rows);
418
+ return e.json(200, Object.fromEntries(rows.map((r) => [r.collection, r.id])));
419
+ }
420
+
421
+ /**
422
+ * DELETE /api/chat/items/{id}: the owner takes an item out of their collection (its file goes with it, unless a
423
+ * message or another item still names it: the item's delete hook unlinks it, §37).
424
+ * @param {core.RequestEvent} e
425
+ */
426
+ function removeItem(e) {
427
+ const user = me(e);
428
+ const item = find(e.app, "collection_items", e.request?.pathValue("id") ?? "");
429
+ if (!item || !canView(e, item)) throw new NotFoundError("The item doesn't exist.");
430
+ const coll = e.app.findRecordById("collections", item.getString("collection"));
431
+ if (coll.getString("owner") !== user.id) throw new ForbiddenError("You can only remove items from your own collections.");
432
+ e.app.runInTransaction((tx) => {
433
+ tx.delete(tx.findRecordById("collection_items", item.id));
434
+ const c = tx.findRecordById("collections", coll.id);
435
+ c.set("items", Math.max(0, c.getInt("items") - 1));
436
+ tx.save(c);
437
+ });
438
+ return e.noContent(204);
439
+ }
440
+
441
+ /**
442
+ * The collection items a message create through the API names (`items`: their ids, as a JSON list in a form), as the
443
+ * `files` rows to attach after the `uploads` uploads, and which collection each came from (`sources`, by stored
444
+ * name). Items of a collection of yours or a public one only.
445
+ * @param {core.RecordRequestEvent} e
446
+ * @param {number} uploads
447
+ * @returns {{ rows: core.Record[], sources: Record<string, string> }}
448
+ */
449
+ function itemsToAttach(e, uploads) {
450
+ const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body);
451
+ let ids = body.items;
452
+ if (ids === undefined || ids === "" || ids === null) return { rows: [], sources: {} };
453
+ if (typeof ids === "string") {
454
+ try {
455
+ ids = JSON.parse(ids);
456
+ } catch {
457
+ ids = null;
458
+ }
459
+ }
460
+ if (!Array.isArray(ids) || ids.some((id) => typeof id !== "string" || !id)) throw fieldError("items", "Must be a list of item ids.");
461
+ // The create rule would refuse it anyway.
462
+ if (!e.auth) throw new ForbiddenError("Only signed-in users can post.");
463
+ const list = [.../** @type {Set<string>} */ (new Set(ids))];
464
+ if (!list.length) return { rows: [], sources: {} };
465
+ if (list.length + uploads > files.MAX_FILES) throw fieldError("files", `At most ${files.MAX_FILES} files.`);
466
+ const gone = () => fieldError("items", "A collection item is no longer available.");
467
+ const items = list.map((id) => {
468
+ const item = find(e.app, "collection_items", id);
469
+ if (!item || !canView(e, item)) throw gone();
470
+ return item;
471
+ });
472
+ const rows = files.byNames(
473
+ e.app,
474
+ items.map((i) => i.getString("file")),
475
+ );
476
+ /** @type {Record<string, string>} */
477
+ const sources = {};
478
+ const out = items.map((item) => {
479
+ const row = rows.get(item.getString("file"));
480
+ if (!row) throw gone();
481
+ if (!sources[item.getString("file")]) sources[item.getString("file")] = item.getString("collection");
482
+ return row;
483
+ });
484
+ return { rows: out, sources };
485
+ }
486
+
487
+ // ---------------------------------------------------------------- subscriptions
488
+
489
+ /** @param {core.App} app @param {string} user @param {string} collection */
490
+ function findSub(app, user, collection) {
491
+ try {
492
+ return app.findFirstRecordByFilter("collection_subs", "user = {:user} && collection = {:collection}", { user, collection });
493
+ } catch {
494
+ return null;
495
+ }
496
+ }
497
+
498
+ /**
499
+ * POST /api/chat/subs { collection, on } → { collection, on, seen_at }: follow someone else's public collection
500
+ * (seen up to now), or stop following it. Idempotent.
501
+ * @param {core.RequestEvent} e
502
+ */
503
+ function subscribe(e) {
504
+ const user = me(e);
505
+ const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body);
506
+ const id = typeof body.collection === "string" ? body.collection : "";
507
+ const what = "Failed to subscribe.";
508
+ // Not "false" or 0 taken for true.
509
+ if (body.on !== undefined && typeof body.on !== "boolean") throw badRequest("on", "Must be true or false.", what);
510
+ const on = body.on !== false;
511
+ const coll = find(e.app, "collections", id);
512
+ if (on) {
513
+ if (!coll?.getBool("public")) throw new NotFoundError("The collection doesn't exist.");
514
+ if (coll.getString("owner") === user.id) throw badRequest("collection", "This is your own collection.", what);
515
+ }
516
+ let row = findSub(e.app, user.id, id);
517
+ if (!on) {
518
+ if (row) e.app.delete(row);
519
+ return e.json(200, { collection: id, on: false, seen_at: "" });
520
+ }
521
+ if (!row) {
522
+ if (e.app.countRecords("collection_subs", $dbx.hashExp({ user: user.id })) >= MAX_SUBS) {
523
+ throw badRequest("collection", `You can follow at most ${MAX_SUBS} collections.`, what);
524
+ }
525
+ const created = new Record(e.app.findCollectionByNameOrId("collection_subs"));
526
+ created.set("user", user.id);
527
+ created.set("collection", id);
528
+ created.set("seen_at", new DateTime());
529
+ try {
530
+ e.app.save(created);
531
+ row = created;
532
+ } catch (err) {
533
+ // Another tab won the race: the unique (user, collection) index kept it to one row.
534
+ row = findSub(e.app, user.id, id);
535
+ if (!row) throw err;
536
+ }
537
+ }
538
+ return e.json(200, { collection: id, on: true, seen_at: row.getString("seen_at") });
539
+ }
540
+
541
+ /**
542
+ * POST /api/chat/subs/seen { collection, at? }: you have seen the collection's items up to `at` (an item's `created`;
543
+ * default now). Only moves forward, never past now. 404 when you don't follow it.
544
+ * @param {core.RequestEvent} e
545
+ */
546
+ function markSeen(e) {
547
+ const user = me(e);
548
+ const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body);
549
+ const id = typeof body.collection === "string" ? body.collection : "";
550
+ const row = id ? findSub(e.app, user.id, id) : null;
551
+ if (!row) throw new NotFoundError("You don't follow this collection.");
552
+ const now = new DateTime();
553
+ let at = now;
554
+ if (body.at !== undefined) {
555
+ const bad = () => badRequest("at", "Must be a date.", "Failed to mark the collection as seen.");
556
+ if (typeof body.at !== "string" || body.at === "") throw bad();
557
+ try {
558
+ at = new DateTime(body.at);
559
+ } catch {
560
+ throw bad();
561
+ }
562
+ if (at.isZero()) throw bad();
563
+ if (at.after(now)) at = now;
564
+ }
565
+ if (at.after(row.getDateTime("seen_at"))) {
566
+ row.set("seen_at", at);
567
+ e.app.save(row);
568
+ }
569
+ return e.json(200, { collection: id, seen_at: row.getString("seen_at") });
570
+ }
571
+
572
+ module.exports = {
573
+ MAX_COLLECTIONS,
574
+ MAX_ITEMS,
575
+ beforeCollectionSave,
576
+ afterCollectionUpdate,
577
+ afterCollectionSaved,
578
+ list,
579
+ badges,
580
+ tellBadges,
581
+ saveItem,
582
+ saved,
583
+ removeItem,
584
+ itemsToAttach,
585
+ subscribe,
586
+ markSeen,
587
+ };