@openpeepshq/core 0.1.33 → 0.1.34

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 (213) hide show
  1. package/dist/accounts/mutations.js +33 -35
  2. package/dist/analytics/compile.js +16 -10
  3. package/dist/analytics/read.js +52 -9
  4. package/dist/analytics/report.d.ts +20 -0
  5. package/dist/backups/index.js +75 -15
  6. package/dist/backups/metadata.d.ts +2 -3
  7. package/dist/backups/metadata.js +6 -2
  8. package/dist/config/defaults/capabilities.js +13 -2
  9. package/dist/config/defaults/community.js +7 -3
  10. package/dist/config/defaults/core.d.ts +1 -1
  11. package/dist/config/defaults/core.js +3 -0
  12. package/dist/config/index.d.ts +21 -0
  13. package/dist/config/index.js +7 -1
  14. package/dist/db/helpers.d.ts +1 -0
  15. package/dist/db/helpers.js +11 -3
  16. package/dist/db/index.d.ts +1 -1
  17. package/dist/db/index.js +1 -0
  18. package/dist/db/init.js +2 -3
  19. package/dist/db/migration/importCollections.d.ts +14 -9
  20. package/dist/db/migration/importCollections.js +114 -164
  21. package/dist/db/migration/shared.d.ts +2 -33
  22. package/dist/db/migration/shared.js +2 -52
  23. package/dist/db/pg/collections.d.ts +2 -2
  24. package/dist/db/pg/collections.js +2 -2
  25. package/dist/db/pg/filters/posts.d.ts +10 -0
  26. package/dist/db/pg/filters/posts.js +28 -4
  27. package/dist/db/pg/filters/profiles.d.ts +1 -0
  28. package/dist/db/pg/filters/profiles.js +2 -1
  29. package/dist/db/pg/map/filters.js +32 -2
  30. package/dist/db/pg/map/mutations.js +13 -8
  31. package/dist/db/pg/map/registry.d.ts +5 -0
  32. package/dist/db/pg/map/registry.js +64 -24
  33. package/dist/db/pg/map/relations.js +9 -5
  34. package/dist/db/pg/migrate.d.ts +1 -2
  35. package/dist/db/pg/migrate.js +6 -6
  36. package/dist/db/pg/queries/activity.js +3 -3
  37. package/dist/db/pg/queries/sorts.d.ts +1 -0
  38. package/dist/db/pg/queries/sorts.js +4 -0
  39. package/dist/db/pg/schema/documents.d.ts +279 -41
  40. package/dist/db/pg/schema/documents.js +21 -8
  41. package/dist/db/pg/schema/edges.d.ts +116 -7
  42. package/dist/db/pg/schema/edges.js +2 -1
  43. package/dist/db/pg/schema/index.d.ts +362 -15
  44. package/dist/db/pg/sql/0010_user_group_membership_roles.sql +16 -0
  45. package/dist/db/pg/sql/0011_drop_data_migrations.sql +1 -0
  46. package/dist/db/pg/sql/0012_posts_last_activity_at.sql +5 -0
  47. package/dist/db/pg/sql/0013_add_blocks_edge.sql +12 -0
  48. package/dist/db/pg/sql/0014_federation_datamodel.sql +59 -0
  49. package/dist/db/pg/sql/0015_profile_hashtags.sql +12 -0
  50. package/dist/db/pg/sql/meta/{0009_snapshot.json → 0015_snapshot.json} +291 -36
  51. package/dist/db/pg/sql/meta/_journal.json +43 -1
  52. package/dist/email/render.js +11 -3
  53. package/dist/events/index.d.ts +4 -0
  54. package/dist/events/index.js +1 -0
  55. package/dist/federation/activities.d.ts +17 -0
  56. package/dist/federation/activities.js +26 -0
  57. package/dist/federation/identity.d.ts +16 -0
  58. package/dist/federation/identity.js +52 -0
  59. package/dist/federation/index.d.ts +4 -0
  60. package/dist/federation/index.js +3 -0
  61. package/dist/federation/profiles.d.ts +3 -0
  62. package/dist/federation/profiles.js +14 -0
  63. package/dist/groups/finders.d.ts +2 -1
  64. package/dist/groups/helpers.d.ts +18 -0
  65. package/dist/groups/mapping.d.ts +4 -2
  66. package/dist/hashtags/finders.d.ts +6 -3
  67. package/dist/hashtags/finders.js +2 -0
  68. package/dist/hashtags/helpers.d.ts +8 -0
  69. package/dist/hashtags/helpers.js +4 -0
  70. package/dist/hashtags/index.d.ts +2 -0
  71. package/dist/hashtags/index.js +2 -0
  72. package/dist/hashtags/mutations.d.ts +3 -0
  73. package/dist/hashtags/mutations.js +13 -1
  74. package/dist/i18n/index.d.ts +1 -1
  75. package/dist/i18n/index.js +3 -1
  76. package/dist/i18n/pluginLocales.d.ts +6 -0
  77. package/dist/i18n/pluginLocales.js +15 -0
  78. package/dist/jams/export.d.ts +19 -0
  79. package/dist/jams/export.js +60 -0
  80. package/dist/jams/health.d.ts +8 -0
  81. package/dist/jams/health.js +46 -0
  82. package/dist/jams/helpers.d.ts +2 -2
  83. package/dist/jams/index.d.ts +2 -0
  84. package/dist/jams/index.js +23 -16
  85. package/dist/jams/jobs.js +1 -1
  86. package/dist/jams/livekit.d.ts +49 -4
  87. package/dist/jams/livekit.js +56 -39
  88. package/dist/jams/mapping.d.ts +3 -3
  89. package/dist/jams/mutations.d.ts +1 -1
  90. package/dist/jams/recording.d.ts +10 -0
  91. package/dist/jams/recording.js +32 -0
  92. package/dist/jams/token.d.ts +13 -1
  93. package/dist/jams/token.js +18 -7
  94. package/dist/jams/waitingRoom.js +1 -1
  95. package/dist/jobs/index.d.ts +1 -0
  96. package/dist/jobs/index.js +6 -1
  97. package/dist/jobs/jobDetail.js +1 -6
  98. package/dist/media/index.d.ts +1 -1
  99. package/dist/media/index.js +23 -8
  100. package/dist/media/processing.js +18 -7
  101. package/dist/notifications/defaultNotifications/follow/index.js +2 -2
  102. package/dist/notifications/defaultNotifications/index.js +4 -0
  103. package/dist/notifications/defaultNotifications/newGroupPost/index.js +12 -6
  104. package/dist/notifications/defaultNotifications/pollEnded/index.d.ts +19 -0
  105. package/dist/notifications/defaultNotifications/pollEnded/index.js +39 -0
  106. package/dist/notifications/defaultNotifications/pollEnded/recipients.d.ts +3 -0
  107. package/dist/notifications/defaultNotifications/pollEnded/recipients.js +18 -0
  108. package/dist/notifications/defaultNotifications/rsvp/index.d.ts +6 -1
  109. package/dist/notifications/defaultNotifications/rsvp/index.js +7 -0
  110. package/dist/notifications/defaultNotifications/rsvpCanceled/index.d.ts +24 -0
  111. package/dist/notifications/defaultNotifications/rsvpCanceled/index.js +75 -0
  112. package/dist/notifications/defaultNotifications/rsvpCanceled/recipients.d.ts +4 -0
  113. package/dist/notifications/defaultNotifications/rsvpCanceled/recipients.js +11 -0
  114. package/dist/notifications/jobs.js +3 -1
  115. package/dist/notifications/mutations.js +4 -0
  116. package/dist/plugins/index.js +37 -1
  117. package/dist/plugins/install.d.ts +28 -9
  118. package/dist/plugins/install.js +281 -49
  119. package/dist/plugins/pluginAuth.d.ts +1 -1
  120. package/dist/plugins/pluginAuth.js +10 -6
  121. package/dist/posts/activity.d.ts +9 -0
  122. package/dist/posts/activity.js +35 -0
  123. package/dist/posts/contextClosure.d.ts +1 -9
  124. package/dist/posts/contextClosure.js +15 -44
  125. package/dist/posts/conversationQueries.d.ts +7 -0
  126. package/dist/posts/conversationQueries.js +76 -2
  127. package/dist/posts/eventAgenda.d.ts +1 -0
  128. package/dist/posts/eventAgenda.js +10 -4
  129. package/dist/posts/eventOccurrenceJobs.js +7 -2
  130. package/dist/posts/eventOccurrences.d.ts +6 -0
  131. package/dist/posts/eventOccurrences.js +21 -0
  132. package/dist/posts/finders.d.ts +15 -8
  133. package/dist/posts/finders.js +67 -18
  134. package/dist/posts/helpers/filters.js +13 -8
  135. package/dist/posts/helpers/index.d.ts +27 -14
  136. package/dist/posts/helpers/index.js +34 -14
  137. package/dist/posts/index.d.ts +5 -2
  138. package/dist/posts/index.js +5 -2
  139. package/dist/posts/mapping.d.ts +216 -13
  140. package/dist/posts/mapping.js +14 -13
  141. package/dist/posts/mutations.d.ts +440 -3
  142. package/dist/posts/mutations.js +155 -32
  143. package/dist/posts/pollEnd.d.ts +3 -0
  144. package/dist/posts/pollEnd.js +7 -0
  145. package/dist/posts/pollEndJobs.d.ts +8 -0
  146. package/dist/posts/pollEndJobs.js +49 -0
  147. package/dist/posts/replyClosure.d.ts +10 -0
  148. package/dist/posts/replyClosure.js +43 -0
  149. package/dist/posts/rsvpConfirmationEmail.js +14 -16
  150. package/dist/posts/threadPreview.d.ts +8 -0
  151. package/dist/posts/threadPreview.js +44 -0
  152. package/dist/posts/unseenCounts.js +4 -1
  153. package/dist/profileSettings/cache.js +22 -5
  154. package/dist/profileSettings/mapping.d.ts +2 -0
  155. package/dist/profiles/activityQueries.d.ts +5 -0
  156. package/dist/profiles/activityQueries.js +85 -0
  157. package/dist/profiles/activitySummary.d.ts +3 -0
  158. package/dist/profiles/activitySummary.js +87 -0
  159. package/dist/profiles/blocks.d.ts +12 -0
  160. package/dist/profiles/blocks.js +73 -0
  161. package/dist/profiles/cache.d.ts +1 -0
  162. package/dist/profiles/cache.js +19 -6
  163. package/dist/profiles/finders.d.ts +2 -1
  164. package/dist/profiles/finders.js +8 -3
  165. package/dist/profiles/helpers.d.ts +2 -0
  166. package/dist/profiles/index.d.ts +2 -0
  167. package/dist/profiles/index.js +2 -0
  168. package/dist/profiles/mapping.d.ts +10 -5
  169. package/dist/profiles/mapping.js +13 -1
  170. package/dist/profiles/mutations.d.ts +8 -4
  171. package/dist/profiles/mutations.js +31 -2
  172. package/dist/redis/connection.d.ts +2 -0
  173. package/dist/redis/connection.js +25 -6
  174. package/dist/roles/index.d.ts +1 -1
  175. package/dist/roles/index.js +1 -1
  176. package/dist/roles/mapping.d.ts +1 -0
  177. package/dist/roles/mutations.js +86 -3
  178. package/dist/search/mapping.d.ts +1 -1
  179. package/dist/search/mapping.js +6 -2
  180. package/dist/server/index.d.ts +18 -0
  181. package/dist/server/index.js +24 -12
  182. package/dist/server/stablePublicServerInfo.d.ts +17 -0
  183. package/dist/server/stablePublicServerInfo.js +37 -0
  184. package/dist/server/status.d.ts +25 -0
  185. package/dist/server/status.js +98 -0
  186. package/dist/stats/finders.d.ts +1 -17681
  187. package/dist/stats/finders.js +9 -5
  188. package/dist/stats/mapping.d.ts +0 -1
  189. package/dist/stats/mapping.js +0 -3
  190. package/package.json +4 -5
  191. package/dist/db/migration/detect.d.ts +0 -3
  192. package/dist/db/migration/detect.js +0 -33
  193. package/dist/db/migration/importPostgres.d.ts +0 -3
  194. package/dist/db/migration/importPostgres.js +0 -18
  195. package/dist/db/migration/transform.d.ts +0 -20
  196. package/dist/db/migration/transform.js +0 -232
  197. package/dist/db/migration/validate.d.ts +0 -18
  198. package/dist/db/migration/validate.js +0 -69
  199. package/dist/db/pg/sql/meta/0000_snapshot.json +0 -3380
  200. package/dist/db/pg/sql/meta/0004_snapshot.json +0 -4114
  201. package/dist/db/pg/sql/meta/0005_snapshot.json +0 -4179
  202. package/dist/db/pg/sql/meta/0006_snapshot.json +0 -4200
  203. package/dist/db/pg/sql/meta/0007_snapshot.json +0 -4179
  204. package/dist/mastodon/index.d.ts +0 -4
  205. package/dist/mastodon/index.js +0 -51
  206. package/dist/mastodon/types.d.ts +0 -7579
  207. package/dist/mastodon/types.js +0 -523
  208. package/dist/mastodon/typescript.d.ts +0 -1578
  209. package/dist/mastodon/typescript.js +0 -1
  210. package/dist/migration/index.d.ts +0 -4
  211. package/dist/migration/index.js +0 -4
  212. package/dist/roles/defaults.d.ts +0 -2
  213. package/dist/roles/defaults.js +0 -95
@@ -8,6 +8,7 @@ import { uuidv7 } from 'uuidv7';
8
8
  import { createJamEvent, updateJamRecording } from './mutations.js';
9
9
  import { findActiveRecording, findActiveRtmpStream } from './finders.js';
10
10
  import { cancelRecordingAutoStop, scheduleRecordingAutoStop } from './jobs.js';
11
+ import { finalizeJamRecording } from './recording.js';
11
12
  import { jamRecordingUploadSecret } from './recordingUploadAuth.js';
12
13
  import { createSignedServiceToken } from '../accessTokens/tokens.js';
13
14
  import { unprocessableRequest } from '../errors/index.js';
@@ -19,6 +20,14 @@ const log = logger('app:jams:livekit');
19
20
  export const JAM_ROOM_EMPTY_TIMEOUT_SEC = 5 * 60;
20
21
  /** Seconds a room stays open after the last participant leaves. */
21
22
  export const JAM_ROOM_DEPARTURE_TIMEOUT_SEC = 60;
23
+ /**
24
+ * LiveKit closes rooms with no participants via emptyTimeout (host still
25
+ * connecting after Start) and departureTimeout (reconnect). Those rooms must
26
+ * not be deleted here. Reclaim only when a non-human participant (egress) is
27
+ * holding the room open — they count toward `numParticipants`, so LiveKit
28
+ * will not time the room out.
29
+ */
30
+ export const shouldReclaimJamRoom = (numParticipants, humanCount) => humanCount === 0 && numParticipants > 0;
22
31
  export const roomService = async () => {
23
32
  const { url, apiKey, apiSecret } = (await config()).jams.livekit;
24
33
  if (!url || !apiKey || !apiSecret) {
@@ -78,16 +87,30 @@ const getEgressClient = async () => {
78
87
  const { url, apiKey, apiSecret } = (await config()).jams.livekit;
79
88
  return new EgressClient(url, apiKey, apiSecret);
80
89
  };
90
+ export const stopEgress = async (egressId) => {
91
+ const egressClient = await getEgressClient();
92
+ try {
93
+ await egressClient.stopEgress(egressId);
94
+ }
95
+ catch (_a) {
96
+ // LiveKit egress can time out or already be stopped/failed; the user-facing
97
+ // stop action should not fail because of that.
98
+ }
99
+ };
81
100
  export const startRecording = async (profile, jamPost, recurrenceId) => {
82
101
  const jamId = jamPost.id;
83
102
  const roomName = jamRoomName(jamPost.id, recurrenceId);
84
103
  const recordingId = uuidv7();
85
- // Clear any recording left `active` by a previous failed egress so the new
86
- // one is the sole active recording for this jam.
104
+ // A leftover `active` row may still be uploading after stop. Finalize it so
105
+ // Complete can succeed, and stop its egress so this start is the only live
106
+ // take.
87
107
  const staleRecording = await findActiveRecording(jamPost);
88
108
  if (staleRecording) {
89
109
  await cancelRecordingAutoStop(staleRecording.id);
90
- await updateJamRecording(staleRecording.id, { status: 'failed' });
110
+ if (staleRecording.egressId) {
111
+ void stopEgress(staleRecording.egressId);
112
+ }
113
+ await finalizeJamRecording(staleRecording.id);
91
114
  }
92
115
  let recording = (await allpeepDb().then(({ db }) => connectRecording(db, profile, jamPost, {
93
116
  id: recordingId,
@@ -200,16 +223,6 @@ export const stopRtmpStream = async (jamPost) => {
200
223
  await emitJamEvent(jamPost.id, jamEvent);
201
224
  return Object.assign(Object.assign({}, stream), { status: 'completed' });
202
225
  };
203
- export const stopEgress = async (egressId) => {
204
- const egressClient = await getEgressClient();
205
- try {
206
- await egressClient.stopEgress(egressId);
207
- }
208
- catch (_a) {
209
- // LiveKit egress can time out or already be stopped/failed; the user-facing
210
- // stop action should not fail because of that.
211
- }
212
- };
213
226
  export const stopRecording = async (jamPost, recurrenceId) => {
214
227
  const jamRecording = await findActiveRecording(jamPost);
215
228
  if (!jamRecording) {
@@ -231,11 +244,13 @@ export const stopRecording = async (jamPost, recurrenceId) => {
231
244
  recurrenceId,
232
245
  });
233
246
  await roomService().then(async (rs) => rs === null || rs === void 0 ? void 0 : rs.sendData(jamRoomName(jamPost.id, recurrenceId), encoder.encode(JSON.stringify(jamEvent)), DataPacket_Kind.LOSSY, {}));
234
- return jamRecording;
247
+ await finalizeJamRecording(jamRecording.id);
248
+ return Object.assign(Object.assign({}, jamRecording), { status: 'finalizing' });
235
249
  };
236
250
  /**
237
- * Stops leftover egress and deletes a LiveKit room that has no human
238
- * participants (egress-only / orphan rooms). Safe to call repeatedly.
251
+ * Stops leftover egress and deletes an egress-only LiveKit room.
252
+ * Do not call this for a room with zero participants — that room is still
253
+ * inside emptyTimeout or departureTimeout. Safe to call repeatedly.
239
254
  */
240
255
  export const reclaimOrphanJamRoom = async (jam, roomName = jam.id) => {
241
256
  try {
@@ -268,35 +283,37 @@ export const finishRecording = async (jamRecording) => {
268
283
  await roomService().then(async (rs) => rs === null || rs === void 0 ? void 0 : rs.sendData(jamRoomName(jamRecording.post.id), encoder.encode(JSON.stringify(jamEvent)), DataPacket_Kind.LOSSY, {}));
269
284
  };
270
285
  export const jamState = async (jam, hideParticipants, recurrenceId) => {
286
+ const inactive = { participants: [], active: false };
271
287
  const rs = await roomService();
272
288
  const roomName = jamRoomName(jam.id, recurrenceId);
273
289
  if (rs === undefined) {
274
- return {
275
- participants: [],
276
- active: false,
277
- };
290
+ return inactive;
278
291
  }
279
- const room = await rs
280
- .listRooms([roomName])
281
- .then((rooms) => rooms.find((r) => r.name === roomName));
282
- if (!room) {
292
+ try {
293
+ const room = await rs
294
+ .listRooms([roomName])
295
+ .then((rooms) => rooms.find((r) => r.name === roomName));
296
+ if (!room) {
297
+ return inactive;
298
+ }
299
+ // No one has joined yet, or the last person just left. Leave the room
300
+ // for LiveKit's empty/departure timeout so a host on "Connecting" is
301
+ // not kicked back to the lobby.
302
+ if (!room.numParticipants) {
303
+ return inactive;
304
+ }
305
+ const participants = await listParticipantIds(roomName);
306
+ if (shouldReclaimJamRoom(room.numParticipants, participants.length)) {
307
+ void reclaimOrphanJamRoom(jam, roomName);
308
+ return inactive;
309
+ }
283
310
  return {
284
- participants: [],
285
- active: false,
311
+ participants: hideParticipants ? [] : participants,
312
+ active: true,
286
313
  };
287
314
  }
288
- const participants = await listParticipantIds(roomName);
289
- if (participants.length === 0) {
290
- // Room exists only for egress ghosts / empty leftovers — reclaim so it
291
- // stops appearing under Live jams.
292
- void reclaimOrphanJamRoom(jam, roomName);
293
- return {
294
- participants: [],
295
- active: false,
296
- };
315
+ catch (e) {
316
+ log.warn(`Failed to read jam state for ${roomName}: ${e.message}`);
317
+ return inactive;
297
318
  }
298
- return {
299
- participants: hideParticipants ? [] : participants,
300
- active: true,
301
- };
302
319
  };
@@ -42,7 +42,7 @@ export declare const jamParticipantsMapping: import("../db/pg/map").Mapping<{
42
42
  }, JamEvent, JamEvent>;
43
43
  export declare const jamRecordingRelation: RelationWithMapping<PostWithMeta, JamRecording>;
44
44
  export declare const jamRecordingsMapping: import("../db/pg/map").Mapping<{
45
- status: "active" | "completed" | "failed" | "requested";
45
+ status: "active" | "completed" | "failed" | "requested" | "finalizing";
46
46
  kind?: "file" | "rtmp" | undefined;
47
47
  destinationHost?: string | undefined;
48
48
  egressId?: string | undefined;
@@ -76,7 +76,7 @@ export declare const jamRecordingsMapping: import("../db/pg/map").Mapping<{
76
76
  updatedAt: string;
77
77
  deletedAt?: string | null | undefined;
78
78
  } & {
79
- status: "active" | "completed" | "failed" | "requested";
79
+ status: "active" | "completed" | "failed" | "requested" | "finalizing";
80
80
  kind?: "file" | "rtmp" | undefined;
81
81
  destinationHost?: string | undefined;
82
82
  egressId?: string | undefined;
@@ -112,7 +112,7 @@ export declare const jamRecordingsMapping: import("../db/pg/map").Mapping<{
112
112
  updatedAt: string;
113
113
  deletedAt?: string | null | undefined;
114
114
  } & {
115
- status: "active" | "completed" | "failed" | "requested";
115
+ status: "active" | "completed" | "failed" | "requested" | "finalizing";
116
116
  kind?: "file" | "rtmp" | undefined;
117
117
  destinationHost?: string | undefined;
118
118
  egressId?: string | undefined;
@@ -5,7 +5,7 @@ export declare const updateJamRecording: (recordingId: string, recording: Partia
5
5
  updatedAt: string;
6
6
  deletedAt?: string | null | undefined;
7
7
  } & {
8
- status: "active" | "completed" | "failed" | "requested";
8
+ status: "active" | "completed" | "failed" | "requested" | "finalizing";
9
9
  kind?: "file" | "rtmp" | undefined;
10
10
  destinationHost?: string | undefined;
11
11
  egressId?: string | undefined;
@@ -4,5 +4,15 @@ import type { JamRecording, JamRecordingWithMeta, MediaAttachment, PostWithMeta
4
4
  * notifies listeners (e.g. streaming pre-warm) via `jamRecordingCompleted`.
5
5
  */
6
6
  export declare const completeJamRecording: (recordingId: string, attachment: MediaAttachment) => Promise<JamRecordingWithMeta | undefined>;
7
+ /**
8
+ * Marks a stopped recording as still accepting its multipart complete. Used
9
+ * after egress stop so a later start does not fail the in-flight upload.
10
+ */
11
+ export declare const finalizeJamRecording: (recordingId: string) => Promise<void>;
12
+ /**
13
+ * Marks an in-progress or finalizing recording failed. Completed recordings
14
+ * are left unchanged. Multipart temp files are the S3 layer's responsibility.
15
+ */
16
+ export declare const failJamRecording: (recordingId: string) => Promise<void>;
7
17
  export declare const publishJamRecordingReply: (eventPost: PostWithMeta, recordingId: string) => Promise<JamRecording>;
8
18
  export declare const deleteJamRecording: (eventPost: PostWithMeta, recordingId: string) => Promise<void>;
@@ -1,8 +1,10 @@
1
1
  import { jamRecordingSchema } from '@openpeepshq/common/types';
2
+ import { jamRecordingAcceptsUpload } from '@openpeepshq/common/lib';
2
3
  import { hub } from '../events/index.js';
3
4
  import { createPost } from '../posts/index.js';
4
5
  import { allpeepDb } from '../db/index.js';
5
6
  import { findJamRecording } from './finders.js';
7
+ import { cancelRecordingAutoStop } from './jobs.js';
6
8
  import { jamRecordingsMapping } from './mapping.js';
7
9
  import { updateJamRecording } from './mutations.js';
8
10
  /**
@@ -20,6 +22,36 @@ export const completeJamRecording = async (recordingId, attachment) => {
20
22
  }
21
23
  return recording;
22
24
  };
25
+ /**
26
+ * Marks a stopped recording as still accepting its multipart complete. Used
27
+ * after egress stop so a later start does not fail the in-flight upload.
28
+ */
29
+ export const finalizeJamRecording = async (recordingId) => {
30
+ const recording = await findJamRecording(recordingId);
31
+ if (!recording) {
32
+ return;
33
+ }
34
+ if (recording.status !== 'requested' && recording.status !== 'active') {
35
+ return;
36
+ }
37
+ await cancelRecordingAutoStop(recordingId);
38
+ await updateJamRecording(recordingId, { status: 'finalizing' });
39
+ };
40
+ /**
41
+ * Marks an in-progress or finalizing recording failed. Completed recordings
42
+ * are left unchanged. Multipart temp files are the S3 layer's responsibility.
43
+ */
44
+ export const failJamRecording = async (recordingId) => {
45
+ const recording = await findJamRecording(recordingId);
46
+ if (!recording) {
47
+ return;
48
+ }
49
+ if (!jamRecordingAcceptsUpload(recording.status)) {
50
+ return;
51
+ }
52
+ await cancelRecordingAutoStop(recordingId);
53
+ await updateJamRecording(recordingId, { status: 'failed' });
54
+ };
23
55
  export const publishJamRecordingReply = async (eventPost, recordingId) => {
24
56
  const recording = await findJamRecording(recordingId);
25
57
  if (!recording) {
@@ -1,4 +1,16 @@
1
1
  import { PostWithMeta, PublicProfile } from '@openpeepshq/common/types';
2
2
  export declare const assertJamRsvpAllowed: (event: PostWithMeta, profile: PublicProfile, recurrenceId?: string) => void;
3
3
  export declare const createJamEgressToken: (event: PostWithMeta, recurrenceId?: string) => Promise<string>;
4
- export declare const createJamToken: (event: PostWithMeta, profile: PublicProfile, external?: boolean, recurrenceId?: string) => Promise<string>;
4
+ export type CreateJamTokenOptions = {
5
+ /** Participant is joining from another instance. */
6
+ external?: boolean;
7
+ recurrenceId?: string;
8
+ /**
9
+ * Automatic re-join after a dropped connection, as opposed to a participant
10
+ * deliberately joining. A reconnect must never open the room: a moderator
11
+ * whose client re-tokens into an ended jam would put it back on the live
12
+ * list and notify the community all over again.
13
+ */
14
+ reconnect?: boolean;
15
+ };
16
+ export declare const createJamToken: (event: PostWithMeta, profile: PublicProfile, { external, recurrenceId, reconnect, }?: CreateJamTokenOptions) => Promise<string>;
@@ -1,5 +1,5 @@
1
1
  import { publicProfileSchema, } from '@openpeepshq/common/types';
2
- import { canModerateJam, countYesRsvps, getEffectiveRsvp, jamRoomName, } from '@openpeepshq/common/lib';
2
+ import { canModerateJam, countYesRsvps, getEffectiveRsvp, isBlockedPair, jamRoomName, } from '@openpeepshq/common/lib';
3
3
  import { authNeeded, forbidden, notFound } from '../errors/index.js';
4
4
  import { config } from '../config/index.js';
5
5
  import { AccessToken, TrackSource } from 'livekit-server-sdk';
@@ -8,6 +8,7 @@ import { JAM_ROOM_DEPARTURE_TIMEOUT_SEC, JAM_ROOM_EMPTY_TIMEOUT_SEC, roomService
8
8
  import { localInstanceDomain } from './helpers.js';
9
9
  import { createJamEvent } from './mutations.js';
10
10
  import { uuidv7 } from 'uuidv7';
11
+ import { findProfile } from '../profiles/index.js';
11
12
  const calculateSources = (jam, profile) => {
12
13
  var _a;
13
14
  const sources = [TrackSource.MICROPHONE];
@@ -60,8 +61,8 @@ export const createJamEgressToken = async (event, recurrenceId) => {
60
61
  });
61
62
  return accessToken.toJwt();
62
63
  };
63
- export const createJamToken = async (event, profile, external = false, recurrenceId) => {
64
- var _a, _b, _c;
64
+ export const createJamToken = async (event, profile, { external = false, recurrenceId, reconnect = false, } = {}) => {
65
+ var _a, _b, _c, _d;
65
66
  if (!profile.id)
66
67
  throw authNeeded({ errorKey: 'error.profileRequired' });
67
68
  const jamId = event.id;
@@ -70,14 +71,24 @@ export const createJamToken = async (event, profile, external = false, recurrenc
70
71
  if (!jam) {
71
72
  throw notFound({ errorKey: 'error.jamNotFound', parameters: { jamId } });
72
73
  }
74
+ const joiner = await findProfile(profile.id);
75
+ if (joiner && isBlockedPair(joiner, (_c = event.profile) === null || _c === void 0 ? void 0 : _c.id)) {
76
+ throw notFound({ errorKey: 'error.jamNotFound', parameters: { jamId } });
77
+ }
73
78
  assertJamRsvpAllowed(event, profile, recurrenceId);
74
79
  const rs = await roomService();
75
80
  if (rs === undefined) {
76
81
  throw forbidden({ errorKey: 'error.jamsUnavailable' });
77
82
  }
78
- const rooms = await rs.listRooms([roomName]);
83
+ let rooms;
84
+ try {
85
+ rooms = await rs.listRooms([roomName]);
86
+ }
87
+ catch (_e) {
88
+ throw forbidden({ errorKey: 'error.jamsUnavailable' });
89
+ }
79
90
  const jamOpen = rooms.length === 1;
80
- if (!jamOpen && !(jam === null || jam === void 0 ? void 0 : jam.moderators.includes(profile.id))) {
91
+ if (!jamOpen && (reconnect || !(jam === null || jam === void 0 ? void 0 : jam.moderators.includes(profile.id)))) {
81
92
  throw forbidden({ errorKey: 'error.jamNotOpen' });
82
93
  }
83
94
  if (!jamOpen) {
@@ -92,7 +103,7 @@ export const createJamToken = async (event, profile, external = false, recurrenc
92
103
  departureTimeout: JAM_ROOM_DEPARTURE_TIMEOUT_SEC,
93
104
  });
94
105
  }
95
- catch (_d) {
106
+ catch (_f) {
96
107
  // Concurrent open may have created the room already.
97
108
  }
98
109
  }
@@ -119,7 +130,7 @@ export const createJamToken = async (event, profile, external = false, recurrenc
119
130
  roomJoin: true,
120
131
  roomAdmin: jam === null || jam === void 0 ? void 0 : jam.moderators.includes(profile.id),
121
132
  roomRecord: jam === null || jam === void 0 ? void 0 : jam.moderators.includes(profile.id),
122
- canPublish: (jam === null || jam === void 0 ? void 0 : jam.type) === 'video-call' || !!((_c = jam === null || jam === void 0 ? void 0 : jam.speakers) === null || _c === void 0 ? void 0 : _c.includes(profile.id)),
133
+ canPublish: (jam === null || jam === void 0 ? void 0 : jam.type) === 'video-call' || !!((_d = jam === null || jam === void 0 ? void 0 : jam.speakers) === null || _d === void 0 ? void 0 : _d.includes(profile.id)),
123
134
  canPublishSources: calculateSources(jam, profile),
124
135
  canPublishData: true,
125
136
  canSubscribe: true,
@@ -74,7 +74,7 @@ export const acceptFromWaitingRoom = async (event, profileId, recurrenceId) => {
74
74
  }
75
75
  const aKey = admittanceKey(event, recurrenceId);
76
76
  await conn.hSet(aKey, {
77
- [profile.id]: await createJamToken(event, profile, false, recurrenceId),
77
+ [profile.id]: await createJamToken(event, profile, { recurrenceId }),
78
78
  });
79
79
  await conn.expire(aKey, ADMITTANCE_TTL_SEC);
80
80
  };
@@ -6,5 +6,6 @@ export declare const connection: {
6
6
  export declare const queues: Record<string, Queue>;
7
7
  export declare const closeQueues: () => Promise<void>;
8
8
  export declare const queueAndWorker: <Input, Output = undefined>(queueName: string, processor: Processor<Input, Output>, queueOptions?: Omit<QueueOptions, "connection">) => [() => Queue, () => Worker];
9
+ export declare const getOrCreateQueue: (queueName: string) => Queue;
9
10
  export { getJobDetail } from './jobDetail';
10
11
  export { jobLogger, logStep, logFailure, formatErrorDetail, type JobLog, } from './jobLog';
@@ -1,4 +1,4 @@
1
- import { Queue, Worker } from 'bullmq';
1
+ import { MetricsTime, Queue, Worker } from 'bullmq';
2
2
  export const connection = {
3
3
  host: process.env.REDIS_HOST || 'localhost',
4
4
  port: Number(process.env.REDIS_PORT) || 6379,
@@ -54,7 +54,12 @@ export const queueAndWorker = (queueName, processor, queueOptions) => [
54
54
  () => new Worker(queueName, processor, {
55
55
  connection,
56
56
  concurrency: 5,
57
+ metrics: { maxDataPoints: MetricsTime.ONE_WEEK },
57
58
  }),
58
59
  ];
60
+ export const getOrCreateQueue = (queueName) => {
61
+ var _a;
62
+ return (_a = queues[queueName]) !== null && _a !== void 0 ? _a : (queues[queueName] = new Queue(queueName, { connection }));
63
+ };
59
64
  export { getJobDetail } from './jobDetail.js';
60
65
  export { jobLogger, logStep, logFailure, formatErrorDetail, } from './jobLog.js';
@@ -1,9 +1,4 @@
1
- import { Queue } from 'bullmq';
2
- import { connection, queues } from './index.js';
3
- const getOrCreateQueue = (queueName) => {
4
- var _a;
5
- return (_a = queues[queueName]) !== null && _a !== void 0 ? _a : (queues[queueName] = new Queue(queueName, { connection }));
6
- };
1
+ import { getOrCreateQueue } from './index.js';
7
2
  export const getJobDetail = async (queueName, jobId) => {
8
3
  var _a, _b, _c, _d, _e;
9
4
  const queue = getOrCreateQueue(queueName);
@@ -12,7 +12,7 @@ export interface MediaFile {
12
12
  }
13
13
  /**
14
14
  * Stream a web `ReadableStream` to a temp file, preserving the original
15
- * extension so format-sniffing tools (audiowaveform, sharp) behave. Peak
15
+ * extension so format-sniffing tools (ffmpeg, sharp) behave. Peak
16
16
  * memory is bounded by the write stream's highWaterMark, not the file size.
17
17
  */
18
18
  export declare const writeStreamToTemp: (stream: ReadableStream, name: string) => Promise<string>;
@@ -9,7 +9,6 @@ import { createReadStream, createWriteStream } from 'node:fs';
9
9
  import { Readable } from 'node:stream';
10
10
  import { pipeline } from 'node:stream/promises';
11
11
  import { getTheme, randomString } from '@openpeepshq/common/lib';
12
- import { execSync } from 'node:child_process';
13
12
  import { logger } from '../log/index.js';
14
13
  import { hub } from '../events/index.js';
15
14
  let storagePromise = null;
@@ -33,7 +32,7 @@ export const mediaStorage = () => {
33
32
  const tempPathFor = (name) => join(tmpdir(), `media-${randomString(16)}${path.extname(name)}`);
34
33
  /**
35
34
  * Stream a web `ReadableStream` to a temp file, preserving the original
36
- * extension so format-sniffing tools (audiowaveform, sharp) behave. Peak
35
+ * extension so format-sniffing tools (ffmpeg, sharp) behave. Peak
37
36
  * memory is bounded by the write stream's highWaterMark, not the file size.
38
37
  */
39
38
  export const writeStreamToTemp = async (stream, name) => {
@@ -159,15 +158,31 @@ const getVideoStreamInfo = (filePath) => new Promise((resolve, reject) => {
159
158
  resolve({ width: stream.width, height: stream.height, duration });
160
159
  });
161
160
  });
161
+ const waveformColor = (hex) => {
162
+ const bare = hex.replace('#', '');
163
+ return /^[0-9a-fA-F]{6}$/.test(bare) ? `0x${bare}` : '0x15678a';
164
+ };
165
+ /**
166
+ * Waveform still via ffmpeg. `audiowaveform` is not a project dependency and
167
+ * is often missing locally; ffmpeg already is, because video processing uses it.
168
+ */
169
+ const renderWaveform = (inputPath, outputPath, color) => new Promise((resolve, reject) => {
170
+ const size = `${previewMaxWidth}x${previewMaxWidth}`;
171
+ ffmpeg(inputPath)
172
+ .noVideo()
173
+ .outputOptions('-filter_complex', `aformat=channel_layouts=mono,showwavespic=s=${size}:colors=${color}`)
174
+ .outputOptions('-frames:v', '1')
175
+ .outputOptions('-update', '1')
176
+ .output(outputPath)
177
+ .on('end', () => resolve())
178
+ .on('error', (error) => reject(error))
179
+ .run();
180
+ });
162
181
  const createAudioPreview = async (inputPath) => {
163
182
  const outputPath = join(tmpdir(), `preview-${randomString(16)}.png`);
183
+ const color = waveformColor(getTheme(await communityConfig()).primaryHex);
164
184
  try {
165
- const duration = await getMediaDuration(inputPath);
166
- const pixelsPerSecond = Math.floor(700 / duration);
167
- execSync(`audiowaveform -i ${inputPath} -o ${outputPath} \
168
- --background-color ffffff88 --waveform-color ${getTheme(await communityConfig()).primaryHex.slice(1)} \
169
- -w ${previewMaxWidth} -h ${previewMaxWidth} --pixels-per-second ${pixelsPerSecond} \
170
- --no-axis-labels -q`);
185
+ await renderWaveform(inputPath, outputPath, color);
171
186
  return { path: outputPath, mimetype: 'image/png' };
172
187
  }
173
188
  catch (error) {
@@ -43,15 +43,26 @@ const runProcessingBody = async ({ mediaAttachmentId, sourceStorageKey, thumbnai
43
43
  previewMimetype = thumbnail.type;
44
44
  previewName = thumbnail.name;
45
45
  }
46
- const preview = await createPreview(previewInputPath, previewMimetype, previewName);
47
- if (preview.path !== sourcePath && preview.path !== previewInputPath) {
48
- temps.add(preview.path);
49
- }
50
- const { key: previewStorageKey } = await storeFromPath(preview.path);
51
46
  const normalizedFilename = encodeURIComponent(transcoded.filename);
52
- const thumbnailFilename = `thumbnail-${normalizedFilename}${normalizedFilename.endsWith('.webp') ? '' : '.webp'}`;
53
47
  const url = storage.getPath(fileStorageKey, normalizedFilename);
54
- const previewUrl = storage.getPath(previewStorageKey, thumbnailFilename);
48
+ // A waveform is a preview, not the audio itself. A missing or broken
49
+ // waveform tool must not leave the attachment stuck in `processing`.
50
+ let previewUrl = null;
51
+ try {
52
+ const preview = await createPreview(previewInputPath, previewMimetype, previewName);
53
+ if (preview.path !== sourcePath && preview.path !== previewInputPath) {
54
+ temps.add(preview.path);
55
+ }
56
+ const { key: previewStorageKey } = await storeFromPath(preview.path);
57
+ const thumbnailFilename = `thumbnail-${normalizedFilename}${normalizedFilename.endsWith('.webp') ? '' : '.webp'}`;
58
+ previewUrl = storage.getPath(previewStorageKey, thumbnailFilename);
59
+ }
60
+ catch (error) {
61
+ if (filetype !== 'audio')
62
+ throw error;
63
+ const message = error instanceof Error ? error.message : String(error);
64
+ log.error(`Audio waveform skipped for ${mediaAttachmentId}: ${message}`);
65
+ }
55
66
  const updated = await updateMediaAttachment(mediaAttachmentId, {
56
67
  url,
57
68
  previewUrl,
@@ -1,6 +1,6 @@
1
1
  import { notificationAll, } from '@openpeepshq/common/types';
2
2
  import { maybeCreateNotification } from '@openpeepshq/core/notifications';
3
- import { getProfileAvatar, profileName, truncateText, } from '@openpeepshq/common/lib';
3
+ import { getProfileAvatar, markdownPlainText, profileName, truncateText, } from '@openpeepshq/common/lib';
4
4
  import { communityConfig } from '../../../config/index.js';
5
5
  import { PUSH_INVALIDATE } from '../../pushInvalidation.js';
6
6
  export default {
@@ -16,7 +16,7 @@ export default {
16
16
  return ({
17
17
  title: `${profileName(notification.senderProfile)} followed you`,
18
18
  options: {
19
- body: truncateText((_a = notification.senderProfile) === null || _a === void 0 ? void 0 : _a.bio),
19
+ body: truncateText(markdownPlainText((_a = notification.senderProfile) === null || _a === void 0 ? void 0 : _a.bio)),
20
20
  icon: getProfileAvatar(notification.senderProfile, await communityConfig()),
21
21
  actions: [
22
22
  {
@@ -14,8 +14,10 @@ import { default as groupAdded } from './groupAdded/index.js';
14
14
  import { default as groupMemberJoined } from './groupMemberJoined/index.js';
15
15
  import { default as groupMemberLeft } from './groupMemberLeft/index.js';
16
16
  import { default as pollVote } from './pollVote/index.js';
17
+ import { default as pollEnded } from './pollEnded/index.js';
17
18
  import { default as newGroupPost } from './newGroupPost/index.js';
18
19
  import { default as rsvp } from './rsvp/index.js';
20
+ import { default as rsvpCanceled } from './rsvpCanceled/index.js';
19
21
  const defaultNotificationsHandlers = [
20
22
  announcement,
21
23
  directMessage,
@@ -32,8 +34,10 @@ const defaultNotificationsHandlers = [
32
34
  groupMemberJoined,
33
35
  groupMemberLeft,
34
36
  pollVote,
37
+ pollEnded,
35
38
  newGroupPost,
36
39
  rsvp,
40
+ rsvpCanceled,
37
41
  ];
38
42
  export const defaultNotificationTypes = defaultNotificationsHandlers.map((handler) => pick(handler, 'type', 'requiredCapabilities', 'defaultSettings'));
39
43
  export const registerDefaultNotifications = async () => {
@@ -22,21 +22,27 @@ const eventHandler = async (data) => {
22
22
  }
23
23
  };
24
24
  const pushRenderer = async (notification) => {
25
- var _a, _b, _c, _d, _e;
26
- return ({
27
- title: `${profileName((_a = notification.post) === null || _a === void 0 ? void 0 : _a.profile)} made a post in ${(_b = notification === null || notification === void 0 ? void 0 : notification.group) === null || _b === void 0 ? void 0 : _b.displayName}`,
25
+ var _a, _b, _c, _d, _e, _f, _g;
26
+ const isRepost = !!((_a = notification.post) === null || _a === void 0 ? void 0 : _a.repost);
27
+ const preview = (_c = (_b = notification.post) === null || _b === void 0 ? void 0 : _b.repost) !== null && _c !== void 0 ? _c : notification.post;
28
+ const name = profileName((_d = notification.post) === null || _d === void 0 ? void 0 : _d.profile);
29
+ const group = (_e = notification.group) === null || _e === void 0 ? void 0 : _e.displayName;
30
+ return {
31
+ title: isRepost
32
+ ? `${name} reposted a post in ${group}`
33
+ : `${name} made a post in ${group}`,
28
34
  options: {
29
- body: (_d = (_c = notification.post) === null || _c === void 0 ? void 0 : _c.data) === null || _d === void 0 ? void 0 : _d.content,
35
+ body: (_f = preview === null || preview === void 0 ? void 0 : preview.data) === null || _f === void 0 ? void 0 : _f.content,
30
36
  icon: getGroupAvatar(notification.group, await communityConfig()),
31
37
  actions: [
32
38
  {
33
- action: `goto:/groups/@${(_e = notification.group) === null || _e === void 0 ? void 0 : _e.handle}`,
39
+ action: `goto:/groups/@${(_g = notification.group) === null || _g === void 0 ? void 0 : _g.handle}`,
34
40
  title: 'Go to post',
35
41
  },
36
42
  ],
37
43
  },
38
44
  invalidateQueries: [PUSH_INVALIDATE.posts, PUSH_INVALIDATE.unseenCounts],
39
- });
45
+ };
40
46
  };
41
47
  export default {
42
48
  type: 'newGroupPost',
@@ -0,0 +1,19 @@
1
+ import type { ExpandedNotification } from '@openpeepshq/common/types';
2
+ declare const _default: {
3
+ type: string;
4
+ event: string;
5
+ eventHandler: (data: unknown) => Promise<void>;
6
+ pushRenderer: (notification: ExpandedNotification) => Promise<{
7
+ title: string;
8
+ options: {
9
+ body: string | undefined;
10
+ icon: string;
11
+ actions: {
12
+ action: string;
13
+ title: string;
14
+ }[];
15
+ };
16
+ invalidateQueries: string[][];
17
+ }>;
18
+ };
19
+ export default _default;
@@ -0,0 +1,39 @@
1
+ import { maybeCreateNotification } from '@openpeepshq/core/notifications';
2
+ import { getProfileAvatar } from '@openpeepshq/common/lib';
3
+ import { communityConfig } from '../../../config/index.js';
4
+ import { PUSH_INVALIDATE } from '../../pushInvalidation.js';
5
+ import { pollEndedRecipientProfiles } from './recipients.js';
6
+ const eventHandler = async (data) => {
7
+ var _a, _b;
8
+ const post = data;
9
+ if (((_a = post.data) === null || _a === void 0 ? void 0 : _a.type) !== 'question') {
10
+ return;
11
+ }
12
+ const fromProfileId = (_b = post.profile) === null || _b === void 0 ? void 0 : _b.id;
13
+ for (const recipient of pollEndedRecipientProfiles(post)) {
14
+ await maybeCreateNotification(recipient, Object.assign({ type: 'pollEnded', postId: post.id }, (fromProfileId ? { fromProfileId } : {})));
15
+ }
16
+ };
17
+ const pushRenderer = async (notification) => {
18
+ var _a, _b, _c, _d, _e;
19
+ return ({
20
+ title: 'A poll has ended',
21
+ options: {
22
+ body: (_b = (_a = notification.post) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.content,
23
+ icon: getProfileAvatar((_c = notification.senderProfile) !== null && _c !== void 0 ? _c : (_d = notification.post) === null || _d === void 0 ? void 0 : _d.profile, await communityConfig()),
24
+ actions: [
25
+ {
26
+ action: `goto:/posts/${(_e = notification.post) === null || _e === void 0 ? void 0 : _e.id}`,
27
+ title: 'See Results',
28
+ },
29
+ ],
30
+ },
31
+ invalidateQueries: [PUSH_INVALIDATE.posts],
32
+ });
33
+ };
34
+ export default {
35
+ type: 'pollEnded',
36
+ event: 'pollEnded',
37
+ eventHandler,
38
+ pushRenderer,
39
+ };
@@ -0,0 +1,3 @@
1
+ import type { PostWithMeta, PublicProfile } from '@openpeepshq/common/types';
2
+ /** Poll author, voters, and parent post author when the poll is a reply. */
3
+ export declare const pollEndedRecipientProfiles: (post: PostWithMeta) => PublicProfile[];