@rocapine/community 0.12.0 → 0.13.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rocapine/community",
3
- "version": "0.12.0",
3
+ "version": "0.13.0",
4
4
  "description": "CLI to install, upgrade and adopt the Rocapine Community SDK's Supabase backend (migrations, Edge Functions) into a project.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -32,6 +32,7 @@ type LocaleCopy = Record<string, CopyValue>;
32
32
  export type PushCopyKey =
33
33
  | "fallbackName"
34
34
  | "comment.title"
35
+ | "reply.title"
35
36
  | "like.one"
36
37
  | "like.many"
37
38
  | "reaction.one"
@@ -43,6 +44,7 @@ const BUILTIN: Record<string, LocaleCopy> = {
43
44
  fallbackName: "Someone",
44
45
  photo: "📷 Photo",
45
46
  "comment.title": "You received a comment",
47
+ "reply.title": "You received a reply",
46
48
  "like.one": "{name} liked your post",
47
49
  "like.many": {
48
50
  one: "{name} and {count} other liked your post",
@@ -58,6 +60,7 @@ const BUILTIN: Record<string, LocaleCopy> = {
58
60
  fallbackName: "Alguém",
59
61
  photo: "📷 Foto",
60
62
  "comment.title": "Recebeste um comentário",
63
+ "reply.title": "Recebeste uma resposta",
61
64
  "like.one": "{name} gostou da tua publicação",
62
65
  "like.many": {
63
66
  one: "{name} e mais {count} pessoa gostou da tua publicação",
@@ -73,6 +76,7 @@ const BUILTIN: Record<string, LocaleCopy> = {
73
76
  fallbackName: "Alguém",
74
77
  photo: "📷 Foto",
75
78
  "comment.title": "Você recebeu um comentário",
79
+ "reply.title": "Você recebeu uma resposta",
76
80
  "like.one": "{name} curtiu seu post",
77
81
  "like.many": {
78
82
  one: "{name} e mais {count} pessoa curtiu seu post",
@@ -88,6 +92,7 @@ const BUILTIN: Record<string, LocaleCopy> = {
88
92
  fallbackName: "Alguien",
89
93
  photo: "📷 Foto",
90
94
  "comment.title": "Has recibido un comentario",
95
+ "reply.title": "Has recibido una respuesta",
91
96
  "like.one": "A {name} le ha gustado tu publicación",
92
97
  "like.many": {
93
98
  one: "A {name} y a {count} persona más les ha gustado tu publicación",
@@ -103,6 +108,7 @@ const BUILTIN: Record<string, LocaleCopy> = {
103
108
  fallbackName: "Alguien",
104
109
  photo: "📷 Foto",
105
110
  "comment.title": "Recibiste un comentario",
111
+ "reply.title": "Recibiste una respuesta",
106
112
  "like.one": "A {name} le gustó tu publicación",
107
113
  "like.many": {
108
114
  one: "A {name} y a {count} persona más les gustó tu publicación",
@@ -118,6 +124,7 @@ const BUILTIN: Record<string, LocaleCopy> = {
118
124
  fallbackName: "Qualcuno",
119
125
  photo: "📷 Foto",
120
126
  "comment.title": "Hai ricevuto un commento",
127
+ "reply.title": "Hai ricevuto una risposta",
121
128
  "like.one": "A {name} piace il tuo post",
122
129
  "like.many": {
123
130
  one: "A {name} e ad altra {count} persona piace il tuo post",
@@ -133,6 +140,7 @@ const BUILTIN: Record<string, LocaleCopy> = {
133
140
  fallbackName: "Ktoś",
134
141
  photo: "📷 Zdjęcie",
135
142
  "comment.title": "Masz nowy komentarz",
143
+ "reply.title": "Masz nową odpowiedź",
136
144
  "like.one": "{name} polubił(a) twój post",
137
145
  "like.many": {
138
146
  one: "{name} i {count} inna osoba polubiły twój post",
@@ -150,6 +158,7 @@ const BUILTIN: Record<string, LocaleCopy> = {
150
158
  fallbackName: "Quelqu'un",
151
159
  photo: "📷 Photo",
152
160
  "comment.title": "Tu as reçu un commentaire",
161
+ "reply.title": "Tu as reçu une réponse",
153
162
  "like.one": "{name} a aimé ta publication",
154
163
  "like.many": {
155
164
  one: "{name} et {count} autre personne ont aimé ta publication",
@@ -165,6 +174,7 @@ const BUILTIN: Record<string, LocaleCopy> = {
165
174
  fallbackName: "Jemand",
166
175
  photo: "📷 Foto",
167
176
  "comment.title": "Du hast einen Kommentar erhalten",
177
+ "reply.title": "Du hast eine Antwort erhalten",
168
178
  "like.one": "{name} gefällt dein Beitrag",
169
179
  "like.many": {
170
180
  one: "{name} und {count} weiterer Person gefällt dein Beitrag",
@@ -13,7 +13,8 @@ export interface ExpoPushMessage {
13
13
  badge?: number;
14
14
  }
15
15
 
16
- /** Unread inbox rows for `uid` (newer than the seen marker), at least 1 since a push
16
+ /** Unread inbox rows for `uid` (newer than the seen marker and not read one by one),
17
+ * capped at 200, at least 1 since a push
17
18
  * is being sent. Falls back to 1 when the inbox module is not installed. */
18
19
  export async function unreadBadge(
19
20
  supabase: { from: (table: string) => any },
@@ -25,14 +26,20 @@ export async function unreadBadge(
25
26
  .select("seen_at")
26
27
  .eq("user_id", uid)
27
28
  .maybeSingle();
28
- let query = supabase
29
- .from("notifications")
30
- .select("*", { count: "exact", head: true })
31
- .eq("user_id", uid);
29
+ let query = supabase.from("notifications").select("id").eq("user_id", uid).limit(200);
32
30
  if (seen?.seen_at) query = query.gt("created_at", seen.seen_at);
33
- const { count, error } = await query;
31
+ const { data: rows, error } = await query;
34
32
  if (error) return 1;
35
- return Math.max(1, count ?? 0);
33
+ const ids = (rows ?? []).map((r: { id: string }) => r.id);
34
+ if (ids.length === 0) return 1;
35
+ // Items marked read one by one (inbox/002_replies_and_reads.sql); a project
36
+ // without that table just counts every row past the watermark.
37
+ const { data: reads } = await supabase
38
+ .from("notification_reads")
39
+ .select("item_id")
40
+ .eq("user_id", uid)
41
+ .in("item_id", ids);
42
+ return Math.max(1, ids.length - (reads?.length ?? 0));
36
43
  } catch {
37
44
  return 1;
38
45
  }
@@ -81,7 +81,7 @@ Deno.serve(async (req) => {
81
81
  to,
82
82
  title,
83
83
  body: excerptFor(locale, profileLocale),
84
- data: { route: "/community", kind: "community_official_post" },
84
+ data: { route: "/community", kind: "community_official_post", postId: post.id },
85
85
  badge: 1,
86
86
  }));
87
87
  await sendExpoPushBatch(messages);
@@ -0,0 +1,77 @@
1
+ {
2
+ "version": "5",
3
+ "specifiers": {
4
+ "jsr:@std/assert@1": "1.0.19",
5
+ "jsr:@std/internal@^1.0.12": "1.0.14",
6
+ "jsr:@supabase/supabase-js@2": "2.116.0",
7
+ "npm:@supabase/auth-js@2.116.0": "2.116.0",
8
+ "npm:@supabase/functions-js@2.116.0": "2.116.0",
9
+ "npm:@supabase/postgrest-js@2.116.0": "2.116.0",
10
+ "npm:@supabase/realtime-js@2.116.0": "2.116.0",
11
+ "npm:@supabase/storage-js@2.116.0": "2.116.0"
12
+ },
13
+ "jsr": {
14
+ "@std/assert@1.0.19": {
15
+ "integrity": "eaada96ee120cb980bc47e040f82814d786fe8162ecc53c91d8df60b8755991e",
16
+ "dependencies": [
17
+ "jsr:@std/internal"
18
+ ]
19
+ },
20
+ "@std/internal@1.0.14": {
21
+ "integrity": "291516b3d4c35024d6ffbc0a9df5bf4c64116e05b50012cf846710152d2ffdf7"
22
+ },
23
+ "@supabase/supabase-js@2.116.0": {
24
+ "integrity": "3005b560a70ba75504f9c11ec48cb05cec71d86d715a3c15be574394963270e0",
25
+ "dependencies": [
26
+ "npm:@supabase/auth-js",
27
+ "npm:@supabase/functions-js",
28
+ "npm:@supabase/postgrest-js",
29
+ "npm:@supabase/realtime-js",
30
+ "npm:@supabase/storage-js"
31
+ ]
32
+ }
33
+ },
34
+ "npm": {
35
+ "@supabase/auth-js@2.116.0": {
36
+ "integrity": "sha512-Cmosty12gyKGK9N3bQb+lMmuAFev5nmUzaR1AsmZHqKOAGzqX1VQzmp49CNPwOx/pw0H9Qqk4rs9yhwTlKpfDg==",
37
+ "dependencies": [
38
+ "tslib"
39
+ ]
40
+ },
41
+ "@supabase/functions-js@2.116.0": {
42
+ "integrity": "sha512-E+VOc2QDcni/fySqkBFiZhnoB3SGydEdZgFI6/dEAGAHx6yEhB46TN9qb2wXs+E+RSzOBV0R6dasiSlw4xlZAA==",
43
+ "dependencies": [
44
+ "tslib"
45
+ ]
46
+ },
47
+ "@supabase/phoenix@0.4.5": {
48
+ "integrity": "sha512-aAn9H9ovVyeApKy11OWOrrOGq8DV68yWeH4ud2lN9fzn4aO8Zb5GLL9m1pUg9nLqIcT+ZDfAcsZe0E/nqdv2lw=="
49
+ },
50
+ "@supabase/postgrest-js@2.116.0": {
51
+ "integrity": "sha512-kGpVZTDHxFTJS3tu+rU0iTAZ+4U0bcLVjxwCk8f3gRhjw3qdCZjTBlgYvc4kGH2XccmAzbkKwXL/mrNHMGSc+A==",
52
+ "dependencies": [
53
+ "tslib"
54
+ ]
55
+ },
56
+ "@supabase/realtime-js@2.116.0": {
57
+ "integrity": "sha512-MHAnlXxi2s6yiJsZsQMfs2B3RFxeVfQWxerqYhIMqcCQV/FuY3LIeouPEkXw/ah7wUWMLYwempF9MOCUScyddg==",
58
+ "dependencies": [
59
+ "@supabase/phoenix",
60
+ "tslib"
61
+ ]
62
+ },
63
+ "@supabase/storage-js@2.116.0": {
64
+ "integrity": "sha512-6/3hR6vccBP6oGM5B6RfbwZcTCKmQOodd/ZWQdsw8yJsU5zO/a//oBL6yLnmgxcjnHSrelW8rsO7hL5DPybyUQ==",
65
+ "dependencies": [
66
+ "iceberg-js",
67
+ "tslib"
68
+ ]
69
+ },
70
+ "iceberg-js@0.8.1": {
71
+ "integrity": "sha512-1dhVQZXhcHje7798IVM+xoo/1ZdVfzOMIc8/rgVSijRK38EDqOJoGula9N/8ZI5RD8QTxNQtK/Gozpr+qUqRRA=="
72
+ },
73
+ "tslib@2.8.1": {
74
+ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="
75
+ }
76
+ }
77
+ }
@@ -1,6 +1,7 @@
1
1
  // Real-time comment notification: a pg_net trigger fires here when a comment
2
- // becomes visible (published). We push to the post author (unless self, opted
3
- // out, no token, or the author has blocked the commenter).
2
+ // becomes visible (published). We push to the post author, or for a reply to
3
+ // the author of the comment it answers only (unless self, opted out, no token,
4
+ // or the recipient has blocked the commenter).
4
5
  //
5
6
  // Security: this function is reachable with the public anon key (the trigger
6
7
  // calls it that way), so the body is UNTRUSTED. Only `record.id` is used; the
@@ -20,7 +21,7 @@ Deno.serve(async (req) => {
20
21
 
21
22
  const { data: comment } = await supabase
22
23
  .from("comments")
23
- .select("id, post_id, author_id, content, status")
24
+ .select("id, post_id, author_id, content, status, parent_id")
24
25
  .eq("id", record.id)
25
26
  .single();
26
27
  if (!comment || comment.status !== "visible") return new Response("skip: not visible");
@@ -30,63 +31,92 @@ Deno.serve(async (req) => {
30
31
  .select("author_id")
31
32
  .eq("id", comment.post_id)
32
33
  .single();
33
- if (!post || post.author_id === comment.author_id) return new Response("skip: self/none");
34
+ if (!post) return new Response("skip: no post");
34
35
 
35
- const { data: pref } = await supabase
36
- .from("push_tokens")
37
- .select("expo_push_token, notify_comments")
38
- .eq("user_id", post.author_id)
39
- .single();
40
- if (!pref?.expo_push_token || !pref.notify_comments) return new Response("skip: no token/pref");
41
-
42
- const { data: blocked } = await supabase
43
- .from("blocks")
44
- .select("blocker_id")
45
- .eq("blocker_id", post.author_id)
46
- .eq("blocked_id", comment.author_id)
47
- .maybeSingle();
48
- if (blocked) return new Response("skip: blocked");
49
-
50
- const { data: recipient } = await supabase
51
- .from("profiles")
52
- .select("locale")
53
- .eq("id", post.author_id)
54
- .single();
55
- const copy = pushCopy(recipient?.locale);
36
+ // A reply pushes only the author of the comment it answers; the post author
37
+ // is pushed for top-level comments (mirrors the inbox trigger,
38
+ // inbox/002_replies_and_reads.sql).
39
+ let parentAuthor: string | null = null;
40
+ if (comment.parent_id) {
41
+ const { data: parent } = await supabase
42
+ .from("comments")
43
+ .select("author_id")
44
+ .eq("id", comment.parent_id)
45
+ .maybeSingle();
46
+ parentAuthor = parent?.author_id ?? null;
47
+ }
48
+ const targets: { uid: string; title: "reply.title" | "comment.title"; kind: string }[] = [];
49
+ if (parentAuthor && parentAuthor !== comment.author_id) {
50
+ targets.push({ uid: parentAuthor, title: "reply.title", kind: "community_reply" });
51
+ }
52
+ if (!parentAuthor && post.author_id !== comment.author_id) {
53
+ targets.push({ uid: post.author_id, title: "comment.title", kind: "community_comment" });
54
+ }
55
+ if (targets.length === 0) return new Response("skip: self/none");
56
56
 
57
57
  const { data: actor } = await supabase
58
58
  .from("profiles")
59
59
  .select("username")
60
60
  .eq("id", comment.author_id)
61
61
  .single();
62
- const name = actor?.username?.trim() || copy.fallbackName;
63
- // Recipient-language excerpt when the translation module is on: translate
64
- // now (a few seconds) rather than push the source language; on failure the
65
- // original goes out and the sweep fills the rows later. translate-one fires
66
- // on the same insert, so when it holds the claim wait up to 20 s (the OpenAI
67
- // request timeout) for its rows.
68
- let excerptSource = comment.content;
69
- const targetLocale = resolveTargetLocale(recipient?.locale);
70
- if (targetLocale) {
71
- const rows = await ensureTranslations(supabase, "comment", comment.id, { waitMs: 20_000 });
72
- const match = rows?.find(
73
- (r) => r.locale === targetLocale && languageOf(r.locale) !== r.source_locale,
74
- );
75
- if (match) excerptSource = match.content;
76
- }
77
- // Title states the event; body is the commenter's name then the comment in
78
- // quotes, e.g. Marie: "So happy for you!". An image-only comment has no text:
79
- // the localized "Photo" label stands in, unquoted.
80
- const body = comment.content.trim()
81
- ? `${name}: "${excerptOrPhoto(excerptSource, "")}"`
82
- : `${name}: ${copy.text("photo")}`;
83
62
 
84
- await sendExpoPush({
85
- to: pref.expo_push_token,
86
- title: copy.text("comment.title"),
87
- body,
88
- data: { route: "/community", kind: "community_comment" },
89
- badge: await unreadBadge(supabase, post.author_id),
90
- });
63
+ const postId = comment.post_id;
64
+ for (const target of targets) await pushTo(target, actor?.username ?? null);
91
65
  return new Response("ok");
66
+
67
+ async function pushTo(
68
+ target: { uid: string; title: "reply.title" | "comment.title"; kind: string },
69
+ actorName: string | null,
70
+ ) {
71
+ const { data: pref } = await supabase
72
+ .from("push_tokens")
73
+ .select("expo_push_token, notify_comments")
74
+ .eq("user_id", target.uid)
75
+ .single();
76
+ if (!pref?.expo_push_token || !pref.notify_comments) return;
77
+
78
+ const { data: blocked } = await supabase
79
+ .from("blocks")
80
+ .select("blocker_id")
81
+ .eq("blocker_id", target.uid)
82
+ .eq("blocked_id", comment!.author_id)
83
+ .maybeSingle();
84
+ if (blocked) return;
85
+
86
+ const { data: recipient } = await supabase
87
+ .from("profiles")
88
+ .select("locale")
89
+ .eq("id", target.uid)
90
+ .single();
91
+ const copy = pushCopy(recipient?.locale);
92
+ const name = actorName?.trim() || copy.fallbackName;
93
+ // Recipient-language excerpt when the translation module is on: translate
94
+ // now (a few seconds) rather than push the source language; on failure the
95
+ // original goes out and the sweep fills the rows later. translate-one fires
96
+ // on the same insert, so when it holds the claim wait up to 20 s (the OpenAI
97
+ // request timeout) for its rows.
98
+ let excerptSource = comment!.content;
99
+ const targetLocale = resolveTargetLocale(recipient?.locale);
100
+ if (targetLocale) {
101
+ const rows = await ensureTranslations(supabase, "comment", comment!.id, { waitMs: 20_000 });
102
+ const match = rows?.find(
103
+ (r) => r.locale === targetLocale && languageOf(r.locale) !== r.source_locale,
104
+ );
105
+ if (match) excerptSource = match.content;
106
+ }
107
+ // Title states the event; body is the commenter's name then the comment in
108
+ // quotes, e.g. Marie: "So happy for you!". An image-only comment has no text:
109
+ // the localized "Photo" label stands in, unquoted.
110
+ const body = comment!.content.trim()
111
+ ? `${name}: "${excerptOrPhoto(excerptSource, "")}"`
112
+ : `${name}: ${copy.text("photo")}`;
113
+
114
+ await sendExpoPush({
115
+ to: pref.expo_push_token,
116
+ title: copy.text(target.title),
117
+ body,
118
+ data: { route: "/community", kind: target.kind, postId },
119
+ badge: await unreadBadge(supabase, target.uid),
120
+ });
121
+ }
92
122
  });
@@ -80,7 +80,7 @@ async function flushPost(postId: string) {
80
80
  await sendExpoPush({
81
81
  to: pref.expo_push_token,
82
82
  title,
83
- data: { route: "/community", kind: "community_like" },
83
+ data: { route: "/community", kind: "community_like", postId },
84
84
  badge: await unreadBadge(supabase, post.author_id),
85
85
  });
86
86
  }
@@ -79,7 +79,7 @@ async function flushPost(postId: string) {
79
79
  await sendExpoPush({
80
80
  to: pref.expo_push_token,
81
81
  title,
82
- data: { route: "/community", kind: "community_reaction" },
82
+ data: { route: "/community", kind: "community_reaction", postId },
83
83
  badge: await unreadBadge(supabase, post.author_id),
84
84
  });
85
85
  }
@@ -0,0 +1,76 @@
1
+ -- Threaded replies and comment likes (after Eve's Rhythm's community v2).
2
+ --
3
+ -- Purely additive, safe for installed app versions: older clients never send
4
+ -- parent_id (null = a top-level comment) and never read comment_likes. A reply
5
+ -- is a comment whose parent_id points at the comment it answers; the app shows
6
+ -- replies one level deep, under their root comment.
7
+
8
+ -- ============ REPLIES ============
9
+ alter table public.comments
10
+ add column if not exists parent_id uuid references public.comments(id) on delete set null;
11
+ create index if not exists comments_parent_idx
12
+ on public.comments (parent_id) where parent_id is not null;
13
+
14
+ -- Column-scoped INSERT grant (002_rls.sql): add parent_id to what a client may
15
+ -- set. GRANT is additive, the other columns stay granted.
16
+ grant insert (parent_id) on table public.comments to authenticated;
17
+
18
+ -- A reply must answer a comment of the same post that the author can see.
19
+ -- SECURITY INVOKER on purpose: RLS hides hidden comments and blocked authors,
20
+ -- so one cannot reply to what one cannot read.
21
+ create or replace function public.comments_parent_same_post()
22
+ returns trigger language plpgsql set search_path = public as $$
23
+ begin
24
+ if not exists (
25
+ select 1 from comments c where c.id = new.parent_id and c.post_id = new.post_id
26
+ ) then
27
+ raise exception 'parent comment not found on this post' using errcode = '23503';
28
+ end if;
29
+ return new;
30
+ end; $$;
31
+
32
+ drop trigger if exists comments_parent_same_post on public.comments;
33
+ create trigger comments_parent_same_post
34
+ before insert on public.comments
35
+ for each row
36
+ when (new.parent_id is not null)
37
+ execute function public.comments_parent_same_post();
38
+
39
+ -- ============ COMMENT LIKES ============
40
+ -- One row per (comment, user), readable wherever the comment is readable,
41
+ -- written only as oneself. Likes on comments notify nobody.
42
+ --
43
+ -- user_id references auth.users, NOT public.profiles, on purpose: a
44
+ -- (comment_id, user_id) key with FKs to both comments and profiles is a
45
+ -- many-to-many junction to PostgREST, which would make every existing
46
+ -- `comments?select=profiles(...)` embed ambiguous (PGRST201) and break the
47
+ -- threads of installed app versions. Same ids either way: a profile's id is
48
+ -- its auth user's id.
49
+ create table if not exists public.comment_likes (
50
+ comment_id uuid not null references public.comments(id) on delete cascade,
51
+ user_id uuid not null references auth.users(id) on delete cascade,
52
+ created_at timestamptz not null default now(),
53
+ primary key (comment_id, user_id)
54
+ );
55
+ create index if not exists comment_likes_user_idx on public.comment_likes (user_id);
56
+
57
+ alter table public.comment_likes enable row level security;
58
+
59
+ drop policy if exists "comment likes readable where comment readable" on public.comment_likes;
60
+ create policy "comment likes readable where comment readable"
61
+ on public.comment_likes for select to authenticated
62
+ using (exists (select 1 from public.comments c where c.id = comment_likes.comment_id));
63
+
64
+ drop policy if exists "like comment as self" on public.comment_likes;
65
+ create policy "like comment as self"
66
+ on public.comment_likes for insert to authenticated
67
+ with check (user_id = auth.uid() and not public.current_user_banned());
68
+
69
+ drop policy if exists "unlike comment as self" on public.comment_likes;
70
+ create policy "unlike comment as self"
71
+ on public.comment_likes for delete to authenticated
72
+ using (user_id = auth.uid());
73
+
74
+ revoke all on table public.comment_likes from anon, authenticated;
75
+ grant select, delete on table public.comment_likes to authenticated;
76
+ grant insert (comment_id, user_id) on table public.comment_likes to authenticated;
@@ -0,0 +1,91 @@
1
+ -- Reply notifications and per-item read state.
2
+ --
3
+ -- Additive: installed app versions keep reading the same RPC and the
4
+ -- `notification_seen` watermark; a new `reply` kind shows on them through their
5
+ -- custom-row fallback (or not at all), and `notification_reads` is only
6
+ -- written by apps that mark items read one by one.
7
+
8
+ -- ============ REPLIES ============
9
+ -- Replaces inbox_on_comment (001_inbox.sql), same triggers (pending -> visible,
10
+ -- and direct visible inserts). A reply notifies only the author of the comment
11
+ -- it answers ('reply'); the post author gets 'comment' for top-level comments
12
+ -- (and for a reply whose parent is gone). Self-events and blocked actors never
13
+ -- notify. Needs core/010_comment_threads.sql (comments.parent_id).
14
+ create or replace function public.inbox_on_comment()
15
+ returns trigger language plpgsql security definer set search_path = public as $$
16
+ declare
17
+ post_author uuid;
18
+ parent_author uuid;
19
+ begin
20
+ select author_id into post_author from posts where id = new.post_id;
21
+ if new.parent_id is not null then
22
+ select author_id into parent_author from comments where id = new.parent_id;
23
+ end if;
24
+
25
+ if parent_author is not null and parent_author <> new.author_id
26
+ and not exists (
27
+ select 1 from blocks where blocker_id = parent_author and blocked_id = new.author_id
28
+ ) then
29
+ begin
30
+ insert into notifications (user_id, kind, actor_id, post_id)
31
+ values (parent_author, 'reply', new.author_id, new.post_id);
32
+ exception when others then null; -- the inbox must never break a comment
33
+ end;
34
+ end if;
35
+
36
+ if post_author is not null and post_author <> new.author_id
37
+ and parent_author is null
38
+ and not exists (
39
+ select 1 from blocks where blocker_id = post_author and blocked_id = new.author_id
40
+ ) then
41
+ begin
42
+ insert into notifications (user_id, kind, actor_id, post_id)
43
+ values (post_author, 'comment', new.author_id, new.post_id);
44
+ exception when others then null;
45
+ end;
46
+ end if;
47
+ return new;
48
+ end; $$;
49
+
50
+ -- ============ PER-ITEM READS ============
51
+ -- For apps that mark an item read when it is tapped (the SDK's `readMode:
52
+ -- "tap"`): an item is read when it is older than the `notification_seen`
53
+ -- watermark ("mark all as read" moves it) or listed here. `item_id` is the id
54
+ -- `list_notifications` returns: a notification's id, or an official post's id.
55
+ create table if not exists public.notification_reads (
56
+ user_id uuid not null references public.profiles(id) on delete cascade,
57
+ item_id uuid not null,
58
+ read_at timestamptz not null default now(),
59
+ primary key (user_id, item_id)
60
+ );
61
+
62
+ alter table public.notification_reads enable row level security;
63
+
64
+ drop policy if exists "read own reads" on public.notification_reads;
65
+ create policy "read own reads" on public.notification_reads
66
+ for select to authenticated using (user_id = auth.uid());
67
+ drop policy if exists "insert own reads" on public.notification_reads;
68
+ create policy "insert own reads" on public.notification_reads
69
+ for insert to authenticated with check (user_id = auth.uid());
70
+ drop policy if exists "delete own reads" on public.notification_reads;
71
+ create policy "delete own reads" on public.notification_reads
72
+ for delete to authenticated using (user_id = auth.uid());
73
+
74
+ revoke all on table public.notification_reads from anon, authenticated;
75
+ grant select, insert, delete on table public.notification_reads to authenticated;
76
+
77
+ -- Same retention as the notifications themselves.
78
+ do $$
79
+ begin
80
+ perform cron.schedule(
81
+ 'notification-reads-purge', '20 3 * * *',
82
+ $cron$ delete from public.notification_reads where read_at < now() - interval '90 days'; $cron$
83
+ );
84
+ exception when others then
85
+ if sqlerrm like '%already exists%' then
86
+ raise notice 'cron job notification-reads-purge already scheduled, skipping';
87
+ else
88
+ raise;
89
+ end if;
90
+ end;
91
+ $$;