@rocapine/community 0.14.0 → 0.16.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/README.md +4 -4
- package/lib/commands/upgrade.js +13 -5
- package/lib/index.js +2 -2
- package/lib/install-shared.d.ts +1 -1
- package/lib/install-shared.js +6 -1
- package/package.json +1 -1
- package/templates/functions/_shared/config.ts +2 -2
- package/templates/functions/broadcast-post/index.ts +27 -14
- package/templates/migrations/attachments/001_attachments.sql +28 -0
- package/templates/migrations/badges/001_badges.sql +25 -0
- package/templates/migrations/core/011_admins.sql +35 -0
- package/templates/migrations/core/012_pin_posts.sql +19 -0
- package/templates/migrations/core/013_post_broadcasts.sql +27 -0
- package/templates/migrations/core/014_post_drafts.sql +116 -0
- package/templates/migrations/core/015_scheduled_posts.sql +273 -0
- package/templates/migrations/images/002_draft_images.sql +34 -0
- package/templates/migrations/inbox/003_pushed_admin_posts.sql +40 -0
- package/templates/migrations/push/005_broadcast_trigger.sql +18 -0
- package/templates/migrations/streaks/002_to_badges.sql +87 -0
package/README.md
CHANGED
|
@@ -13,7 +13,7 @@ version. The binary is named `community`.
|
|
|
13
13
|
## `init`
|
|
14
14
|
|
|
15
15
|
```bash
|
|
16
|
-
npx @rocapine/community init [--modules core,push,polls,reaction,inbox,translation,images,streaks] [--project-url <url>] [--anon-key <key>] [--dir supabase]
|
|
16
|
+
npx @rocapine/community init [--modules core,push,polls,reaction,inbox,translation,images,attachments,badges,streaks] [--project-url <url>] [--anon-key <key>] [--dir supabase]
|
|
17
17
|
```
|
|
18
18
|
|
|
19
19
|
Copies the migrations and Edge Functions for the requested modules into
|
|
@@ -21,13 +21,13 @@ Copies the migrations and Edge Functions for the requested modules into
|
|
|
21
21
|
relative to the current directory), and writes a `community-sdk.json`
|
|
22
22
|
manifest at the repo root recording what was installed.
|
|
23
23
|
|
|
24
|
-
- `--modules` — comma-separated (`core,push,polls,reaction,inbox,translation,images,streaks`). `core`
|
|
24
|
+
- `--modules` — comma-separated (`core,push,polls,reaction,inbox,translation,images,attachments,badges,streaks`). `core`
|
|
25
25
|
is always implied even if omitted. Omit the flag entirely to install every
|
|
26
26
|
module. Regardless of the order you type them, modules are installed
|
|
27
|
-
`core → push → polls → reaction → inbox → translation → images → streaks` — this order is load-bearing:
|
|
27
|
+
`core → push → polls → reaction → inbox → translation → images → attachments → badges → streaks` — this order is load-bearing:
|
|
28
28
|
the inbox module's reaction trigger is guarded at install time and must
|
|
29
29
|
find the reaction module's table already present, so reaction has to land
|
|
30
|
-
first. Requesting `inbox` without `reaction`, or `translation` without `polls`, prints a (non-fatal) warning (reactions missing from the inbox; poll labels left untranslated).
|
|
30
|
+
first. `streaks` (deprecated: it moves an existing streak install onto badges) always brings `badges`. Requesting `inbox` without `reaction`, or `translation` without `polls`, prints a (non-fatal) warning (reactions missing from the inbox; poll labels left untranslated).
|
|
31
31
|
- `--project-url` / `--anon-key` — needed only if a migration in the
|
|
32
32
|
selected modules carries a placeholder (see "Placeholder guard" below).
|
|
33
33
|
If omitted, the CLI tries to read the project URL from
|
package/lib/commands/upgrade.js
CHANGED
|
@@ -58,9 +58,14 @@ async function runUpgrade(options = {}) {
|
|
|
58
58
|
// rules `init --modules` uses; left empty/undefined, behaviour here must stay
|
|
59
59
|
// byte-identical to the pre-`addModules` path (no resolveModules call, no
|
|
60
60
|
// spurious warnings for e.g. an existing inbox-without-reaction install).
|
|
61
|
+
// One implication still applies: streaks/002 moves the streak onto badges, so an
|
|
62
|
+
// install that has streaks gets badges too.
|
|
63
|
+
const installed = manifest.modules.includes("streaks")
|
|
64
|
+
? [...manifest.modules, "badges"]
|
|
65
|
+
: manifest.modules;
|
|
61
66
|
const canonicalModules = options.addModules && options.addModules.length > 0
|
|
62
|
-
? (0, install_shared_1.resolveModules)([...
|
|
63
|
-
: install_shared_1.MODULE_ORDER.filter((m) =>
|
|
67
|
+
? (0, install_shared_1.resolveModules)([...installed, ...options.addModules], onWarn)
|
|
68
|
+
: install_shared_1.MODULE_ORDER.filter((m) => installed.includes(m));
|
|
64
69
|
const addedModules = canonicalModules.filter((m) => !manifest.modules.includes(m));
|
|
65
70
|
const installedTemplateIds = new Set(manifest.installedTemplates ?? reconstructInstalledTemplateIds(manifest.installedFiles));
|
|
66
71
|
const pending = [];
|
|
@@ -189,9 +194,12 @@ async function runUpgrade(options = {}) {
|
|
|
189
194
|
const updatedManifest = {
|
|
190
195
|
schemaVersion: manifest_1.CURRENT_SCHEMA_VERSION,
|
|
191
196
|
sdkVersion: (0, install_shared_1.readOwnPackageVersion)(),
|
|
192
|
-
// Only --add-modules
|
|
193
|
-
//
|
|
194
|
-
|
|
197
|
+
// Only --add-modules (or a module brought along, like badges with streaks)
|
|
198
|
+
// rewrites the module list; a plain upgrade keeps the manifest's own (order
|
|
199
|
+
// and any entry this CLI doesn't know).
|
|
200
|
+
modules: (options.addModules && options.addModules.length > 0) || addedModules.length > 0
|
|
201
|
+
? canonicalModules
|
|
202
|
+
: manifest.modules,
|
|
195
203
|
installedFiles,
|
|
196
204
|
installedTemplates: [...newInstalledTemplateIds].sort(),
|
|
197
205
|
};
|
package/lib/index.js
CHANGED
|
@@ -60,7 +60,7 @@ program
|
|
|
60
60
|
program
|
|
61
61
|
.command("init")
|
|
62
62
|
.description("Copy the community backend into a Supabase project: migrations, Edge Functions, and a community-sdk.json manifest")
|
|
63
|
-
.option("--modules <modules>", "comma-separated module list (core,push,polls,reaction,inbox,translation,images,streaks) — core is always implied; defaults to all modules")
|
|
63
|
+
.option("--modules <modules>", "comma-separated module list (core,push,polls,reaction,inbox,translation,images,attachments,badges,streaks) — core is always implied; defaults to all modules")
|
|
64
64
|
.option("--project-url <url>", "Supabase project URL, e.g. https://<ref>.supabase.co — optional, only fills in the printed settings seed statement")
|
|
65
65
|
.option("--anon-key <key>", "Supabase anon key — optional, only fills in the printed settings seed statement")
|
|
66
66
|
.option("--dir <dir>", "target Supabase directory, relative to the current directory", "supabase")
|
|
@@ -103,7 +103,7 @@ program
|
|
|
103
103
|
.command("adopt")
|
|
104
104
|
.description("Register an already-live community backend (e.g. an app that hand-rolled its own before this SDK existed) with community-sdk.json, without copying any files")
|
|
105
105
|
.requiredOption("--schema-version <n>", "the community-sdk schema version this app's live backend corresponds to")
|
|
106
|
-
.requiredOption("--modules <modules>", "comma-separated module list (core,push,polls,reaction,inbox,translation,images,streaks) — core is always implied")
|
|
106
|
+
.requiredOption("--modules <modules>", "comma-separated module list (core,push,polls,reaction,inbox,translation,images,attachments,badges,streaks) — core is always implied")
|
|
107
107
|
.option("--dir <dir>", "Supabase directory this app would use, relative to the current directory", "supabase")
|
|
108
108
|
.action(async (opts) => {
|
|
109
109
|
try {
|
package/lib/install-shared.d.ts
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
* single source of truth for module names, order, and the function sets
|
|
11
11
|
* each module pulls in.
|
|
12
12
|
*/
|
|
13
|
-
export declare const MODULE_ORDER: readonly ["core", "push", "polls", "reaction", "inbox", "translation", "images", "streaks"];
|
|
13
|
+
export declare const MODULE_ORDER: readonly ["core", "push", "polls", "reaction", "inbox", "translation", "images", "attachments", "badges", "streaks"];
|
|
14
14
|
export type Module = (typeof MODULE_ORDER)[number];
|
|
15
15
|
export declare function functionsForModules(modules: readonly Module[]): string[];
|
|
16
16
|
/**
|
package/lib/install-shared.js
CHANGED
|
@@ -73,6 +73,9 @@ exports.MODULE_ORDER = [
|
|
|
73
73
|
"inbox",
|
|
74
74
|
"translation",
|
|
75
75
|
"images",
|
|
76
|
+
"attachments",
|
|
77
|
+
"badges",
|
|
78
|
+
// Deprecated: kept to move existing streaks onto badges (streaks/002). Implies badges.
|
|
76
79
|
"streaks",
|
|
77
80
|
];
|
|
78
81
|
const ALWAYS_FUNCTIONS = [
|
|
@@ -111,8 +114,10 @@ function resolveModules(requested, onWarn) {
|
|
|
111
114
|
throw new Error(`community-sdk: unknown module "${m}" (expected one of ${exports.MODULE_ORDER.join(", ")})`);
|
|
112
115
|
}
|
|
113
116
|
}
|
|
114
|
-
// core is always required/implied.
|
|
117
|
+
// core is always required/implied; streaks/002 moves the streak onto badges.
|
|
115
118
|
requestedSet.add("core");
|
|
119
|
+
if (requestedSet.has("streaks"))
|
|
120
|
+
requestedSet.add("badges");
|
|
116
121
|
const canonicalModules = exports.MODULE_ORDER.filter((m) => requestedSet.has(m));
|
|
117
122
|
if (canonicalModules.includes("inbox") && !canonicalModules.includes("reaction")) {
|
|
118
123
|
onWarn("community-sdk: module 'inbox' selected without 'reaction' — reaction notifications won't appear in the inbox until the reaction module is also installed.");
|
package/package.json
CHANGED
|
@@ -2,6 +2,6 @@
|
|
|
2
2
|
// deploys unchanged to every app. Push copy (actor fallback name, like /
|
|
3
3
|
// comment / reaction titles) lives in _shared/copy.ts (COMMUNITY_PUSH_COPY).
|
|
4
4
|
|
|
5
|
-
// Push title fallback for
|
|
6
|
-
// username (normally the
|
|
5
|
+
// Push title fallback for admin broadcast posts whose author has no
|
|
6
|
+
// username (normally the admin account's display name).
|
|
7
7
|
export const BROADCAST_FALLBACK_TITLE = Deno.env.get("COMMUNITY_APP_NAME") ?? "Community";
|
|
@@ -1,8 +1,11 @@
|
|
|
1
|
-
// Broadcast push for an
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
//
|
|
1
|
+
// Broadcast push for an admin post. Two callers: the push module's trigger once a
|
|
2
|
+
// post an admin asked to send to everyone is visible (push/005_broadcast_trigger.sql,
|
|
3
|
+
// with the public anon key), or a dashboard with the service-role key. The anon key
|
|
4
|
+
// passes the platform's verify_jwt, so the body is untrusted: only `post_id` is
|
|
5
|
+
// read, and an anon call sends nothing unless the post's admin author asked for it
|
|
6
|
+
// (core/013_post_broadcasts.sql). `broadcast_at` is claimed before sending, so a
|
|
7
|
+
// post goes out once and the inbox lists exactly the posts that were sent.
|
|
8
|
+
// Sends an Expo push to every registered token (batches of 100) but the author's.
|
|
6
9
|
|
|
7
10
|
import { adminClient, fetchAllRows, isServiceCaller } from "../_shared/client.ts";
|
|
8
11
|
import { excerptOrPhoto, pushCopy } from "../_shared/copy.ts";
|
|
@@ -13,25 +16,32 @@ import { ensureTranslations, resolveTargetLocale, TARGET_LOCALES } from "../_sha
|
|
|
13
16
|
const supabase = adminClient();
|
|
14
17
|
|
|
15
18
|
Deno.serve(async (req) => {
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
const { post_id } = (await req.json()) as { post_id?: string };
|
|
19
|
+
const service = isServiceCaller(req);
|
|
20
|
+
const { post_id } = (await req.json().catch(() => ({}))) as { post_id?: string };
|
|
21
21
|
if (!post_id) return new Response("missing post_id", { status: 400 });
|
|
22
22
|
|
|
23
23
|
const { data: post } = await supabase
|
|
24
24
|
.from("posts")
|
|
25
|
-
.select("id, author_id, content, status")
|
|
25
|
+
.select("id, author_id, content, status, broadcast_requested")
|
|
26
26
|
.eq("id", post_id)
|
|
27
27
|
.single();
|
|
28
28
|
if (!post || post.status !== "visible") return new Response("skip: post not visible");
|
|
29
29
|
|
|
30
30
|
const { data: author } = await supabase
|
|
31
31
|
.from("profiles")
|
|
32
|
-
.select("username")
|
|
32
|
+
.select("username, is_admin")
|
|
33
33
|
.eq("id", post.author_id)
|
|
34
34
|
.single();
|
|
35
|
+
if (!service && !(post.broadcast_requested && author?.is_admin)) {
|
|
36
|
+
return new Response("forbidden", { status: 403 });
|
|
37
|
+
}
|
|
38
|
+
const { data: claimed } = await supabase
|
|
39
|
+
.from("posts")
|
|
40
|
+
.update({ broadcast_at: new Date().toISOString() })
|
|
41
|
+
.eq("id", post.id)
|
|
42
|
+
.is("broadcast_at", null)
|
|
43
|
+
.select("id");
|
|
44
|
+
if (!claimed?.length) return new Response("skip: already sent");
|
|
35
45
|
const title = author?.username?.trim() || BROADCAST_FALLBACK_TITLE;
|
|
36
46
|
|
|
37
47
|
// waitMs: when translate-one holds the claim (it fires on the same insert),
|
|
@@ -61,7 +71,10 @@ Deno.serve(async (req) => {
|
|
|
61
71
|
.order("user_id")
|
|
62
72
|
.range(from, to),
|
|
63
73
|
);
|
|
64
|
-
|
|
74
|
+
// The author's own devices: their center never lists their own post.
|
|
75
|
+
const seen = new Set<string>(
|
|
76
|
+
rows.filter((r) => r.user_id === post.author_id).map((r) => r.expo_push_token as string),
|
|
77
|
+
);
|
|
65
78
|
const messages = rows
|
|
66
79
|
.map((r) => {
|
|
67
80
|
const profile = Array.isArray(r.profiles) ? r.profiles[0] : r.profiles;
|
|
@@ -81,7 +94,7 @@ Deno.serve(async (req) => {
|
|
|
81
94
|
to,
|
|
82
95
|
title,
|
|
83
96
|
body: excerptFor(locale, profileLocale),
|
|
84
|
-
data: { route: "/community", kind: "
|
|
97
|
+
data: { route: "/community", kind: "community_admin_post", postId: post.id },
|
|
85
98
|
badge: 1,
|
|
86
99
|
}));
|
|
87
100
|
await sendExpoPushBatch(messages);
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
-- community-sdk attachments/001_attachments.sql (schema v1)
|
|
2
|
+
-- Attachments module: one reference to the app's own content per post (a verse, a
|
|
3
|
+
-- recipe, a session), `{ "type": "verse", "id": "43.3.16" }`. The post never stores a
|
|
4
|
+
-- URL, a title or an image: each reader's app draws the card from its own data, and
|
|
5
|
+
-- its button opens that content in the app. Which types exist, and who may attach,
|
|
6
|
+
-- is the app's configuration. Client-written: a shape and size check is the only
|
|
7
|
+
-- guard. Fully idempotent.
|
|
8
|
+
|
|
9
|
+
alter table public.posts add column if not exists attachment jsonb;
|
|
10
|
+
|
|
11
|
+
alter table public.posts drop constraint if exists posts_attachment_check;
|
|
12
|
+
alter table public.posts add constraint posts_attachment_check check (
|
|
13
|
+
attachment is null or (
|
|
14
|
+
jsonb_typeof(attachment) = 'object'
|
|
15
|
+
-- `?` first: a missing key would make jsonb_typeof null, which a check lets pass.
|
|
16
|
+
and attachment ? 'type'
|
|
17
|
+
and attachment ? 'id'
|
|
18
|
+
and jsonb_typeof(attachment -> 'type') = 'string'
|
|
19
|
+
and jsonb_typeof(attachment -> 'id') = 'string'
|
|
20
|
+
and octet_length(attachment::text) <= 512
|
|
21
|
+
)
|
|
22
|
+
);
|
|
23
|
+
|
|
24
|
+
-- The text stays required: pushes and inbox rows read an empty post as a photo.
|
|
25
|
+
|
|
26
|
+
-- Posts use column-scoped insert grants (core/002_rls.sql); extend them.
|
|
27
|
+
grant insert (attachment) on table public.posts to authenticated;
|
|
28
|
+
grant select (attachment) on table public.posts to anon, authenticated;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
-- community-sdk badges/001_badges.sql (schema v1)
|
|
2
|
+
-- Badges module: app-defined badges on each profile (a streak, a pregnancy month,
|
|
3
|
+
-- a rank…), shown next to the author on posts and comments and on the profile.
|
|
4
|
+
-- The app writes `badges` (JSON keyed by its badge ids) for its own member; the
|
|
5
|
+
-- member writes `hidden_badges`, the ids they chose to hide. Readers only ever see
|
|
6
|
+
-- the generated `visible_badges`, so a hidden badge never leaves the database.
|
|
7
|
+
-- Client-written by design (the app computes the values on the device): a size and
|
|
8
|
+
-- shape check is the only guard. Fully idempotent.
|
|
9
|
+
|
|
10
|
+
alter table public.profiles
|
|
11
|
+
add column if not exists badges jsonb not null default '{}'::jsonb,
|
|
12
|
+
add column if not exists hidden_badges text[] not null default '{}';
|
|
13
|
+
|
|
14
|
+
alter table public.profiles drop constraint if exists profiles_badges_check;
|
|
15
|
+
alter table public.profiles add constraint profiles_badges_check
|
|
16
|
+
check (jsonb_typeof(badges) = 'object' and octet_length(badges::text) <= 2048);
|
|
17
|
+
|
|
18
|
+
alter table public.profiles
|
|
19
|
+
add column if not exists visible_badges jsonb
|
|
20
|
+
generated always as (badges - hidden_badges) stored;
|
|
21
|
+
|
|
22
|
+
-- Owners write their own row (RLS "update own profile"); the raw values stay
|
|
23
|
+
-- unreadable, everyone reads the visible ones and the hidden ids (the toggles).
|
|
24
|
+
grant update (badges, hidden_badges) on table public.profiles to authenticated;
|
|
25
|
+
grant select (visible_badges, hidden_badges) on public.profiles to anon, authenticated;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
-- community-sdk core/011_admins.sql (schema v1)
|
|
2
|
+
-- "Official" accounts become admin accounts (`profiles.is_admin`), and the
|
|
3
|
+
-- posts insert policy no longer reserves the 'news' topic: which topics only
|
|
4
|
+
-- admins post in is the app's `adminOnly` config, applied by the SDK's UI.
|
|
5
|
+
--
|
|
6
|
+
-- Expand step, for app versions on SDK 0.14 or older:
|
|
7
|
+
-- - `is_official` stays, read-only and always equal to `is_admin`;
|
|
8
|
+
-- - list_notifications still names admin posts `official_post` (the only kind
|
|
9
|
+
-- those versions know); SDK 0.15 reads it as `admin_post`.
|
|
10
|
+
-- Contract step, once no such version is in use: drop `is_official`, and return
|
|
11
|
+
-- `admin_post` from list_notifications.
|
|
12
|
+
|
|
13
|
+
alter table public.profiles rename column is_official to is_admin;
|
|
14
|
+
alter table public.profiles
|
|
15
|
+
add column is_official boolean generated always as (is_admin) stored;
|
|
16
|
+
-- `is_admin` keeps the column grant `is_official` had (002_rls.sql).
|
|
17
|
+
grant select (is_official) on public.profiles to anon, authenticated;
|
|
18
|
+
|
|
19
|
+
create or replace function public.current_user_admin()
|
|
20
|
+
returns boolean
|
|
21
|
+
language sql stable security definer set search_path = public
|
|
22
|
+
as $$
|
|
23
|
+
select coalesce((select is_admin from profiles where id = auth.uid()), false);
|
|
24
|
+
$$;
|
|
25
|
+
|
|
26
|
+
drop policy "insert own posts if not banned" on public.posts;
|
|
27
|
+
create policy "insert own posts if not banned"
|
|
28
|
+
on public.posts for insert to authenticated
|
|
29
|
+
with check (
|
|
30
|
+
author_id = auth.uid()
|
|
31
|
+
and not public.current_user_banned()
|
|
32
|
+
and status = 'pending'
|
|
33
|
+
);
|
|
34
|
+
|
|
35
|
+
drop function public.current_user_official();
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
-- community-sdk core/012_pin_posts.sql (schema v1)
|
|
2
|
+
-- Admins pin and unpin posts from the app. `pinned_at` stays out of the client's
|
|
3
|
+
-- column grants; this function is the only client path to it. A pinned post leads
|
|
4
|
+
-- its feeds (newest pin first) until unpinned.
|
|
5
|
+
|
|
6
|
+
create or replace function public.set_post_pinned(p_post_id uuid, p_pinned boolean)
|
|
7
|
+
returns void
|
|
8
|
+
language plpgsql security definer set search_path = public
|
|
9
|
+
as $$
|
|
10
|
+
begin
|
|
11
|
+
if not public.current_user_admin() then
|
|
12
|
+
raise exception 'only admins pin posts' using errcode = '42501';
|
|
13
|
+
end if;
|
|
14
|
+
update posts set pinned_at = case when p_pinned then now() end where id = p_post_id;
|
|
15
|
+
end;
|
|
16
|
+
$$;
|
|
17
|
+
|
|
18
|
+
revoke execute on function public.set_post_pinned(uuid, boolean) from public, anon;
|
|
19
|
+
grant execute on function public.set_post_pinned(uuid, boolean) to authenticated;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
-- community-sdk core/013_post_broadcasts.sql (schema v1)
|
|
2
|
+
-- "Notify everyone" for admin posts. An admin asks for it on their own post
|
|
3
|
+
-- (request_post_broadcast); the push module's broadcast-post sends it once the post
|
|
4
|
+
-- is visible, even when moderation publishes it later, and stamps `broadcast_at`.
|
|
5
|
+
-- The inbox lists an admin post only once it is stamped, so the notification
|
|
6
|
+
-- center shows exactly the admin posts that were pushed.
|
|
7
|
+
-- Both columns stay out of the client's grants; this function is the only client path.
|
|
8
|
+
|
|
9
|
+
alter table public.posts
|
|
10
|
+
add column if not exists broadcast_requested boolean not null default false,
|
|
11
|
+
add column if not exists broadcast_at timestamptz;
|
|
12
|
+
|
|
13
|
+
create or replace function public.request_post_broadcast(p_post_id uuid)
|
|
14
|
+
returns void
|
|
15
|
+
language plpgsql security definer set search_path = public
|
|
16
|
+
as $$
|
|
17
|
+
begin
|
|
18
|
+
if not public.current_user_admin() then
|
|
19
|
+
raise exception 'only admins notify everyone' using errcode = '42501';
|
|
20
|
+
end if;
|
|
21
|
+
update posts set broadcast_requested = true
|
|
22
|
+
where id = p_post_id and author_id = auth.uid();
|
|
23
|
+
end;
|
|
24
|
+
$$;
|
|
25
|
+
|
|
26
|
+
revoke execute on function public.request_post_broadcast(uuid) from public, anon;
|
|
27
|
+
grant execute on function public.request_post_broadcast(uuid) to authenticated;
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
-- community-sdk core/014_post_drafts.sql (schema v1)
|
|
2
|
+
-- Shared post drafts for the community dashboard (service role only): the team
|
|
3
|
+
-- writes a post under a team account, edits it together (`version` guards
|
|
4
|
+
-- concurrent saves), then publishes it with publish_post_draft. Publishing skips
|
|
5
|
+
-- moderation (the team wrote it), applies pin and "notify everyone", copies the
|
|
6
|
+
-- poll, attachment or image, deletes the draft and logs `publish_post`.
|
|
7
|
+
-- Clients never see this table. Fully idempotent.
|
|
8
|
+
|
|
9
|
+
create table if not exists public.post_drafts (
|
|
10
|
+
id uuid primary key default gen_random_uuid(),
|
|
11
|
+
author_id uuid references public.profiles(id) on delete set null,
|
|
12
|
+
topic text,
|
|
13
|
+
content text not null default '' check (char_length(content) <= 2000),
|
|
14
|
+
image_path text,
|
|
15
|
+
image_width int,
|
|
16
|
+
image_height int,
|
|
17
|
+
poll_options text[],
|
|
18
|
+
attachment jsonb,
|
|
19
|
+
notify boolean not null default false,
|
|
20
|
+
pin boolean not null default false,
|
|
21
|
+
publish_at timestamptz,
|
|
22
|
+
version int not null default 1,
|
|
23
|
+
created_by text not null,
|
|
24
|
+
updated_by text not null,
|
|
25
|
+
created_at timestamptz not null default now(),
|
|
26
|
+
updated_at timestamptz not null default now()
|
|
27
|
+
);
|
|
28
|
+
alter table public.post_drafts enable row level security;
|
|
29
|
+
-- No policy: readable only by the service role.
|
|
30
|
+
revoke all on table public.post_drafts from public, anon, authenticated;
|
|
31
|
+
|
|
32
|
+
alter table public.moderation_actions drop constraint if exists moderation_actions_action_check;
|
|
33
|
+
alter table public.moderation_actions add constraint moderation_actions_action_check check (action in
|
|
34
|
+
('hide','restore','confirm_hide','reject_report','ban','unban',
|
|
35
|
+
'publish_post','create_team_account','update_team_account'));
|
|
36
|
+
|
|
37
|
+
-- Errors are raised with the code as the message (errcode P0001): draft_not_found,
|
|
38
|
+
-- draft_changed, not_a_team_account, author_banned, not_admin, invalid_content,
|
|
39
|
+
-- invalid_image, invalid_poll, invalid_attachment, one_extra_only. Columns of
|
|
40
|
+
-- optional modules (images, attachments) are only named when the draft uses
|
|
41
|
+
-- them, so a backend without those modules still publishes plain and poll drafts.
|
|
42
|
+
create or replace function public.publish_post_draft(p_draft_id uuid, p_version int, p_actor text)
|
|
43
|
+
returns uuid
|
|
44
|
+
language plpgsql security definer set search_path = public
|
|
45
|
+
as $$
|
|
46
|
+
declare
|
|
47
|
+
d post_drafts;
|
|
48
|
+
author profiles;
|
|
49
|
+
new_id uuid;
|
|
50
|
+
n int;
|
|
51
|
+
i int;
|
|
52
|
+
begin
|
|
53
|
+
select * into d from post_drafts where id = p_draft_id for update;
|
|
54
|
+
if not found then raise exception 'draft_not_found'; end if;
|
|
55
|
+
if d.version is distinct from p_version then raise exception 'draft_changed'; end if;
|
|
56
|
+
|
|
57
|
+
select * into author from profiles where id = d.author_id;
|
|
58
|
+
if not found or not author.is_house then raise exception 'not_a_team_account'; end if;
|
|
59
|
+
if author.is_banned then raise exception 'author_banned'; end if;
|
|
60
|
+
if (d.pin or d.notify) and not author.is_admin then raise exception 'not_admin'; end if;
|
|
61
|
+
|
|
62
|
+
-- Like posts_content_check: text is optional when there is an image.
|
|
63
|
+
if char_length(d.content) > 2000 or (char_length(d.content) = 0 and d.image_path is null) then
|
|
64
|
+
raise exception 'invalid_content';
|
|
65
|
+
end if;
|
|
66
|
+
-- Mirrors posts_image_check and posts_image_path_format (images/001). The image lives
|
|
67
|
+
-- in the author's storage folder; the dashboard moves it when the author changes.
|
|
68
|
+
if d.image_path is not null and (coalesce(d.image_width, 0) <= 0 or coalesce(d.image_height, 0) <= 0
|
|
69
|
+
or d.image_path !~ '^[0-9a-f-]{36}/[A-Za-z0-9_-]+\.jpg$'
|
|
70
|
+
or split_part(d.image_path, '/', 1) <> d.author_id::text) then
|
|
71
|
+
raise exception 'invalid_image';
|
|
72
|
+
end if;
|
|
73
|
+
n := coalesce(array_length(d.poll_options, 1), 0);
|
|
74
|
+
if d.poll_options is not null and (n not between 2 and 4
|
|
75
|
+
or exists (select 1 from unnest(d.poll_options) l where coalesce(char_length(l), 0) not between 1 and 60)) then
|
|
76
|
+
raise exception 'invalid_poll';
|
|
77
|
+
end if;
|
|
78
|
+
-- Mirrors posts_attachment_check (attachments/001); coalesce because a null check result would pass.
|
|
79
|
+
if d.attachment is not null and not coalesce(jsonb_typeof(d.attachment) = 'object'
|
|
80
|
+
and d.attachment ? 'type' and d.attachment ? 'id'
|
|
81
|
+
and jsonb_typeof(d.attachment -> 'type') = 'string' and jsonb_typeof(d.attachment -> 'id') = 'string'
|
|
82
|
+
and octet_length(d.attachment::text) <= 512, false) then
|
|
83
|
+
raise exception 'invalid_attachment';
|
|
84
|
+
end if;
|
|
85
|
+
if (d.image_path is not null)::int + (d.poll_options is not null)::int + (d.attachment is not null)::int > 1 then
|
|
86
|
+
raise exception 'one_extra_only';
|
|
87
|
+
end if;
|
|
88
|
+
|
|
89
|
+
-- The image goes in the insert itself: an image-only post needs it to pass posts_content_check.
|
|
90
|
+
if d.image_path is not null then
|
|
91
|
+
insert into posts (author_id, topic, content, status, moderated_at, broadcast_requested, pinned_at,
|
|
92
|
+
image_path, image_width, image_height)
|
|
93
|
+
values (d.author_id, d.topic, d.content, 'visible', now(), d.notify, case when d.pin then now() end,
|
|
94
|
+
d.image_path, d.image_width, d.image_height)
|
|
95
|
+
returning id into new_id;
|
|
96
|
+
else
|
|
97
|
+
insert into posts (author_id, topic, content, status, moderated_at, broadcast_requested, pinned_at)
|
|
98
|
+
values (d.author_id, d.topic, d.content, 'visible', now(), d.notify, case when d.pin then now() end)
|
|
99
|
+
returning id into new_id;
|
|
100
|
+
end if;
|
|
101
|
+
if d.attachment is not null then
|
|
102
|
+
update posts set attachment = d.attachment where id = new_id;
|
|
103
|
+
end if;
|
|
104
|
+
for i in 1..n loop
|
|
105
|
+
insert into poll_options (post_id, idx, label) values (new_id, i - 1, d.poll_options[i]);
|
|
106
|
+
end loop;
|
|
107
|
+
|
|
108
|
+
delete from post_drafts where id = d.id;
|
|
109
|
+
insert into moderation_actions (actor_email, action, target_post_id, target_user_id)
|
|
110
|
+
values (p_actor, 'publish_post', new_id, d.author_id);
|
|
111
|
+
return new_id;
|
|
112
|
+
end;
|
|
113
|
+
$$;
|
|
114
|
+
|
|
115
|
+
revoke execute on function public.publish_post_draft(uuid, int, text) from public, anon, authenticated;
|
|
116
|
+
grant execute on function public.publish_post_draft(uuid, int, text) to service_role;
|
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
-- community-sdk core/015_scheduled_posts.sql (schema v1)
|
|
2
|
+
-- Scheduled posts for the community dashboard (service role only): a draft gets a
|
|
3
|
+
-- publish_at instant (publish_tz is the zone the team picked, for display only) and
|
|
4
|
+
-- schedule_post_draft sets or clears it. A draft can carry a planned time without being armed:
|
|
5
|
+
-- armed means scheduled_by is not null, and only armed drafts are published by the cron.
|
|
6
|
+
-- Planning a time checks the time and the event window; arming validates the whole post.
|
|
7
|
+
-- check_post_draft holds the validation that publish_post_draft and the scheduler share.
|
|
8
|
+
-- Requires core/014. Fully idempotent.
|
|
9
|
+
-- topic_from / topic_until (nullable dates, until exclusive) hold the date window of an event
|
|
10
|
+
-- topic, which lives in the dashboard's config; the dashboard writes them with the topic.
|
|
11
|
+
|
|
12
|
+
alter table public.post_drafts add column if not exists scheduled_by text;
|
|
13
|
+
alter table public.post_drafts add column if not exists publish_tz text;
|
|
14
|
+
alter table public.post_drafts add column if not exists publish_error text;
|
|
15
|
+
alter table public.post_drafts add column if not exists failed_at timestamptz;
|
|
16
|
+
alter table public.post_drafts add column if not exists topic_from date;
|
|
17
|
+
alter table public.post_drafts add column if not exists topic_until date;
|
|
18
|
+
|
|
19
|
+
-- Only armed drafts are due; the predicate changed in the planned-time revision, so recreate it.
|
|
20
|
+
drop index if exists public.post_drafts_due_idx;
|
|
21
|
+
create index post_drafts_due_idx on public.post_drafts (publish_at)
|
|
22
|
+
where publish_at is not null and publish_error is null and scheduled_by is not null;
|
|
23
|
+
|
|
24
|
+
alter table public.moderation_actions drop constraint if exists moderation_actions_action_check;
|
|
25
|
+
alter table public.moderation_actions add constraint moderation_actions_action_check check (action in
|
|
26
|
+
('hide','restore','confirm_hide','reject_report','ban','unban',
|
|
27
|
+
'publish_post','create_team_account','update_team_account','schedule_post'));
|
|
28
|
+
|
|
29
|
+
-- The event-window part of the check, alone (it needs d.publish_tz): the local date the post goes
|
|
30
|
+
-- out in the draft's zone must fall in [topic_from, topic_until). A draft without a zone is guarded
|
|
31
|
+
-- by the dashboard only. Raises topic_closed.
|
|
32
|
+
create or replace function public.check_post_draft_window(d post_drafts, p_at timestamptz default null)
|
|
33
|
+
returns void
|
|
34
|
+
language plpgsql security definer set search_path = public
|
|
35
|
+
as $$
|
|
36
|
+
begin
|
|
37
|
+
if d.publish_tz is not null and (d.topic_from is not null or d.topic_until is not null)
|
|
38
|
+
and ((coalesce(p_at, now()) at time zone d.publish_tz)::date < d.topic_from
|
|
39
|
+
or (coalesce(p_at, now()) at time zone d.publish_tz)::date >= d.topic_until) then
|
|
40
|
+
raise exception 'topic_closed';
|
|
41
|
+
end if;
|
|
42
|
+
end;
|
|
43
|
+
$$;
|
|
44
|
+
|
|
45
|
+
revoke execute on function public.check_post_draft_window(post_drafts, timestamptz) from public, anon, authenticated;
|
|
46
|
+
|
|
47
|
+
-- Raises the publish error codes (errcode P0001, code as message): not_a_team_account,
|
|
48
|
+
-- author_banned, not_admin, invalid_content, invalid_image, invalid_poll,
|
|
49
|
+
-- invalid_attachment, one_extra_only, invalid_topic, topic_closed. Callers are security definer; nobody else may run it.
|
|
50
|
+
-- Takes the instant the post goes out (default now) for the event window: publishing checks it at
|
|
51
|
+
-- that moment, scheduling checks the chosen time. Replaces the one-argument version of earlier runs.
|
|
52
|
+
drop function if exists public.check_post_draft(post_drafts);
|
|
53
|
+
create or replace function public.check_post_draft(d post_drafts, p_at timestamptz default null)
|
|
54
|
+
returns void
|
|
55
|
+
language plpgsql security definer set search_path = public
|
|
56
|
+
as $$
|
|
57
|
+
declare
|
|
58
|
+
author profiles;
|
|
59
|
+
n int;
|
|
60
|
+
begin
|
|
61
|
+
select * into author from profiles where id = d.author_id;
|
|
62
|
+
if not found or not author.is_house then raise exception 'not_a_team_account'; end if;
|
|
63
|
+
if author.is_banned then raise exception 'author_banned'; end if;
|
|
64
|
+
if (d.pin or d.notify) and not author.is_admin then raise exception 'not_admin'; end if;
|
|
65
|
+
|
|
66
|
+
-- Like posts_content_check: text is optional when there is an image.
|
|
67
|
+
if char_length(d.content) > 2000 or (char_length(d.content) = 0 and d.image_path is null) then
|
|
68
|
+
raise exception 'invalid_content';
|
|
69
|
+
end if;
|
|
70
|
+
-- Mirrors posts_image_check and posts_image_path_format (images/001). The image lives
|
|
71
|
+
-- in the author's storage folder; the dashboard moves it when the author changes.
|
|
72
|
+
if d.image_path is not null and (coalesce(d.image_width, 0) <= 0 or coalesce(d.image_height, 0) <= 0
|
|
73
|
+
or d.image_path !~ '^[0-9a-f-]{36}/[A-Za-z0-9_-]+\.jpg$'
|
|
74
|
+
or split_part(d.image_path, '/', 1) <> d.author_id::text) then
|
|
75
|
+
raise exception 'invalid_image';
|
|
76
|
+
end if;
|
|
77
|
+
n := coalesce(array_length(d.poll_options, 1), 0);
|
|
78
|
+
if d.poll_options is not null and (n not between 2 and 4
|
|
79
|
+
or exists (select 1 from unnest(d.poll_options) l where coalesce(char_length(l), 0) not between 1 and 60)) then
|
|
80
|
+
raise exception 'invalid_poll';
|
|
81
|
+
end if;
|
|
82
|
+
-- Mirrors posts_attachment_check (attachments/001); coalesce because a null check result would pass.
|
|
83
|
+
if d.attachment is not null and not coalesce(jsonb_typeof(d.attachment) = 'object'
|
|
84
|
+
and d.attachment ? 'type' and d.attachment ? 'id'
|
|
85
|
+
and jsonb_typeof(d.attachment -> 'type') = 'string' and jsonb_typeof(d.attachment -> 'id') = 'string'
|
|
86
|
+
and octet_length(d.attachment::text) <= 512, false) then
|
|
87
|
+
raise exception 'invalid_attachment';
|
|
88
|
+
end if;
|
|
89
|
+
if (d.image_path is not null)::int + (d.poll_options is not null)::int + (d.attachment is not null)::int > 1 then
|
|
90
|
+
raise exception 'one_extra_only';
|
|
91
|
+
end if;
|
|
92
|
+
-- Topic rules live in the dashboard; here a draft only needs one, so the cron never posts without it.
|
|
93
|
+
if d.topic is null then raise exception 'invalid_topic'; end if;
|
|
94
|
+
perform check_post_draft_window(d, p_at);
|
|
95
|
+
end;
|
|
96
|
+
$$;
|
|
97
|
+
|
|
98
|
+
revoke execute on function public.check_post_draft(post_drafts, timestamptz) from public, anon, authenticated;
|
|
99
|
+
|
|
100
|
+
-- Same checks and codes as 014 (the validation now lives in check_post_draft, which also raises
|
|
101
|
+
-- invalid_topic: a draft needs a topic to go out).
|
|
102
|
+
create or replace function public.publish_post_draft(p_draft_id uuid, p_version int, p_actor text)
|
|
103
|
+
returns uuid
|
|
104
|
+
language plpgsql security definer set search_path = public
|
|
105
|
+
as $$
|
|
106
|
+
declare
|
|
107
|
+
d post_drafts;
|
|
108
|
+
new_id uuid;
|
|
109
|
+
n int;
|
|
110
|
+
i int;
|
|
111
|
+
begin
|
|
112
|
+
select * into d from post_drafts where id = p_draft_id for update;
|
|
113
|
+
if not found then raise exception 'draft_not_found'; end if;
|
|
114
|
+
if d.version is distinct from p_version then raise exception 'draft_changed'; end if;
|
|
115
|
+
|
|
116
|
+
perform check_post_draft(d);
|
|
117
|
+
n := coalesce(array_length(d.poll_options, 1), 0);
|
|
118
|
+
|
|
119
|
+
-- The image goes in the insert itself: an image-only post needs it to pass posts_content_check.
|
|
120
|
+
if d.image_path is not null then
|
|
121
|
+
insert into posts (author_id, topic, content, status, moderated_at, broadcast_requested, pinned_at,
|
|
122
|
+
image_path, image_width, image_height)
|
|
123
|
+
values (d.author_id, d.topic, d.content, 'visible', now(), d.notify, case when d.pin then now() end,
|
|
124
|
+
d.image_path, d.image_width, d.image_height)
|
|
125
|
+
returning id into new_id;
|
|
126
|
+
else
|
|
127
|
+
insert into posts (author_id, topic, content, status, moderated_at, broadcast_requested, pinned_at)
|
|
128
|
+
values (d.author_id, d.topic, d.content, 'visible', now(), d.notify, case when d.pin then now() end)
|
|
129
|
+
returning id into new_id;
|
|
130
|
+
end if;
|
|
131
|
+
if d.attachment is not null then
|
|
132
|
+
update posts set attachment = d.attachment where id = new_id;
|
|
133
|
+
end if;
|
|
134
|
+
for i in 1..n loop
|
|
135
|
+
insert into poll_options (post_id, idx, label) values (new_id, i - 1, d.poll_options[i]);
|
|
136
|
+
end loop;
|
|
137
|
+
|
|
138
|
+
delete from post_drafts where id = d.id;
|
|
139
|
+
insert into moderation_actions (actor_email, action, target_post_id, target_user_id)
|
|
140
|
+
values (p_actor, 'publish_post', new_id, d.author_id);
|
|
141
|
+
return new_id;
|
|
142
|
+
end;
|
|
143
|
+
$$;
|
|
144
|
+
|
|
145
|
+
revoke execute on function public.publish_post_draft(uuid, int, text) from public, anon, authenticated;
|
|
146
|
+
grant execute on function public.publish_post_draft(uuid, int, text) to service_role;
|
|
147
|
+
|
|
148
|
+
-- Plans, arms or clears the schedule of a draft and returns its new version. p_arm = false (with a
|
|
149
|
+
-- time) only plans it: the time, the zone and the event window are checked, not the post, and the
|
|
150
|
+
-- draft stays unarmed (scheduled_by null), so the cron leaves it alone; with the current time it
|
|
151
|
+
-- disarms a draft and keeps its time, with no check (the time may have passed); "the current
|
|
152
|
+
-- time" is compared at millisecond precision, since the dashboard round-trips times through JS
|
|
153
|
+
-- Dates, and p_tz must be the current zone. Re-sending it to an unarmed draft with no error does
|
|
154
|
+
-- nothing. p_arm = true (also when p_arm is null) validates the whole post (check_post_draft)
|
|
155
|
+
-- and arms it. A null p_publish_at clears the time and disarms. Logged (schedule_post) only when the
|
|
156
|
+
-- armed state changes or an armed draft's time changes.
|
|
157
|
+
-- Errors: draft_not_found, draft_changed, invalid_time (also a missing or unknown p_tz), plus the
|
|
158
|
+
-- check_post_draft codes (topic_closed for a time outside the event window). Clearing a draft with
|
|
159
|
+
-- no time, no error and no arming does nothing.
|
|
160
|
+
drop function if exists public.schedule_post_draft(uuid, int, timestamptz, text, text);
|
|
161
|
+
create or replace function public.schedule_post_draft(
|
|
162
|
+
p_draft_id uuid, p_version int, p_publish_at timestamptz, p_tz text, p_actor text, p_arm boolean default true)
|
|
163
|
+
returns int
|
|
164
|
+
language plpgsql security definer set search_path = public
|
|
165
|
+
as $$
|
|
166
|
+
declare
|
|
167
|
+
d post_drafts;
|
|
168
|
+
was_armed boolean;
|
|
169
|
+
now_armed boolean := p_publish_at is not null and coalesce(p_arm, true);
|
|
170
|
+
keep boolean; -- unschedule: disarm and keep the current time, which may be past, so nothing is re-checked
|
|
171
|
+
begin
|
|
172
|
+
select * into d from post_drafts where id = p_draft_id for update;
|
|
173
|
+
if not found then raise exception 'draft_not_found'; end if;
|
|
174
|
+
if d.version is distinct from p_version then raise exception 'draft_changed'; end if;
|
|
175
|
+
was_armed := d.scheduled_by is not null;
|
|
176
|
+
keep := p_publish_at is not null and not coalesce(p_arm, true)
|
|
177
|
+
and date_trunc('milliseconds', p_publish_at) = date_trunc('milliseconds', d.publish_at)
|
|
178
|
+
and p_tz is not distinct from d.publish_tz;
|
|
179
|
+
|
|
180
|
+
if keep then
|
|
181
|
+
if not was_armed and d.publish_error is null then return d.version; end if; -- nothing changes
|
|
182
|
+
elsif p_publish_at is not null then
|
|
183
|
+
if p_publish_at <= now() or p_publish_at > now() + interval '1 year 1 day' then
|
|
184
|
+
raise exception 'invalid_time';
|
|
185
|
+
end if;
|
|
186
|
+
-- The zone is for display only, but it must be an IANA name (not a POSIX string the dashboard can't show).
|
|
187
|
+
if p_tz is null or p_tz not in (select name from pg_timezone_names) then raise exception 'invalid_time'; end if;
|
|
188
|
+
d.publish_tz := p_tz;
|
|
189
|
+
if now_armed then
|
|
190
|
+
perform check_post_draft(d, p_publish_at); -- the whole post, event window included
|
|
191
|
+
else
|
|
192
|
+
perform check_post_draft_window(d, p_publish_at);
|
|
193
|
+
end if;
|
|
194
|
+
elsif d.publish_at is null and d.publish_error is null and not was_armed then
|
|
195
|
+
return d.version; -- nothing to clear
|
|
196
|
+
end if;
|
|
197
|
+
|
|
198
|
+
update post_drafts set
|
|
199
|
+
publish_at = p_publish_at,
|
|
200
|
+
publish_tz = case when p_publish_at is not null then p_tz end,
|
|
201
|
+
scheduled_by = case when now_armed then p_actor end,
|
|
202
|
+
publish_error = null,
|
|
203
|
+
failed_at = null,
|
|
204
|
+
version = version + 1,
|
|
205
|
+
updated_by = p_actor,
|
|
206
|
+
updated_at = now()
|
|
207
|
+
where id = d.id;
|
|
208
|
+
|
|
209
|
+
if was_armed <> now_armed or (now_armed and d.publish_at is distinct from p_publish_at) then
|
|
210
|
+
insert into moderation_actions (actor_email, action, target_user_id, note)
|
|
211
|
+
values (p_actor, 'schedule_post', d.author_id,
|
|
212
|
+
'draft ' || d.id || case when now_armed
|
|
213
|
+
then ' at ' || to_char(p_publish_at at time zone 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"') else ' unscheduled' end);
|
|
214
|
+
end if;
|
|
215
|
+
return d.version + 1;
|
|
216
|
+
end;
|
|
217
|
+
$$;
|
|
218
|
+
|
|
219
|
+
revoke execute on function public.schedule_post_draft(uuid, int, timestamptz, text, text, boolean) from public, anon, authenticated;
|
|
220
|
+
grant execute on function public.schedule_post_draft(uuid, int, timestamptz, text, text, boolean) to service_role;
|
|
221
|
+
|
|
222
|
+
-- Publishes the armed drafts (scheduled_by set) whose time has come and returns how many went out. A draft more than
|
|
223
|
+
-- 30 minutes late is marked 'missed' instead; a draft that fails keeps its publish_at and
|
|
224
|
+
-- stores the error (the code for a P0001 error, else the message; cut to 200 characters),
|
|
225
|
+
-- so the next run skips it until the team reschedules it. A transient error (serialization
|
|
226
|
+
-- failure, deadlock, lock not available) leaves the draft untouched to be retried next run;
|
|
227
|
+
-- the 30-minute rule bounds the retries. Run by pg_cron every minute.
|
|
228
|
+
create or replace function public.publish_due_post_drafts()
|
|
229
|
+
returns int
|
|
230
|
+
language plpgsql security definer set search_path = public
|
|
231
|
+
as $$
|
|
232
|
+
declare
|
|
233
|
+
r record;
|
|
234
|
+
n int := 0;
|
|
235
|
+
begin
|
|
236
|
+
for r in
|
|
237
|
+
select id, version, scheduled_by, publish_at from post_drafts
|
|
238
|
+
where publish_at <= now() and publish_error is null and scheduled_by is not null
|
|
239
|
+
order by publish_at for update skip locked
|
|
240
|
+
loop
|
|
241
|
+
if r.publish_at < now() - interval '30 minutes' then
|
|
242
|
+
update post_drafts set publish_error = 'missed', failed_at = now() where id = r.id;
|
|
243
|
+
else
|
|
244
|
+
begin
|
|
245
|
+
perform publish_post_draft(r.id, r.version, r.scheduled_by);
|
|
246
|
+
n := n + 1;
|
|
247
|
+
exception
|
|
248
|
+
when serialization_failure or deadlock_detected or lock_not_available then
|
|
249
|
+
raise log 'publish_due_post_drafts: transient % on draft %', sqlstate, r.id;
|
|
250
|
+
when others then
|
|
251
|
+
update post_drafts set failed_at = now(),
|
|
252
|
+
publish_error = left(sqlerrm, 200)
|
|
253
|
+
where id = r.id;
|
|
254
|
+
end;
|
|
255
|
+
end if;
|
|
256
|
+
end loop;
|
|
257
|
+
return n;
|
|
258
|
+
end;
|
|
259
|
+
$$;
|
|
260
|
+
|
|
261
|
+
revoke execute on function public.publish_due_post_drafts() from public, anon, authenticated, service_role;
|
|
262
|
+
|
|
263
|
+
do $$
|
|
264
|
+
begin
|
|
265
|
+
perform cron.schedule('post-drafts-publish', '* * * * *', $cron$ select public.publish_due_post_drafts(); $cron$);
|
|
266
|
+
exception when others then
|
|
267
|
+
if sqlerrm like '%already exists%' then
|
|
268
|
+
raise notice 'cron job post-drafts-publish already scheduled, skipping';
|
|
269
|
+
else
|
|
270
|
+
raise;
|
|
271
|
+
end if;
|
|
272
|
+
end;
|
|
273
|
+
$$;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
-- community-sdk images/002_draft_images.sql (schema v1)
|
|
2
|
+
-- The nightly sweep keeps images that a shared post draft (core/014_post_drafts.sql)
|
|
3
|
+
-- points at, so a draft written yesterday still has its picture today.
|
|
4
|
+
-- Redefines post_images_unreferenced with one more reference check. Idempotent.
|
|
5
|
+
|
|
6
|
+
create or replace function public.post_images_unreferenced(p_limit int default 500)
|
|
7
|
+
returns setof text
|
|
8
|
+
language sql
|
|
9
|
+
stable
|
|
10
|
+
security definer
|
|
11
|
+
set search_path = ''
|
|
12
|
+
as $$
|
|
13
|
+
select o.name
|
|
14
|
+
from storage.objects o
|
|
15
|
+
where o.bucket_id = 'post-images'
|
|
16
|
+
and o.created_at < now() - interval '24 hours'
|
|
17
|
+
and not exists (
|
|
18
|
+
select 1 from public.posts p
|
|
19
|
+
where p.image_path = o.name and p.status <> 'deleted'
|
|
20
|
+
)
|
|
21
|
+
and not exists (
|
|
22
|
+
select 1 from public.comments c
|
|
23
|
+
where c.image_path = o.name and c.status <> 'deleted'
|
|
24
|
+
)
|
|
25
|
+
and not exists (
|
|
26
|
+
select 1 from public.post_drafts d
|
|
27
|
+
where d.image_path = o.name
|
|
28
|
+
)
|
|
29
|
+
order by o.created_at
|
|
30
|
+
limit p_limit;
|
|
31
|
+
$$;
|
|
32
|
+
|
|
33
|
+
revoke all on function public.post_images_unreferenced(int) from public, anon, authenticated;
|
|
34
|
+
grant execute on function public.post_images_unreferenced(int) to service_role;
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
-- community-sdk inbox/003_pushed_admin_posts.sql (schema v1)
|
|
2
|
+
-- The notification center is the history of the pushes: an admin post is listed
|
|
3
|
+
-- only once it was sent to everyone (`posts.broadcast_at`, core/013), dated when it
|
|
4
|
+
-- was sent. Admin posts that were never pushed leave the center. Same return shape
|
|
5
|
+
-- as before, so installed app versions read it unchanged.
|
|
6
|
+
|
|
7
|
+
create or replace function public.list_notifications(p_limit int default 50)
|
|
8
|
+
returns table (
|
|
9
|
+
id uuid,
|
|
10
|
+
kind text,
|
|
11
|
+
actor_id uuid,
|
|
12
|
+
actor_username text,
|
|
13
|
+
post_id uuid,
|
|
14
|
+
post_excerpt text,
|
|
15
|
+
created_at timestamptz
|
|
16
|
+
)
|
|
17
|
+
language sql stable security definer set search_path = public
|
|
18
|
+
as $$
|
|
19
|
+
(
|
|
20
|
+
select n.id, n.kind, n.actor_id, pr.username, n.post_id,
|
|
21
|
+
left(p.content, 140), n.created_at
|
|
22
|
+
from notifications n
|
|
23
|
+
left join profiles pr on pr.id = n.actor_id
|
|
24
|
+
left join posts p on p.id = n.post_id
|
|
25
|
+
where n.user_id = auth.uid()
|
|
26
|
+
and (n.post_id is null or p.status in ('visible', 'pending'))
|
|
27
|
+
)
|
|
28
|
+
union all
|
|
29
|
+
(
|
|
30
|
+
select p.id, 'official_post', p.author_id, pr.username, p.id,
|
|
31
|
+
left(p.content, 140), p.broadcast_at
|
|
32
|
+
from posts p
|
|
33
|
+
join profiles pr on pr.id = p.author_id
|
|
34
|
+
where p.status = 'visible' and p.broadcast_at is not null
|
|
35
|
+
and p.author_id <> auth.uid()
|
|
36
|
+
and p.broadcast_at > now() - interval '90 days'
|
|
37
|
+
)
|
|
38
|
+
order by created_at desc
|
|
39
|
+
limit p_limit;
|
|
40
|
+
$$;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
-- community-sdk push/005_broadcast_trigger.sql (schema v1)
|
|
2
|
+
-- Sends an admin post to everyone (broadcast-post) once it is visible and was asked
|
|
3
|
+
-- for (core/013_post_broadcasts.sql): on a visible insert, on publication by
|
|
4
|
+
-- moderation, or when asked after publication. broadcast-post stamps `broadcast_at`
|
|
5
|
+
-- before sending, so a post goes out at most once.
|
|
6
|
+
|
|
7
|
+
create or replace function public.broadcast_post_webhook()
|
|
8
|
+
returns trigger language plpgsql security definer set search_path = public as $$
|
|
9
|
+
begin
|
|
10
|
+
perform public.community_call_function('broadcast-post', jsonb_build_object('post_id', new.id));
|
|
11
|
+
return new;
|
|
12
|
+
end; $$;
|
|
13
|
+
|
|
14
|
+
create or replace trigger on_post_broadcast_ready
|
|
15
|
+
after insert or update of status, broadcast_requested on public.posts
|
|
16
|
+
for each row
|
|
17
|
+
when (new.status = 'visible' and new.broadcast_requested and new.broadcast_at is null)
|
|
18
|
+
execute function public.broadcast_post_webhook();
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
-- community-sdk streaks/002_to_badges.sql (schema v1)
|
|
2
|
+
-- Moves the streak onto the badges module (badges/001 must run first): the current
|
|
3
|
+
-- streak becomes the `streak` badge ({ since }), the best one `bestStreak`
|
|
4
|
+
-- ({ days }), their toggles `hidden_badges`.
|
|
5
|
+
-- Expand step: the legacy columns stay, and a trigger keeps both forms equal in both
|
|
6
|
+
-- directions, so app builds still writing and reading the legacy columns keep
|
|
7
|
+
-- working next to the new ones. streaks/003 drops them once those builds are gone.
|
|
8
|
+
-- Fully idempotent.
|
|
9
|
+
|
|
10
|
+
update public.profiles set
|
|
11
|
+
badges = badges
|
|
12
|
+
|| case when streak_started_at is not null
|
|
13
|
+
then jsonb_build_object('streak', jsonb_build_object('since', to_jsonb(streak_started_at)))
|
|
14
|
+
else '{}'::jsonb end
|
|
15
|
+
|| case when best_streak_days is not null
|
|
16
|
+
then jsonb_build_object('bestStreak', jsonb_build_object('days', best_streak_days))
|
|
17
|
+
else '{}'::jsonb end,
|
|
18
|
+
hidden_badges = array(
|
|
19
|
+
select distinct h from unnest(
|
|
20
|
+
hidden_badges
|
|
21
|
+
|| case when not show_streak then array['streak'] else '{}'::text[] end
|
|
22
|
+
|| case when not show_best_streak then array['bestStreak'] else '{}'::text[] end
|
|
23
|
+
) h
|
|
24
|
+
)
|
|
25
|
+
where streak_started_at is not null
|
|
26
|
+
or best_streak_days is not null
|
|
27
|
+
or not show_streak
|
|
28
|
+
or not show_best_streak;
|
|
29
|
+
|
|
30
|
+
create or replace function public.profiles_sync_legacy_streak()
|
|
31
|
+
returns trigger
|
|
32
|
+
language plpgsql
|
|
33
|
+
set search_path = ''
|
|
34
|
+
as $$
|
|
35
|
+
declare
|
|
36
|
+
legacy_changed boolean :=
|
|
37
|
+
(new.streak_started_at, new.best_streak_days) is distinct from (old.streak_started_at, old.best_streak_days);
|
|
38
|
+
legacy_shown_changed boolean :=
|
|
39
|
+
(new.show_streak, new.show_best_streak) is distinct from (old.show_streak, old.show_best_streak);
|
|
40
|
+
badges_changed boolean := new.badges is distinct from old.badges;
|
|
41
|
+
hidden_changed boolean := new.hidden_badges is distinct from old.hidden_badges;
|
|
42
|
+
begin
|
|
43
|
+
-- A new build wrote the badges: keep the legacy columns in step for old readers.
|
|
44
|
+
-- The badges win when one write carries both forms. A value that does not read as
|
|
45
|
+
-- a date or a day count leaves the legacy column empty rather than failing the write.
|
|
46
|
+
if badges_changed then
|
|
47
|
+
begin
|
|
48
|
+
new.streak_started_at := case when jsonb_typeof(new.badges -> 'streak' -> 'since') = 'string'
|
|
49
|
+
then (new.badges -> 'streak' ->> 'since')::timestamptz end;
|
|
50
|
+
exception when data_exception then
|
|
51
|
+
new.streak_started_at := null;
|
|
52
|
+
end;
|
|
53
|
+
begin
|
|
54
|
+
new.best_streak_days := case when jsonb_typeof(new.badges -> 'bestStreak' -> 'days') = 'number'
|
|
55
|
+
then greatest((new.badges -> 'bestStreak' ->> 'days')::numeric, 0)::int end;
|
|
56
|
+
exception when data_exception then
|
|
57
|
+
new.best_streak_days := null;
|
|
58
|
+
end;
|
|
59
|
+
-- An old build wrote the legacy values: rewrite the two streak badges.
|
|
60
|
+
elsif legacy_changed then
|
|
61
|
+
new.badges := (new.badges - 'streak' - 'bestStreak')
|
|
62
|
+
|| case when new.streak_started_at is not null
|
|
63
|
+
then jsonb_build_object('streak', jsonb_build_object('since', to_jsonb(new.streak_started_at)))
|
|
64
|
+
else '{}'::jsonb end
|
|
65
|
+
|| case when new.best_streak_days is not null
|
|
66
|
+
then jsonb_build_object('bestStreak', jsonb_build_object('days', new.best_streak_days))
|
|
67
|
+
else '{}'::jsonb end;
|
|
68
|
+
end if;
|
|
69
|
+
|
|
70
|
+
if hidden_changed then
|
|
71
|
+
new.show_streak := not ('streak' = any (new.hidden_badges));
|
|
72
|
+
new.show_best_streak := not ('bestStreak' = any (new.hidden_badges));
|
|
73
|
+
elsif legacy_shown_changed then
|
|
74
|
+
new.hidden_badges := array(
|
|
75
|
+
select h from unnest(new.hidden_badges) h where h not in ('streak', 'bestStreak')
|
|
76
|
+
)
|
|
77
|
+
|| case when not new.show_streak then array['streak'] else '{}'::text[] end
|
|
78
|
+
|| case when not new.show_best_streak then array['bestStreak'] else '{}'::text[] end;
|
|
79
|
+
end if;
|
|
80
|
+
return new;
|
|
81
|
+
end;
|
|
82
|
+
$$;
|
|
83
|
+
|
|
84
|
+
drop trigger if exists profiles_sync_legacy_streak on public.profiles;
|
|
85
|
+
create trigger profiles_sync_legacy_streak
|
|
86
|
+
before update on public.profiles
|
|
87
|
+
for each row execute function public.profiles_sync_legacy_streak();
|