@openpeepshq/core 0.1.32 → 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 (261) hide show
  1. package/dist/accessTokens/helpers.d.ts +2 -2
  2. package/dist/accessTokens/tokens.js +14 -7
  3. package/dist/accounts/mutations.d.ts +2 -2
  4. package/dist/accounts/mutations.js +33 -35
  5. package/dist/analytics/cache.js +12 -7
  6. package/dist/analytics/compile.js +16 -10
  7. package/dist/analytics/pdfReport.d.ts +1 -0
  8. package/dist/analytics/pdfReport.js +5 -4
  9. package/dist/analytics/privacy.d.ts +18 -0
  10. package/dist/analytics/privacy.js +10 -0
  11. package/dist/analytics/read.js +75 -19
  12. package/dist/analytics/report.d.ts +21 -1
  13. package/dist/analytics/report.js +9 -2
  14. package/dist/backups/index.js +78 -15
  15. package/dist/backups/metadata.d.ts +8 -2
  16. package/dist/backups/metadata.js +6 -2
  17. package/dist/config/defaults/capabilities.js +13 -2
  18. package/dist/config/defaults/community.js +7 -9
  19. package/dist/config/defaults/core.d.ts +1 -1
  20. package/dist/config/defaults/core.js +3 -0
  21. package/dist/config/defaults/db.d.ts +0 -2
  22. package/dist/config/defaults/db.js +0 -2
  23. package/dist/config/index.d.ts +25 -3
  24. package/dist/config/index.js +7 -1
  25. package/dist/db/helpers.d.ts +7 -28
  26. package/dist/db/helpers.js +30 -152
  27. package/dist/db/index.d.ts +3 -1
  28. package/dist/db/index.js +5 -0
  29. package/dist/db/init.js +2 -2
  30. package/dist/db/migration/importCollections.d.ts +15 -10
  31. package/dist/db/migration/importCollections.js +121 -155
  32. package/dist/db/migration/shared.d.ts +2 -37
  33. package/dist/db/migration/shared.js +2 -59
  34. package/dist/db/pg/client.js +4 -0
  35. package/dist/db/pg/collections.d.ts +2 -2
  36. package/dist/db/pg/collections.js +2 -2
  37. package/dist/db/pg/filters/edges.d.ts +1 -1
  38. package/dist/db/pg/filters/edges.js +1 -1
  39. package/dist/db/pg/filters/posts.d.ts +11 -0
  40. package/dist/db/pg/filters/posts.js +37 -3
  41. package/dist/db/pg/filters/profiles.d.ts +1 -0
  42. package/dist/db/pg/filters/profiles.js +2 -1
  43. package/dist/db/pg/map/filters.js +37 -2
  44. package/dist/db/pg/map/mutations.js +13 -8
  45. package/dist/db/pg/map/registry.d.ts +5 -0
  46. package/dist/db/pg/map/registry.js +64 -24
  47. package/dist/db/pg/map/relations.d.ts +1 -1
  48. package/dist/db/pg/map/relations.js +98 -46
  49. package/dist/db/pg/migrate.d.ts +22 -0
  50. package/dist/db/pg/migrate.js +88 -2
  51. package/dist/db/pg/queries/activity.js +3 -3
  52. package/dist/db/pg/queries/sorts.d.ts +1 -0
  53. package/dist/db/pg/queries/sorts.js +4 -0
  54. package/dist/db/pg/schema/documents.d.ts +422 -41
  55. package/dist/db/pg/schema/documents.js +43 -9
  56. package/dist/db/pg/schema/edges.d.ts +117 -7
  57. package/dist/db/pg/schema/edges.js +4 -2
  58. package/dist/db/pg/schema/index.d.ts +505 -15
  59. package/dist/db/pg/sql/0007_shallow_oracle.sql +3 -0
  60. package/dist/db/pg/sql/0008_group_owner_roles.sql +31 -0
  61. package/dist/db/pg/sql/0009_event_occurrences.sql +26 -0
  62. package/dist/db/pg/sql/0010_user_group_membership_roles.sql +16 -0
  63. package/dist/db/pg/sql/0011_drop_data_migrations.sql +1 -0
  64. package/dist/db/pg/sql/0012_posts_last_activity_at.sql +5 -0
  65. package/dist/db/pg/sql/0013_add_blocks_edge.sql +12 -0
  66. package/dist/db/pg/sql/0014_federation_datamodel.sql +59 -0
  67. package/dist/db/pg/sql/0015_profile_hashtags.sql +12 -0
  68. package/dist/db/pg/sql/meta/{0006_snapshot.json → 0015_snapshot.json} +393 -39
  69. package/dist/db/pg/sql/meta/_journal.json +64 -1
  70. package/dist/db/replaceOrigin.js +6 -0
  71. package/dist/db/types.d.ts +0 -4
  72. package/dist/email/render.js +11 -3
  73. package/dist/events/index.d.ts +6 -1
  74. package/dist/events/index.js +55 -33
  75. package/dist/federation/activities.d.ts +17 -0
  76. package/dist/federation/activities.js +26 -0
  77. package/dist/federation/identity.d.ts +16 -0
  78. package/dist/federation/identity.js +52 -0
  79. package/dist/federation/index.d.ts +4 -0
  80. package/dist/federation/index.js +3 -0
  81. package/dist/federation/profiles.d.ts +3 -0
  82. package/dist/federation/profiles.js +14 -0
  83. package/dist/groups/finders.d.ts +3 -2
  84. package/dist/groups/helpers.d.ts +24 -6
  85. package/dist/groups/mapping.d.ts +6 -4
  86. package/dist/groups/mapping.js +2 -2
  87. package/dist/groups/mutations.js +1 -1
  88. package/dist/hashtags/finders.d.ts +6 -3
  89. package/dist/hashtags/finders.js +2 -0
  90. package/dist/hashtags/helpers.d.ts +8 -0
  91. package/dist/hashtags/helpers.js +4 -0
  92. package/dist/hashtags/index.d.ts +2 -0
  93. package/dist/hashtags/index.js +2 -0
  94. package/dist/hashtags/mutations.d.ts +3 -0
  95. package/dist/hashtags/mutations.js +13 -1
  96. package/dist/i18n/index.d.ts +1 -1
  97. package/dist/i18n/index.js +3 -1
  98. package/dist/i18n/pluginLocales.d.ts +6 -0
  99. package/dist/i18n/pluginLocales.js +15 -0
  100. package/dist/inviteLinks/helpers.d.ts +4 -4
  101. package/dist/jams/cache.d.ts +1 -1
  102. package/dist/jams/cache.js +2 -1
  103. package/dist/jams/export.d.ts +19 -0
  104. package/dist/jams/export.js +60 -0
  105. package/dist/jams/finders.d.ts +2 -1
  106. package/dist/jams/finders.js +18 -7
  107. package/dist/jams/health.d.ts +8 -0
  108. package/dist/jams/health.js +46 -0
  109. package/dist/jams/helpers.d.ts +6 -2
  110. package/dist/jams/index.d.ts +6 -3
  111. package/dist/jams/index.js +41 -27
  112. package/dist/jams/jobs.js +1 -1
  113. package/dist/jams/livekit.d.ts +93 -10
  114. package/dist/jams/livekit.js +151 -52
  115. package/dist/jams/mapping.d.ts +17 -7
  116. package/dist/jams/mutations.d.ts +3 -1
  117. package/dist/jams/recording.d.ts +10 -0
  118. package/dist/jams/recording.js +32 -0
  119. package/dist/jams/rtmp.d.ts +5 -0
  120. package/dist/jams/rtmp.js +8 -0
  121. package/dist/jams/token.d.ts +15 -3
  122. package/dist/jams/token.js +30 -16
  123. package/dist/jams/waitingRoom.d.ts +6 -6
  124. package/dist/jams/waitingRoom.js +24 -23
  125. package/dist/jobs/index.d.ts +1 -0
  126. package/dist/jobs/index.js +6 -1
  127. package/dist/jobs/jobDetail.js +1 -6
  128. package/dist/media/index.d.ts +1 -1
  129. package/dist/media/index.js +23 -8
  130. package/dist/media/processing.js +18 -7
  131. package/dist/notifications/defaultNotifications/follow/index.js +2 -2
  132. package/dist/notifications/defaultNotifications/groupMemberJoined/index.js +3 -1
  133. package/dist/notifications/defaultNotifications/groupMemberLeft/index.js +3 -1
  134. package/dist/notifications/defaultNotifications/index.js +4 -0
  135. package/dist/notifications/defaultNotifications/newGroupPost/index.js +12 -6
  136. package/dist/notifications/defaultNotifications/pollEnded/index.d.ts +19 -0
  137. package/dist/notifications/defaultNotifications/pollEnded/index.js +39 -0
  138. package/dist/notifications/defaultNotifications/pollEnded/recipients.d.ts +3 -0
  139. package/dist/notifications/defaultNotifications/pollEnded/recipients.js +18 -0
  140. package/dist/notifications/defaultNotifications/rsvp/index.d.ts +6 -1
  141. package/dist/notifications/defaultNotifications/rsvp/index.js +7 -0
  142. package/dist/notifications/defaultNotifications/rsvpCanceled/index.d.ts +24 -0
  143. package/dist/notifications/defaultNotifications/rsvpCanceled/index.js +75 -0
  144. package/dist/notifications/defaultNotifications/rsvpCanceled/recipients.d.ts +4 -0
  145. package/dist/notifications/defaultNotifications/rsvpCanceled/recipients.js +11 -0
  146. package/dist/notifications/helpers.js +6 -2
  147. package/dist/notifications/jobs.js +3 -1
  148. package/dist/notifications/mutations.js +4 -0
  149. package/dist/notifications/push.js +11 -4
  150. package/dist/plugins/helpers.d.ts +1 -0
  151. package/dist/plugins/helpers.js +1 -8
  152. package/dist/plugins/index.d.ts +5 -0
  153. package/dist/plugins/index.js +78 -5
  154. package/dist/plugins/install.d.ts +39 -0
  155. package/dist/plugins/install.js +455 -0
  156. package/dist/plugins/pluginAuth.d.ts +1 -1
  157. package/dist/plugins/pluginAuth.js +10 -6
  158. package/dist/plugins/state.d.ts +4 -0
  159. package/dist/plugins/state.js +29 -0
  160. package/dist/posts/activity.d.ts +9 -0
  161. package/dist/posts/activity.js +35 -0
  162. package/dist/posts/contextClosure.d.ts +1 -9
  163. package/dist/posts/contextClosure.js +15 -44
  164. package/dist/posts/conversationQueries.d.ts +7 -0
  165. package/dist/posts/conversationQueries.js +76 -2
  166. package/dist/posts/eventAgenda.d.ts +166 -0
  167. package/dist/posts/eventAgenda.js +126 -0
  168. package/dist/posts/eventOccurrenceJobs.d.ts +4 -0
  169. package/dist/posts/eventOccurrenceJobs.js +28 -0
  170. package/dist/posts/eventOccurrences.d.ts +10 -0
  171. package/dist/posts/eventOccurrences.js +61 -0
  172. package/dist/posts/finders.d.ts +47 -16
  173. package/dist/posts/finders.js +93 -62
  174. package/dist/posts/helpers/filters.js +14 -9
  175. package/dist/posts/helpers/index.d.ts +129 -30
  176. package/dist/posts/helpers/index.js +66 -33
  177. package/dist/posts/index.d.ts +7 -1
  178. package/dist/posts/index.js +7 -1
  179. package/dist/posts/mapping.d.ts +491 -13
  180. package/dist/posts/mapping.js +45 -10
  181. package/dist/posts/mutations.d.ts +441 -4
  182. package/dist/posts/mutations.js +177 -43
  183. package/dist/posts/pollEnd.d.ts +3 -0
  184. package/dist/posts/pollEnd.js +7 -0
  185. package/dist/posts/pollEndJobs.d.ts +8 -0
  186. package/dist/posts/pollEndJobs.js +49 -0
  187. package/dist/posts/replyClosure.d.ts +10 -0
  188. package/dist/posts/replyClosure.js +43 -0
  189. package/dist/posts/rsvpConfirmationEmail.js +14 -15
  190. package/dist/posts/threadPreview.d.ts +8 -0
  191. package/dist/posts/threadPreview.js +44 -0
  192. package/dist/posts/unseenCounts.d.ts +2 -0
  193. package/dist/posts/unseenCounts.js +28 -8
  194. package/dist/profileSettings/cache.js +22 -5
  195. package/dist/profileSettings/mapping.d.ts +2 -0
  196. package/dist/profiles/activityQueries.d.ts +5 -0
  197. package/dist/profiles/activityQueries.js +85 -0
  198. package/dist/profiles/activitySummary.d.ts +3 -0
  199. package/dist/profiles/activitySummary.js +87 -0
  200. package/dist/profiles/blocks.d.ts +12 -0
  201. package/dist/profiles/blocks.js +73 -0
  202. package/dist/profiles/cache.d.ts +4 -1
  203. package/dist/profiles/cache.js +28 -7
  204. package/dist/profiles/finders.d.ts +2 -1
  205. package/dist/profiles/finders.js +8 -3
  206. package/dist/profiles/helpers.d.ts +7 -5
  207. package/dist/profiles/index.d.ts +3 -1
  208. package/dist/profiles/index.js +3 -1
  209. package/dist/profiles/mapping.d.ts +10 -5
  210. package/dist/profiles/mapping.js +13 -1
  211. package/dist/profiles/mutations.d.ts +8 -4
  212. package/dist/profiles/mutations.js +42 -15
  213. package/dist/pushSubscriptions/helpers.d.ts +2 -2
  214. package/dist/pushSubscriptions/mutations.js +13 -1
  215. package/dist/redis/connection.d.ts +2 -0
  216. package/dist/redis/connection.js +25 -6
  217. package/dist/reports/helpers.d.ts +6 -6
  218. package/dist/roles/index.d.ts +1 -1
  219. package/dist/roles/index.js +1 -1
  220. package/dist/roles/mapping.d.ts +1 -0
  221. package/dist/roles/mutations.js +86 -3
  222. package/dist/search/mapping.d.ts +1 -1
  223. package/dist/search/mapping.js +6 -2
  224. package/dist/server/index.d.ts +19 -1
  225. package/dist/server/index.js +37 -18
  226. package/dist/server/stablePublicServerInfo.d.ts +17 -0
  227. package/dist/server/stablePublicServerInfo.js +37 -0
  228. package/dist/server/status.d.ts +25 -0
  229. package/dist/server/status.js +98 -0
  230. package/dist/stats/finders.d.ts +1 -16131
  231. package/dist/stats/finders.js +9 -5
  232. package/dist/stats/mapping.d.ts +21 -1
  233. package/dist/stats/mapping.js +0 -3
  234. package/package.json +6 -12
  235. package/dist/db/arango.d.ts +0 -2
  236. package/dist/db/arango.js +0 -110
  237. package/dist/db/migration/autoMigrate.d.ts +0 -2
  238. package/dist/db/migration/autoMigrate.js +0 -111
  239. package/dist/db/migration/cli.d.ts +0 -1
  240. package/dist/db/migration/cli.js +0 -56
  241. package/dist/db/migration/detect.d.ts +0 -6
  242. package/dist/db/migration/detect.js +0 -87
  243. package/dist/db/migration/exportArango.d.ts +0 -4
  244. package/dist/db/migration/exportArango.js +0 -80
  245. package/dist/db/migration/importPostgres.d.ts +0 -3
  246. package/dist/db/migration/importPostgres.js +0 -18
  247. package/dist/db/migration/transform.d.ts +0 -18
  248. package/dist/db/migration/transform.js +0 -209
  249. package/dist/db/migration/validate.d.ts +0 -18
  250. package/dist/db/migration/validate.js +0 -69
  251. package/dist/db/pg/sql/meta/0000_snapshot.json +0 -3380
  252. package/dist/db/pg/sql/meta/0004_snapshot.json +0 -4114
  253. package/dist/db/pg/sql/meta/0005_snapshot.json +0 -4179
  254. package/dist/mastodon/index.d.ts +0 -4
  255. package/dist/mastodon/index.js +0 -51
  256. package/dist/mastodon/types.d.ts +0 -7579
  257. package/dist/mastodon/types.js +0 -523
  258. package/dist/mastodon/typescript.d.ts +0 -1578
  259. package/dist/mastodon/typescript.js +0 -1
  260. package/dist/roles/defaults.d.ts +0 -2
  261. package/dist/roles/defaults.js +0 -94
@@ -1,17 +1,27 @@
1
+ import { sql } from 'drizzle-orm';
1
2
  import { allpeepDb } from '../db/index.js';
2
3
  import { uuidv7 } from 'uuidv7';
3
4
  import { nowIso } from '../db/pg/mappers.js';
4
5
  import { postSeen } from '../db/pg/schema/edges.js';
5
- import { audienceConnector, bookmarkConnector, bookmarkDisconnector, entryConnector, extractHashtags, groupConnector, hashtagConnector, hashtagDisconnector, mentionConnector, reactionConnector, reactionDisconnector, replyConnector, repostConnector, resolveMentionsForPost, transformPost, } from './helpers/index.js';
6
+ import { audienceConnector, bookmarkConnector, bookmarkDisconnector, entryConnector, extractHashtags, groupConnector, hashtagConnector, hashtagDisconnector, mentionConnector, replyConnector, repostConnector, resolveMentionsForPost, transformPost, } from './helpers/index.js';
6
7
  import { postsMapping, repostRelation } from './mapping.js';
8
+ import { bumpConversationActivity } from './activity.js';
7
9
  import { findGroup } from '../groups/finders.js';
10
+ import { findLatestThreadPostId } from './conversationQueries.js';
11
+ import { findPostsForAuth } from './finders.js';
12
+ import { profilesCache } from '../profiles/cache.js';
8
13
  import { findOrCreateHashtag } from '../hashtags/index.js';
9
14
  import { hub } from '../events/index.js';
10
- import { listPostsByGroup } from './finders.js';
11
- import { canManageEventRsvps, countYesRsvps, eventDataForDbUpdate, getEffectiveRsvp, normalizeEventDataForSave, passThroughUndefined, } from '@openpeepshq/common/lib';
15
+ import { listUnseenGroupPostIds } from './unseenCounts.js';
16
+ import { AP_LIKE_REACTION, canManageEventRsvps, countYesRsvps, eventDataForDbUpdate, getEffectiveRsvp, instanceRsvpIdsForProfile, overlaySeriesRsvpEntries, normalizeEventDataForSave, passThroughUndefined, rsvpCancelNotice, sameRecurrenceId, seriesYesBlockedByCapacity, } from '@openpeepshq/common/lib';
12
17
  import { forbidden, unprocessableRequest } from '../errors/index.js';
18
+ import { areBlocked, hasBlockAmong } from '../profiles/blocks.js';
19
+ import { rebuildEventOccurrences, clearEventOccurrences, } from './eventOccurrences.js';
20
+ import { cancelPollEnd, schedulePollEnd } from './pollEndJobs.js';
21
+ import { config } from '../config/index.js';
22
+ import { localObjectScalars } from '../federation/identity.js';
13
23
  export const createPost = async (data, profile, postData, relations = {}) => {
14
- var _a;
24
+ var _a, _b;
15
25
  if (data.type === 'event') {
16
26
  data = normalizeEventDataForSave(data);
17
27
  }
@@ -25,6 +35,17 @@ export const createPost = async (data, profile, postData, relations = {}) => {
25
35
  if (repliedToPost) {
26
36
  postData.visibility = repliedToPost.visibility;
27
37
  }
38
+ if (repliedToPost &&
39
+ (await areBlocked(db, profile.id, repliedToPost.creatorId))) {
40
+ throw forbidden({ errorKey: 'error.cannotInteractBlocked' });
41
+ }
42
+ const audienceIds = [
43
+ profile.id,
44
+ ...((_a = relations.audience) !== null && _a !== void 0 ? _a : []).map((member) => member.id),
45
+ ];
46
+ if (await hasBlockAmong(db, audienceIds)) {
47
+ throw forbidden({ errorKey: 'error.cannotInteractBlocked' });
48
+ }
28
49
  const group = await ((repliedToPost === null || repliedToPost === void 0 ? void 0 : repliedToPost.group) ||
29
50
  (relations.groupId ? findGroup(relations.groupId) : undefined));
30
51
  // Group-linked posts always use visibility=group so community/local feeds
@@ -33,15 +54,17 @@ export const createPost = async (data, profile, postData, relations = {}) => {
33
54
  postData = Object.assign(Object.assign({}, postData), { visibility: 'group' });
34
55
  }
35
56
  const hashtags = extractHashtags(data);
36
- const post = await postsMapping
37
- .removeDefaultFilter()
38
- .create(db, Object.assign(Object.assign({}, postData), { data, type: data.type, creatorId: profile.id }));
57
+ const id = uuidv7();
58
+ const domain = (await config()).activityPub.defaultDomain;
59
+ const object = localObjectScalars(id, domain, relations.inReplyToId);
60
+ const post = await postsMapping.removeDefaultFilter().create(db, Object.assign(Object.assign(Object.assign({ id }, postData), object), { data, type: data.type, creatorId: profile.id }));
39
61
  await entryConnector(db, profile, post, {
40
62
  type: 'create',
41
63
  data,
42
64
  });
43
65
  if (repliedToPost) {
44
66
  await replyConnector(db, post, repliedToPost);
67
+ await bumpConversationActivity(db, post.id);
45
68
  }
46
69
  if (group) {
47
70
  await groupConnector(db, post, group);
@@ -57,7 +80,7 @@ export const createPost = async (data, profile, postData, relations = {}) => {
57
80
  if (mentions.length) {
58
81
  await Promise.all(mentions.map(async (mention) => mentionConnector(db, post, mention.profile, { text: mention.text })));
59
82
  }
60
- const audienceToLink = ((_a = relations.audience) === null || _a === void 0 ? void 0 : _a.length)
83
+ const audienceToLink = ((_b = relations.audience) === null || _b === void 0 ? void 0 : _b.length)
61
84
  ? relations.audience
62
85
  : repliedToPost === null || repliedToPost === void 0 ? void 0 : repliedToPost.audience;
63
86
  if (audienceToLink === null || audienceToLink === void 0 ? void 0 : audienceToLink.length) {
@@ -67,6 +90,12 @@ export const createPost = async (data, profile, postData, relations = {}) => {
67
90
  }
68
91
  const newPost = await postsMapping.find(db, post.id);
69
92
  const transformedPost = await transformPost(newPost);
93
+ if (data.type === 'event') {
94
+ await rebuildEventOccurrences(transformedPost.id, data);
95
+ }
96
+ if (data.type === 'question') {
97
+ await schedulePollEnd(transformedPost.id, data.expiresAt);
98
+ }
70
99
  hub.emit('postCreated', transformedPost);
71
100
  return transformedPost;
72
101
  };
@@ -94,11 +123,28 @@ export const updatePost = async (post, profile, data) => {
94
123
  const newPost = await postsMapping
95
124
  .find(db, post.id)
96
125
  .then(passThroughUndefined(transformPost));
126
+ if (normalized.type === 'event') {
127
+ await rebuildEventOccurrences(post.id, normalized);
128
+ }
129
+ if (normalized.type === 'question') {
130
+ await schedulePollEnd(post.id, normalized.expiresAt);
131
+ }
132
+ else {
133
+ await cancelPollEnd(post.id);
134
+ }
97
135
  hub.emit('postUpdated', newPost);
98
136
  return newPost;
99
137
  };
100
- export const reactToPost = async (post, profile, data) => allpeepDb().then(({ db }) => reactionConnector(db, profile, post, data).then(() => hub.emit('reactionCreated', profile, post, Object.assign({ type: 'reaction' }, data))));
101
- export const retractReaction = async (post, profile) => allpeepDb().then(({ db }) => reactionDisconnector(db, profile, post));
138
+ export const reactToPost = async (post, profile, data) => allpeepDb().then(({ db }) => entryConnector(db, profile, post, {
139
+ type: 'reaction',
140
+ data: { reaction: data.reaction },
141
+ })
142
+ .then(() => bumpConversationActivity(db, post.id))
143
+ .then(() => hub.emit('reactionCreated', profile, post, Object.assign({ type: 'reaction' }, data))));
144
+ export const retractReaction = async (post, profile) => allpeepDb().then(({ db }) => entryConnector(db, profile, post, {
145
+ type: 'unreaction',
146
+ data: { reaction: AP_LIKE_REACTION },
147
+ }));
102
148
  export const bookmarkPost = async (post, profile) => allpeepDb().then(({ db }) => bookmarkConnector(db, profile, post).then(() => hub.emit('bookmarkCreated', profile, post)));
103
149
  export const unbookmarkPost = async (post, profile) => allpeepDb().then(({ db }) => bookmarkDisconnector(db, profile, post));
104
150
  export const markPostsSeen = async (posts, profile) => {
@@ -106,30 +152,23 @@ export const markPostsSeen = async (posts, profile) => {
106
152
  return;
107
153
  const { db } = await allpeepDb();
108
154
  const ts = nowIso();
109
- await db
110
- .insert(postSeen)
111
- .values(posts.map((post) => ({
155
+ await db.insert(postSeen).values(posts.map((post) => ({
112
156
  id: uuidv7(),
113
157
  fromId: profile.id,
114
158
  toId: post.id,
115
159
  body: {},
116
160
  createdAt: ts,
117
161
  updatedAt: ts,
118
- })))
119
- .onConflictDoNothing({
120
- target: [postSeen.fromId, postSeen.toId],
121
- });
162
+ })));
122
163
  };
123
164
  export const markGroupPostsSeen = async (authData, groupId) => {
124
165
  if (!authData.profile) {
125
166
  throw new Error('Profile required');
126
167
  }
127
168
  const profile = authData.profile;
128
- const posts = await listPostsByGroup(authData, groupId, { limit: 9999 });
129
- const unseen = posts.filter((post) => post.seen === false && post.profile.id !== profile.id);
130
- if (unseen.length > 0) {
131
- await markPostsSeen(unseen, profile);
132
- }
169
+ const { db } = await allpeepDb();
170
+ const unseenIds = await listUnseenGroupPostIds(db, profile.id, groupId);
171
+ await markPostsSeen(unseenIds.map((id) => ({ id })), profile);
133
172
  };
134
173
  export const deletePost = async (post, profile) => {
135
174
  const { db } = await allpeepDb();
@@ -139,17 +178,29 @@ export const deletePost = async (post, profile) => {
139
178
  type: 'tombstone',
140
179
  },
141
180
  });
142
- await Promise.all(post.reactions.map(async (reaction) => {
143
- await reactionDisconnector(db, reaction.profile, post);
144
- }));
145
181
  await postsMapping.deleteRelations(db, post.id, Object.assign(Object.assign({}, repostRelation), { direction: 'INBOUND' }));
146
182
  await postsMapping.delete(db, post.id);
183
+ if (post.type === 'event') {
184
+ await clearEventOccurrences(post.id);
185
+ }
186
+ if (post.type === 'question') {
187
+ await cancelPollEnd(post.id);
188
+ }
147
189
  return postsMapping.find(db, post.id);
148
190
  };
149
191
  export const vote = (profile, post, data) => allpeepDb().then(({ db }) => entryConnector(db, profile, post, {
150
192
  type: 'answer',
151
193
  data,
152
194
  }).then(() => hub.emit('entryCreated', profile, post, { type: 'answer', data })));
195
+ const attendingRsvp = (response) => response === 'yes' || response === 'tentative';
196
+ const rsvpOccurrenceIds = (data) => {
197
+ var _a;
198
+ if ((_a = data.recurrenceIds) === null || _a === void 0 ? void 0 : _a.length)
199
+ return data.recurrenceIds;
200
+ if (data.recurrenceId)
201
+ return [data.recurrenceId];
202
+ return undefined;
203
+ };
153
204
  export const rsvpRespond = async (profile, post, data) => {
154
205
  var _a, _b, _c, _d;
155
206
  if (profile.id === post.profile.id) {
@@ -167,6 +218,7 @@ export const rsvpRespond = async (profile, post, data) => {
167
218
  if (((_b = getEffectiveRsvp(post, profile.id)) === null || _b === void 0 ? void 0 : _b.response) === 'removed') {
168
219
  throw forbidden({ errorKey: 'error.rsvpRemoved' });
169
220
  }
221
+ const occurrenceIds = rsvpOccurrenceIds(data);
170
222
  const maxAttendees = post.data.maxAttendees;
171
223
  if (maxAttendees) {
172
224
  if (data.response === 'tentative') {
@@ -175,28 +227,54 @@ export const rsvpRespond = async (profile, post, data) => {
175
227
  });
176
228
  }
177
229
  if (data.response === 'yes') {
178
- const currentRsvp = getEffectiveRsvp(post, profile.id);
179
- if ((currentRsvp === null || currentRsvp === void 0 ? void 0 : currentRsvp.response) !== 'yes' &&
180
- countYesRsvps(post) >= maxAttendees) {
181
- throw unprocessableRequest({ errorKey: 'error.eventAtCapacity' });
230
+ if (!occurrenceIds && post.data.recurrence) {
231
+ if (seriesYesBlockedByCapacity(post, profile.id)) {
232
+ throw unprocessableRequest({ errorKey: 'error.eventAtCapacity' });
233
+ }
234
+ }
235
+ else {
236
+ const ids = occurrenceIds !== null && occurrenceIds !== void 0 ? occurrenceIds : [undefined];
237
+ for (const recurrenceId of ids) {
238
+ const currentRsvp = getEffectiveRsvp(post, profile.id, recurrenceId);
239
+ if ((currentRsvp === null || currentRsvp === void 0 ? void 0 : currentRsvp.response) !== 'yes' &&
240
+ countYesRsvps(post, recurrenceId) >= maxAttendees) {
241
+ throw unprocessableRequest({ errorKey: 'error.eventAtCapacity' });
242
+ }
243
+ }
182
244
  }
183
245
  }
184
246
  }
185
247
  const { db } = await allpeepDb();
186
- const previousResponse = (_d = [...((_c = post.rsvps) !== null && _c !== void 0 ? _c : [])]
187
- .filter((rsvp) => rsvp.profile.id === profile.id)
188
- .sort((a, b) => (a.createdAt < b.createdAt ? 1 : -1))[0]) === null || _d === void 0 ? void 0 : _d.response;
189
- await entryConnector(db, profile, post, {
190
- type: 'rsvp',
191
- data,
192
- });
193
- hub.emit('rsvpCreated', profile, post, {
194
- type: 'rsvp',
195
- data,
196
- previousResponse,
197
- });
248
+ const previousResponses = occurrenceIds
249
+ ? occurrenceIds.map((id) => { var _a; return (_a = getEffectiveRsvp(post, profile.id, id)) === null || _a === void 0 ? void 0 : _a.response; })
250
+ : undefined;
251
+ const previousResponse = previousResponses
252
+ ? previousResponses.every(attendingRsvp)
253
+ ? previousResponses[0]
254
+ : previousResponses.find((response) => !attendingRsvp(response))
255
+ : (_d = [...((_c = post.rsvps) !== null && _c !== void 0 ? _c : [])]
256
+ .filter((rsvp) => rsvp.profile.id === profile.id)
257
+ .filter((rsvp) => !rsvp.recurrenceId)
258
+ .sort((a, b) => (a.createdAt < b.createdAt ? 1 : -1))[0]) === null || _d === void 0 ? void 0 : _d.response;
259
+ const writes = occurrenceIds
260
+ ? occurrenceIds.map((recurrenceId) => ({
261
+ response: data.response,
262
+ recurrenceId,
263
+ }))
264
+ : overlaySeriesRsvpEntries(data.response, instanceRsvpIdsForProfile(post, profile.id));
265
+ for (const entry of writes) {
266
+ await entryConnector(db, profile, post, {
267
+ type: 'rsvp',
268
+ data: entry,
269
+ });
270
+ }
271
+ const cancel = rsvpCancelNotice(post, profile.id, data.response, occurrenceIds);
272
+ hub.emit('rsvpCreated', profile, post, Object.assign({ type: 'rsvp', data: Object.assign({ response: data.response }, ((occurrenceIds === null || occurrenceIds === void 0 ? void 0 : occurrenceIds.length) === 1
273
+ ? { recurrenceId: occurrenceIds[0] }
274
+ : {})), occurrenceIds,
275
+ previousResponse }, (cancel ? { cancel } : {})));
198
276
  };
199
- export const rsvpManageByOrganizer = async (actingProfile, targetProfile, post, response) => {
277
+ export const rsvpManageByOrganizer = async (actingProfile, targetProfile, post, response, recurrenceId) => {
200
278
  var _a, _b;
201
279
  if (!canManageEventRsvps(actingProfile, post)) {
202
280
  throw forbidden({ errorKey: 'forbidden' });
@@ -207,10 +285,14 @@ export const rsvpManageByOrganizer = async (actingProfile, targetProfile, post,
207
285
  if (post.type !== 'event') {
208
286
  throw unprocessableRequest({ errorKey: 'error.unprocessableRequest' });
209
287
  }
210
- const data = { response };
288
+ const data = { response, recurrenceId };
211
289
  const { db } = await allpeepDb();
212
290
  const previousResponse = (_b = [...((_a = post.rsvps) !== null && _a !== void 0 ? _a : [])]
213
291
  .filter((rsvp) => rsvp.profile.id === targetProfile.id)
292
+ .filter((rsvp) => recurrenceId
293
+ ? sameRecurrenceId(rsvp.recurrenceId, recurrenceId) ||
294
+ !rsvp.recurrenceId
295
+ : !rsvp.recurrenceId)
214
296
  .sort((a, b) => (a.createdAt < b.createdAt ? 1 : -1))[0]) === null || _b === void 0 ? void 0 : _b.response;
215
297
  await entryConnector(db, targetProfile, post, {
216
298
  type: 'rsvp',
@@ -222,3 +304,55 @@ export const rsvpManageByOrganizer = async (actingProfile, targetProfile, post,
222
304
  previousResponse,
223
305
  });
224
306
  };
307
+ /**
308
+ * Remove a profile from a direct-message conversation thread.
309
+ *
310
+ * - Creates a system "X left" post (empty content) with the *remaining*
311
+ * participants as audience. The leaving user is excluded so future
312
+ * replies (which inherit the audience) won't notify them, and the thread
313
+ * disappears from their inbox.
314
+ * - MessageInThread detects the leave via the audience diff: the leaving
315
+ * user was in the previous post's audience but not in the left-post's.
316
+ * - The conversation post-creation endpoint detects leavers (author not in
317
+ * their own post's audience) to block further posting and exclude them
318
+ * from future replies' audience.
319
+ * - For 1:1 DMs (no remaining participants), removes the user from every
320
+ * post's audience so the thread vanishes from their inbox.
321
+ * - The leaving user can still find the thread in the "Archived" conversations
322
+ * tab, detected by posts they authored but are not in.
323
+ */
324
+ export const leaveConversation = async (rootPost, profile) => {
325
+ var _a, _b;
326
+ const { db } = await allpeepDb();
327
+ const lastPostId = await findLatestThreadPostId(rootPost.id);
328
+ const [lastPost] = lastPostId === rootPost.id
329
+ ? [rootPost]
330
+ : await findPostsForAuth([lastPostId]);
331
+ if (!lastPost)
332
+ return;
333
+ const remainingAudience = (_b = (_a = lastPost.audience) === null || _a === void 0 ? void 0 : _a.filter((p) => p.id !== profile.id)) !== null && _b !== void 0 ? _b : [];
334
+ if (remainingAudience.length > 0) {
335
+ await createPost({ type: 'note', content: '' }, profile, { type: 'note', visibility: 'direct', creatorId: profile.id }, {
336
+ inReplyToId: lastPost.id,
337
+ audience: remainingAudience,
338
+ });
339
+ }
340
+ else {
341
+ // 1:1 DM — remove the user from every post's audience so the
342
+ // thread no longer appears in their inbox.
343
+ await db.execute(sql `
344
+ WITH RECURSIVE t AS (
345
+ SELECT ${rootPost.id}::text AS id, 0 AS depth
346
+ UNION ALL
347
+ SELECT rt.from_id::text, t.depth + 1
348
+ FROM reply_to rt
349
+ INNER JOIN t ON rt.to_id = t.id
350
+ WHERE t.depth < 9999
351
+ )
352
+ DELETE FROM audience
353
+ WHERE from_id IN (SELECT id FROM t)
354
+ AND to_id = ${profile.id}
355
+ `);
356
+ }
357
+ await profilesCache.del(profile.id);
358
+ };
@@ -0,0 +1,3 @@
1
+ import type { PostWithMeta } from '@openpeepshq/common/types';
2
+ export declare const pollEndDelayMs: (expiresAt: string, now?: number) => number;
3
+ export declare const shouldEmitPollEnded: (post: PostWithMeta | undefined, scheduledExpiresAt: string) => post is PostWithMeta;
@@ -0,0 +1,7 @@
1
+ export const pollEndDelayMs = (expiresAt, now = Date.now()) => new Date(expiresAt).getTime() - now;
2
+ export const shouldEmitPollEnded = (post, scheduledExpiresAt) => {
3
+ var _a;
4
+ return !!post &&
5
+ ((_a = post.data) === null || _a === void 0 ? void 0 : _a.type) === 'question' &&
6
+ post.data.expiresAt === scheduledExpiresAt;
7
+ };
@@ -0,0 +1,8 @@
1
+ export interface PollEndJobData {
2
+ postId: string;
3
+ expiresAt: string;
4
+ }
5
+ declare const pollEndQueue: () => import("bullmq").Queue, pollEndWorker: () => import("bullmq").Worker;
6
+ export declare const schedulePollEnd: (postId: string, expiresAt?: string) => Promise<void>;
7
+ export declare const cancelPollEnd: (postId: string) => Promise<void>;
8
+ export { pollEndQueue, pollEndWorker };
@@ -0,0 +1,49 @@
1
+ import { queueAndWorker } from '../jobs/index.js';
2
+ import { logger } from '../log/index.js';
3
+ import { hub } from '../events/index.js';
4
+ import { findPost } from './finders.js';
5
+ import { pollEndDelayMs, shouldEmitPollEnded } from './pollEnd.js';
6
+ const log = logger('app:posts:pollEnd');
7
+ const pollEndJobId = (postId) => `poll-end:${postId}`;
8
+ const [pollEndQueue, pollEndWorker] = queueAndWorker('poll-end', async (job) => {
9
+ const post = await findPost(job.data.postId);
10
+ if (!shouldEmitPollEnded(post, job.data.expiresAt)) {
11
+ log.info(`Skipping poll-end for ${job.data.postId}`);
12
+ return;
13
+ }
14
+ log.info(`Poll ended ${job.data.postId}`);
15
+ await hub.emit('pollEnded', post);
16
+ }, {
17
+ defaultJobOptions: {
18
+ removeOnComplete: { age: 86400 },
19
+ removeOnFail: { age: 86400 * 7, count: 50 },
20
+ },
21
+ });
22
+ export const schedulePollEnd = async (postId, expiresAt) => {
23
+ try {
24
+ const queue = pollEndQueue();
25
+ const jobId = pollEndJobId(postId);
26
+ await queue.remove(jobId).catch(() => undefined);
27
+ if (!expiresAt) {
28
+ return;
29
+ }
30
+ const delay = pollEndDelayMs(expiresAt);
31
+ if (delay <= 0) {
32
+ return;
33
+ }
34
+ await queue.add('end', { postId, expiresAt }, { jobId, delay });
35
+ }
36
+ catch (err) {
37
+ log.error({ err, postId }, 'Failed to schedule poll-end job');
38
+ }
39
+ };
40
+ export const cancelPollEnd = async (postId) => {
41
+ try {
42
+ const queue = pollEndQueue();
43
+ await queue.remove(pollEndJobId(postId));
44
+ }
45
+ catch (err) {
46
+ log.error({ err, postId }, 'Failed to cancel poll-end job');
47
+ }
48
+ };
49
+ export { pollEndQueue, pollEndWorker };
@@ -0,0 +1,10 @@
1
+ import type { PgDb } from '../db/pg/client';
2
+ export declare const CONTEXT_NODE_CAP = 100;
3
+ type ClosureDirection = 'ancestors' | 'descendents';
4
+ /** Collect reply-graph ids via one recursive CTE (capped). */
5
+ export declare const collectReplyClosureIds: (db: PgDb, startId: string, direction: ClosureDirection, { maxDepth, limit, newestFirst, }?: {
6
+ maxDepth?: number;
7
+ limit?: number;
8
+ newestFirst?: boolean;
9
+ }) => Promise<string[]>;
10
+ export {};
@@ -0,0 +1,43 @@
1
+ import { sql } from 'drizzle-orm';
2
+ export const CONTEXT_NODE_CAP = 100;
3
+ /** Collect reply-graph ids via one recursive CTE (capped). */
4
+ export const collectReplyClosureIds = async (db, startId, direction, { maxDepth = 9999, limit = CONTEXT_NODE_CAP,
5
+ /** Newest-first by uuidv7 id (useful for long DM threads). */
6
+ newestFirst = false, } = {}) => {
7
+ if (!startId || limit <= 0)
8
+ return [];
9
+ const orderClause = newestFirst ? sql `ORDER BY id DESC` : sql ``;
10
+ const query = direction === 'ancestors'
11
+ ? sql `
12
+ WITH RECURSIVE t AS (
13
+ SELECT to_id AS id, 1 AS depth
14
+ FROM reply_to
15
+ WHERE from_id = ${startId}
16
+ UNION ALL
17
+ SELECT r.to_id, t.depth + 1
18
+ FROM reply_to r
19
+ INNER JOIN t ON r.from_id = t.id
20
+ WHERE t.depth < ${maxDepth}
21
+ )
22
+ SELECT id FROM t
23
+ ${orderClause}
24
+ LIMIT ${limit}
25
+ `
26
+ : sql `
27
+ WITH RECURSIVE t AS (
28
+ SELECT from_id AS id, 1 AS depth
29
+ FROM reply_to
30
+ WHERE to_id = ${startId}
31
+ UNION ALL
32
+ SELECT r.from_id, t.depth + 1
33
+ FROM reply_to r
34
+ INNER JOIN t ON r.to_id = t.id
35
+ WHERE t.depth < ${maxDepth}
36
+ )
37
+ SELECT id FROM t
38
+ ${orderClause}
39
+ LIMIT ${limit}
40
+ `;
41
+ const result = (await db.execute(query));
42
+ return result.rows.map((row) => row.id);
43
+ };
@@ -1,7 +1,8 @@
1
- import { buildEventIcs } from '@openpeepshq/common/lib';
1
+ import { rsvpConfirmationContent } from '@openpeepshq/common/lib';
2
2
  import { hub } from '../events/index.js';
3
3
  import { emailService } from '../email/index.js';
4
4
  import { findByProfile } from '../accounts/index.js';
5
+ import { findProfileSettings } from '../profileSettings/index.js';
5
6
  import { serverRootUrl } from '../server/index.js';
6
7
  import { logger } from '../log/index.js';
7
8
  const log = logger('openpeeps:rsvp-email');
@@ -13,7 +14,7 @@ const attendingResponses = ['yes', 'tentative'];
13
14
  * avoid re-sending when someone toggles between yes/maybe.
14
15
  */
15
16
  const handleRsvpCreated = async (profileArg, postArg, payloadArg) => {
16
- var _a, _b, _c, _d, _e, _f, _g;
17
+ var _a, _b, _c;
17
18
  const profile = profileArg;
18
19
  const post = postArg;
19
20
  const payload = payloadArg;
@@ -33,16 +34,20 @@ const handleRsvpCreated = async (profileArg, postArg, payloadArg) => {
33
34
  }
34
35
  const rootUrl = await serverRootUrl();
35
36
  const postUrl = `${rootUrl}/posts/${post.id}`;
36
- const ics = buildEventIcs(post, { postUrl });
37
- if (!ics) {
37
+ const occurrenceIds = (_c = payload.occurrenceIds) !== null && _c !== void 0 ? _c : (payload.data.recurrenceId ? [payload.data.recurrenceId] : undefined);
38
+ const confirmation = rsvpConfirmationContent(post, {
39
+ postUrl,
40
+ occurrenceIds,
41
+ });
42
+ if (!confirmation) {
38
43
  return;
39
44
  }
40
45
  const accounts = await findByProfile(profile);
41
46
  if (!accounts.length) {
42
47
  return;
43
48
  }
44
- const event = post.data;
45
49
  const mailer = await emailService();
50
+ const profileSettings = await findProfileSettings(profile.id);
46
51
  for (const account of accounts) {
47
52
  if (!account.email) {
48
53
  continue;
@@ -51,19 +56,13 @@ const handleRsvpCreated = async (profileArg, postArg, payloadArg) => {
51
56
  .send({
52
57
  to: account.email,
53
58
  template: 'eventRsvpConfirmation',
54
- locals: {
55
- eventName: ((_c = event.name) === null || _c === void 0 ? void 0 : _c.trim()) || 'Event',
56
- eventUrl: postUrl,
57
- response,
58
- start: event.start,
59
- end: (_d = event.end) !== null && _d !== void 0 ? _d : null,
60
- location: (_f = (_e = event.physicalLocation) === null || _e === void 0 ? void 0 : _e.text) !== null && _f !== void 0 ? _f : null,
61
- allDay: (_g = event.wholeDay) !== null && _g !== void 0 ? _g : false,
62
- },
59
+ locals: Object.assign({ eventName: confirmation.eventName, eventUrl: postUrl, response, start: confirmation.start, end: confirmation.end, location: confirmation.location, allDay: confirmation.allDay, occurrenceCount: confirmation.occurrenceCount }, ((profileSettings === null || profileSettings === void 0 ? void 0 : profileSettings.timeZone)
60
+ ? { timeZone: profileSettings.timeZone }
61
+ : {})),
63
62
  attachments: [
64
63
  {
65
64
  filename: 'event.ics',
66
- content: ics,
65
+ content: confirmation.ics,
67
66
  contentType: 'text/calendar; method=PUBLISH; charset=utf-8',
68
67
  },
69
68
  ],
@@ -0,0 +1,8 @@
1
+ import type { DbPost } from '@openpeepshq/common/types';
2
+ export declare const THREAD_PREVIEW_LIMIT = 3;
3
+ export declare const loadThreadPreviewReplies: (rootId: string, currentProfile?: {
4
+ id: string;
5
+ }) => Promise<{
6
+ replies: DbPost[];
7
+ hasMore: boolean;
8
+ }>;
@@ -0,0 +1,44 @@
1
+ import { allpeepDb } from '../db/index.js';
2
+ import { fetchRowsByIds, hydrateMapData } from '../db/pg/map/relations.js';
3
+ import { collectReplyClosureIds } from './replyClosure.js';
4
+ import { EMBEDDED_LATEST_REPLIES_LIMIT, threadPreviewMappingForProfile, } from './mapping.js';
5
+ export const THREAD_PREVIEW_LIMIT = EMBEDDED_LATEST_REPLIES_LIMIT;
6
+ export const loadThreadPreviewReplies = async (rootId, currentProfile) => {
7
+ if (!rootId)
8
+ return { replies: [], hasMore: false };
9
+ const { db } = await allpeepDb();
10
+ const ids = await collectReplyClosureIds(db, rootId, 'descendents', {
11
+ newestFirst: true,
12
+ limit: THREAD_PREVIEW_LIMIT + 1,
13
+ });
14
+ const hasMore = ids.length > THREAD_PREVIEW_LIMIT;
15
+ const previewIds = ids.slice(0, THREAD_PREVIEW_LIMIT);
16
+ if (!previewIds.length)
17
+ return { replies: [], hasMore: false };
18
+ const mapData = threadPreviewMappingForProfile(currentProfile).data();
19
+ const rows = await fetchRowsByIds(db, mapData.collection, previewIds, mapData.softDelete);
20
+ const hydrated = (await hydrateMapData(db, mapData, rows));
21
+ const byPreviewId = new Map(hydrated.map((post) => [post.id, post]));
22
+ const parentIds = [
23
+ ...new Set(hydrated
24
+ .map((post) => post.inReplyToId)
25
+ .filter((id) => !!id && id !== rootId && !byPreviewId.has(id))),
26
+ ];
27
+ let parents = [];
28
+ if (parentIds.length) {
29
+ const parentRows = await fetchRowsByIds(db, mapData.collection, parentIds, mapData.softDelete);
30
+ parents = (await hydrateMapData(db, mapData, parentRows));
31
+ }
32
+ const byId = new Map([...hydrated, ...parents].map((post) => [post.id, post]));
33
+ const replies = previewIds
34
+ .map((id) => byPreviewId.get(id))
35
+ .filter((post) => !!post)
36
+ .map((post) => {
37
+ const parentId = post.inReplyToId;
38
+ if (!parentId || parentId === rootId)
39
+ return post;
40
+ const parent = byId.get(parentId);
41
+ return parent ? Object.assign(Object.assign({}, post), { replyTo: parent }) : post;
42
+ });
43
+ return { replies, hasMore };
44
+ };
@@ -2,6 +2,8 @@ import type { UnseenPostCounts } from '@openpeepshq/common/types';
2
2
  import type { PgDb } from '../db/pg/client';
3
3
  /** Group unseen counts via anti-join (no post hydration). */
4
4
  export declare const countUnseenGroupPosts: (db: PgDb, profileId: string, groupIds: string[]) => Promise<Record<string, number>>;
5
+ /** Same posts as {@link countUnseenGroupPosts} for one group (mark-all-read). */
6
+ export declare const listUnseenGroupPostIds: (db: PgDb, profileId: string, groupId: string) => Promise<string[]>;
5
7
  /**
6
8
  * Direct-message unread counts keyed by conversation root.
7
9
  * Walks reply_to to roots without hydrating posts.
@@ -1,4 +1,18 @@
1
1
  import { sql } from 'drizzle-orm';
2
+ /** Shared predicates for group unseen count and mark-all-read.
3
+ * Includes replies to group posts, not just top-level posts — replies carry
4
+ * the same groupId and should contribute to the group unread badge.
5
+ */
6
+ const unseenGroupPostMatch = (profileId) => sql `
7
+ p.visibility <> 'direct'
8
+ AND p.creator_id <> ${profileId}
9
+ AND NOT EXISTS (
10
+ SELECT 1
11
+ FROM post_seen ps
12
+ WHERE ps.from_id = ${profileId}
13
+ AND ps.to_id = p.id::text
14
+ )
15
+ `;
2
16
  /** Group unseen counts via anti-join (no post hydration). */
3
17
  export const countUnseenGroupPosts = async (db, profileId, groupIds) => {
4
18
  const counts = Object.fromEntries(groupIds.map((groupId) => [groupId, 0]));
@@ -11,14 +25,7 @@ export const countUnseenGroupPosts = async (db, profileId, groupIds) => {
11
25
  ON p.id::text = pg.from_id
12
26
  AND p.deleted_at IS NULL
13
27
  WHERE pg.to_id IN (${sql.join(groupIds.map((id) => sql `${id}`), sql `, `)})
14
- AND p.visibility <> 'direct'
15
- AND p.creator_id <> ${profileId}
16
- AND NOT EXISTS (
17
- SELECT 1
18
- FROM post_seen ps
19
- WHERE ps.from_id = ${profileId}
20
- AND ps.to_id = p.id::text
21
- )
28
+ AND ${unseenGroupPostMatch(profileId)}
22
29
  GROUP BY pg.to_id
23
30
  `));
24
31
  for (const row of result.rows) {
@@ -29,6 +36,19 @@ export const countUnseenGroupPosts = async (db, profileId, groupIds) => {
29
36
  }
30
37
  return counts;
31
38
  };
39
+ /** Same posts as {@link countUnseenGroupPosts} for one group (mark-all-read). */
40
+ export const listUnseenGroupPostIds = async (db, profileId, groupId) => {
41
+ const result = (await db.execute(sql `
42
+ SELECT p.id::text AS post_id
43
+ FROM post_groups pg
44
+ INNER JOIN posts p
45
+ ON p.id::text = pg.from_id
46
+ AND p.deleted_at IS NULL
47
+ WHERE pg.to_id = ${groupId}
48
+ AND ${unseenGroupPostMatch(profileId)}
49
+ `));
50
+ return result.rows.map((row) => row.post_id).filter((id) => !!id);
51
+ };
32
52
  /**
33
53
  * Direct-message unread counts keyed by conversation root.
34
54
  * Walks reply_to to roots without hydrating posts.