Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

perf(web): join share-page download permission checks

Aditya Garudf5bc6214d7ea
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 22c3eea7a..346bfa6ab 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -143,6 +143,7 @@ jobs:
__tests__/unit/playback-store.test.ts
__tests__/unit/remove-organization-member.test.ts
__tests__/unit/seo-demo-videos.test.ts
+ __tests__/unit/share-page-round-trips.test.ts
__tests__/unit/signed-baa-card.test.ts
__tests__/unit/space-folder-page-access.test.ts
__tests__/unit/space-page-round-trips.test.ts
@@ -155,6 +156,7 @@ jobs:
__tests__/unit/transcript-hours.test.ts
__tests__/unit/transcript-numbers.test.ts
__tests__/unit/video-analytics-access.test.ts
+ __tests__/unit/video-download-permissions.test.ts
__tests__/unit/voice-note-playback.test.ts
- name: Typecheck
diff --git a/apps/web/__tests__/unit/share-page-round-trips.test.ts b/apps/web/__tests__/unit/share-page-round-trips.test.ts
new file mode 100644
index 000000000..27db7cf59
--- /dev/null
+++ b/apps/web/__tests__/unit/share-page-round-trips.test.ts
@@ -0,0 +1,324 @@
+import { createHash } from "node:crypto";
+import { organizations } from "@cap/database/schema";
+import { getTableColumns } from "drizzle-orm";
+import { Context, Effect } from "effect";
+import { type ComponentProps, isValidElement, type ReactElement } from "react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({ query: vi.fn() }));
+
+vi.mock("server-only", () => ({}));
+vi.mock("@cap/database", async () => {
+ const { drizzle } = await import("drizzle-orm/mysql-proxy");
+ const client = drizzle(mocks.query);
+ return { db: () => client };
+});
+vi.mock("@cap/database/auth/session", () => ({
+ getCurrentUser: async () => ({ id: "viewer", activeOrganizationId: "org-1" }),
+}));
+vi.mock("@cap/env", () => ({
+ buildEnv: { NEXT_PUBLIC_WEB_URL: "https://cap.so" },
+ serverEnv: () => ({}),
+}));
+vi.mock("@cap/ui", () => ({ Logo: () => null }));
+vi.mock("@cap/utils", () => ({ userIsPro: () => true }));
+vi.mock("@cap/web-backend", async () => {
+ const { Context, Effect } = await import("effect");
+ const { resolveEffectiveVideoRules } = await import(
+ "../../../../packages/web-backend/src/Videos/EffectiveVideoRules"
+ );
+ return {
+ Database: Context.GenericTag("SharePerfDatabase"),
+ ImageUploads: Context.GenericTag("SharePerfImages"),
+ Videos: Context.GenericTag("SharePerfVideos"),
+ Tinybird: Context.GenericTag("SharePerfAnalytics"),
+ provideOptionalAuth: <A, E, R>(effect: Effect.Effect<A, E, R>) => effect,
+ resolveEffectiveVideoRules,
+ };
+});
+vi.mock("@cap/web-backend/src/Videos/VideosPolicy", () => ({
+ VideosPolicy: Context.GenericTag("SharePerfPolicy"),
+}));
+vi.mock("@/lib/server", async () => {
+ const { db } = await import("@cap/database");
+ return {
+ runPromise: <A, E>(effect: Effect.Effect<A, E, unknown>) =>
+ effect.pipe(
+ Effect.provideService(Context.GenericTag("SharePerfPolicy"), {
+ canViewLoaded: () => Effect.void,
+ }),
+ Effect.provideService(Context.GenericTag("SharePerfDatabase"), {
+ use: <T>(callback: (client: ReturnType<typeof db>) => Promise<T>) =>
+ Effect.promise(() => callback(db())),
+ }),
+ Effect.provideService(Context.GenericTag("SharePerfImages"), {
+ resolveImageUrl: (url: string) => Effect.succeed(url),
+ }),
+ Effect.provideService(Context.GenericTag("SharePerfAnalytics"), {
+ querySql: () => Effect.succeed({ data: [{ views: 120 }] }),
+ }),
+ Effect.runPromise,
+ ),
+ };
+});
+vi.mock("next/headers", () => ({ headers: async () => new Headers() }));
+vi.mock("next/navigation", () => ({ notFound: vi.fn() }));
+vi.mock("@/lib/ai/provider", () => ({ isAiConfigured: () => false }));
+vi.mock("@/lib/desktop-segments-recovery", () => ({
+ completeDesktopSegmentsManifestAndQueue: vi.fn(),
+}));
+vi.mock("@/lib/Notification", () => ({
+ createNotification: async () => undefined,
+}));
+vi.mock("@/lib/loom-deferred-processing", () => ({
+ getPendingLoomProcessing: () => null,
+}));
+vi.mock("@/lib/public-share-video", () => ({ getPublicShareVideo: vi.fn() }));
+vi.mock("@/lib/share-playback", () => ({
+ getSharePlaybackUrl: async () => "https://media.example.com/result.mp4",
+}));
+vi.mock("@/lib/share-web-url", () => ({ resolveShareWebUrl: vi.fn() }));
+vi.mock("@/lib/transcribe", () => ({ transcribeVideo: vi.fn() }));
+vi.mock("@/utils/flags", () => ({ isAiGenerationEnabled: async () => true }));
+vi.mock("@/app/s/[videoId]/_components/PasswordGate", () => ({
+ PasswordGate: () => null,
+}));
+vi.mock("@/app/s/[videoId]/_components/PendingRecordingShare", () => ({
+ PendingRecordingShare: () => null,
+}));
+vi.mock("@/app/s/[videoId]/_components/ShareHeader", () => ({
+ ShareHeader: () => null,
+}));
+vi.mock("@/app/s/[videoId]/Share", () => ({ Share: () => null }));
+
+import type { ShareHeader } from "@/app/s/[videoId]/_components/ShareHeader";
+import ShareVideoPage from "@/app/s/[videoId]/page";
+import type { Share } from "@/app/s/[videoId]/Share";
+
+const createdAt = "2026-10-20 12:00:00";
+const organization = {
+ id: "org-1",
+ name: "Team",
+ ownerId: "viewer",
+ settings: {},
+};
+const recording = {
+ id: "video-1",
+ name: "Ten minute walkthrough",
+ ownerId: "owner",
+ orgId: "org-1",
+ createdAt,
+ updatedAt: createdAt,
+ effectiveCreatedAt: createdAt,
+ source: { type: "desktopMP4" },
+ metadata: { summary: "Project walkthrough" },
+ duration: 600,
+ public: 1,
+ isScreenshot: 0,
+ transcriptionStatus: "COMPLETE",
+};
+
+function project(
+ query: string,
+ tables: Record<string, Record<string, unknown>>,
+) {
+ return query
+ .slice(7, query.indexOf(" from "))
+ .split(", ")
+ .map((column) => {
+ if (column.includes(" IS NOT NULL")) return 0;
+ const match = /^`(\w+)`\.`(\w+)`$/.exec(column);
+ if (!match) throw new Error(`Unexpected projection: ${column}`);
+ return tables[match[1] ?? ""]?.[match[2] ?? ""] ?? null;
+ });
+}
+
+function rowsFor(query: string) {
+ if (
+ query.includes("from `videos` inner join") ||
+ query.includes("from `videos` left join")
+ ) {
+ return [
+ project(query, {
+ videos: recording,
+ users: { id: "owner", name: "Owner", email: "[email protected]" },
+ organizations: organization,
+ shared_videos: { organizationId: "shared-org" },
+ }),
+ ];
+ }
+ if (query.includes("from `comments`")) {
+ return Array.from({ length: 30 }, (_, index) =>
+ project(query, {
+ comments: {
+ id: `comment-${index}`,
+ videoId: recording.id,
+ authorId: `author-${index % 5}`,
+ content: `Review note ${index}`,
+ type: "text",
+ timestamp: index * 20,
+ createdAt,
+ updatedAt: createdAt,
+ },
+ users: {
+ name: `Reviewer ${index % 5}`,
+ image: "https://example.com/avatar.png",
+ },
+ }),
+ );
+ }
+ if (query.includes("from `organizations`")) {
+ if (query.includes("left join")) return [["viewer", "member"]];
+ if (query.includes("inner join")) return [];
+ if (query.startsWith("select `id`, `name` from"))
+ return [["org-1", "Team"]];
+ return [
+ Object.values(getTableColumns(organizations)).map(
+ (column) =>
+ (organization as Record<string, unknown>)[column.name] ?? null,
+ ),
+ ];
+ }
+ if (query.includes("from `organization_members`")) {
+ if (query.includes("count(")) return [[5]];
+ if (query.startsWith("select `role`")) return [["member"]];
+ return [];
+ }
+ if (query.includes("from `spaces`"))
+ return Array.from({ length: 3 }, (_, i) => [
+ `dashboard-space-${i}`,
+ 0,
+ "Public",
+ 0,
+ `Space ${i}`,
+ null,
+ "org-1",
+ "viewer",
+ null,
+ {},
+ "member",
+ 0,
+ 5,
+ 10,
+ ]);
+ if (query.includes("from `videos`")) return [["org-1"]];
+ if (query.includes("from `shared_videos`")) {
+ if (query.includes("COUNT(")) return [[10]];
+ if (query.includes("inner join `organization_members`")) return [];
+ if (query.includes("inner join `organizations`"))
+ return [["shared-org", "Shared team", "shared-org", null]];
+ return [["shared-org"]];
+ }
+ if (query.includes("from `space_videos`")) {
+ if (query.includes("inner join `space_members`"))
+ return query.includes("inner join `spaces`")
+ ? [["space-1", "Project", "org-1"]]
+ : [["space-member"]];
+ if (query.includes("inner join `spaces`"))
+ return [["space-1", "Project", "org-1", null, {}, 0]];
+ return [["space-1"]];
+ }
+ if (query.includes("from `space_members`")) return [["space-member"]];
+ if (query.includes("from `video_edits`")) return [];
+ throw new Error(`Unexpected query: ${query}`);
+}
+
+async function loadPage() {
+ const page = (await ShareVideoPage({
+ params: Promise.resolve({ videoId: recording.id }),
+ searchParams: Promise.resolve({}),
+ })) as ReactElement<{ children: unknown }>;
+ const authorized = page.props.children;
+ if (!isValidElement(authorized) || typeof authorized.type !== "function") {
+ throw new Error("Expected authorized content");
+ }
+ const content = await (
+ authorized.type as (
+ props: unknown,
+ ) => Promise<
+ ReactElement<{ children: ReactElement<ComponentProps<typeof Share>> }>
+ >
+ )(authorized.props);
+ const props = content.props.children.props;
+ const { header, comments, views, initialPlaybackUrl, ...data } = props;
+ const headerElement = header as ReactElement<
+ ComponentProps<typeof ShareHeader>
+ >;
+ return {
+ ...data,
+ header: { ...headerElement.props, views: await headerElement.props.views },
+ comments: await comments,
+ views: await views,
+ initialPlaybackUrl: await initialPlaybackUrl,
+ };
+}
+
+beforeEach(() => mocks.query.mockReset());
+
+describe("share page database round trips", () => {
+ it("keeps download permission and edit checks within the existing page load", async () => {
+ const pending: Array<() => void> = [];
+ mocks.query.mockImplementation(
+ (query: string) =>
+ new Promise((resolve) => {
+ pending.push(() => resolve({ rows: rowsFor(query) }));
+ }),
+ );
+ let settled = false;
+ const page = loadPage().finally(() => {
+ settled = true;
+ });
+ let roundTrips = 0;
+ let idleTicks = 0;
+ while (!settled) {
+ const issued = mocks.query.mock.calls.length;
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ if (mocks.query.mock.calls.length !== issued || pending.length === 0) {
+ idleTicks = 0;
+ continue;
+ }
+ if (++idleTicks < 3) continue;
+ idleTicks = 0;
+ roundTrips++;
+ for (const release of pending.splice(0)) release();
+ }
+ const result = await page;
+ expect(result.comments).toHaveLength(30);
+ expect(result.data).toMatchObject({ duration: 600 });
+ expect(result.header.spacesData).toHaveLength(4);
+ expect(result.header).toMatchObject({ canDownload: true, hasEdits: false });
+ expect({ roundTrips, queries: mocks.query.mock.calls.length }).toEqual({
+ roundTrips: 4,
+ queries: 20,
+ });
+ });
+
+ it.skipIf(!process.env.CAP_SHARE_PAGE_BENCH)(
+ "measures simulated 20ms database latency",
+ async () => {
+ const samples: number[] = [];
+ const outputs = new Set<string>();
+ mocks.query.mockImplementation(async (query: string) => {
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ return { rows: rowsFor(query) };
+ });
+ for (let iteration = 0; iteration < 22; iteration++) {
+ const start = performance.now();
+ const result = await loadPage();
+ if (iteration > 0) samples.push(performance.now() - start);
+ outputs.add(
+ createHash("sha256").update(JSON.stringify(result)).digest("hex"),
+ );
+ }
+ samples.sort((a, b) => a - b);
+ expect(outputs.size).toBe(1);
+ console.log(
+ JSON.stringify({
+ medianMs: samples[10],
+ queriesPerLoad: mocks.query.mock.calls.length / 22,
+ output: [...outputs][0],
+ }),
+ );
+ },
+ );
+});
diff --git a/apps/web/__tests__/unit/video-download-permissions.test.ts b/apps/web/__tests__/unit/video-download-permissions.test.ts
index 5737566ef..6534b8e2c 100644
--- a/apps/web/__tests__/unit/video-download-permissions.test.ts
+++ b/apps/web/__tests__/unit/video-download-permissions.test.ts
@@ -1,114 +1,152 @@
-import type { Organisation, User, Video } from "@cap/web-domain";
+import { User, Video } from "@cap/web-domain";
import { beforeEach, describe, expect, it, vi } from "vitest";
-const schema = {
- organizationMembers: { table: "organizationMembers" },
- sharedVideos: { table: "sharedVideos" },
- spaceMembers: { table: "spaceMembers" },
- spaceVideos: { table: "spaceVideos" },
-};
+const mocks = vi.hoisted(() => ({ query: vi.fn() }));
-vi.mock("@cap/database/schema", () => schema);
-
-// Each select() call resolves against the next queued result, and the table it
-// read is recorded so a test can assert which lookups actually happened.
-let queued: unknown[][] = [];
-const tablesRead: string[] = [];
-
-const mockDb = {
- select: () => mockDb,
- from: (table: { table: string }) => {
- tablesRead.push(table.table);
- return mockDb;
- },
- where: () => {
- const rows = queued.shift() ?? [];
- const result = Promise.resolve(rows) as Promise<unknown[]> & {
- limit: () => Promise<unknown[]>;
- };
- result.limit = () => Promise.resolve(rows);
- return result;
- },
-};
-
-vi.mock("@cap/database", () => ({ db: () => mockDb }));
+vi.mock("@cap/database", async () => {
+ const { drizzle } = await import("drizzle-orm/mysql-proxy");
+ const client = drizzle(mocks.query);
+ return { db: () => client };
+});
-const { canUserDownloadVideo } = await import(
- "../../lib/video-download-permissions"
-);
+import { canUserDownloadVideo } from "@/lib/video-download-permissions";
-const OWNER = "user-owner" as User.UserId;
-const OTHER = "user-other" as User.UserId;
-const VIDEO = "video-1" as Video.VideoId;
-const VIDEO_ORG = "org-owning-the-video" as Organisation.OrganisationId;
+const OWNER = User.UserId.make("user-owner");
+const OTHER = User.UserId.make("user-other");
+const VIDEO = Video.VideoId.make("video-1");
+let organizationShared: boolean;
+let organizationMember: boolean;
+let spaceShared: boolean;
+let spaceMember: boolean;
-function call(userId: User.UserId) {
+function call(userId = OTHER) {
return canUserDownloadVideo({ userId, ownerId: OWNER, videoId: VIDEO });
}
-describe("canUserDownloadVideo", () => {
- beforeEach(() => {
- queued = [];
- tablesRead.length = 0;
+beforeEach(() => {
+ organizationShared = false;
+ organizationMember = false;
+ spaceShared = false;
+ spaceMember = false;
+ mocks.query.mockImplementation(async (query: string, params: unknown[]) => {
+ if (query.includes("inner join")) {
+ const organization = query.includes("`organization_members`");
+ const membershipTable = organization
+ ? "organization_members"
+ : "space_members";
+ const shareTable = organization ? "shared_videos" : "space_videos";
+ const key = organization ? "organizationId" : "spaceId";
+ expect(query).toContain(
+ `\`${shareTable}\`.\`${key}\` = \`${membershipTable}\`.\`${key}\``,
+ );
+ expect(query).toContain(`\`${membershipTable}\`.\`userId\` = ?`);
+ expect(query).toContain(`\`${shareTable}\`.\`videoId\` = ?`);
+ expect(query).toContain("limit ?");
+ expect(params).toEqual([OTHER, VIDEO, 1]);
+ const allowed = organization
+ ? organizationShared && organizationMember
+ : spaceShared && spaceMember;
+ return { rows: allowed ? [["membership-1"]] : [] };
+ }
+ if (query.includes("from `shared_videos`")) {
+ return { rows: organizationShared ? [["org-1"]] : [] };
+ }
+ if (query.includes("from `organization_members`")) {
+ return { rows: organizationMember ? [["membership-1"]] : [] };
+ }
+ if (query.includes("from `space_videos`")) {
+ return { rows: spaceShared ? [["space-1"]] : [] };
+ }
+ if (query.includes("from `space_members`")) {
+ return { rows: spaceMember ? [["membership-1"]] : [] };
+ }
+ throw new Error(`Unexpected query: ${query}`);
});
+});
+describe("canUserDownloadVideo", () => {
it("allows the owner without querying shares", async () => {
expect(await call(OWNER)).toBe(true);
- expect(tablesRead).toEqual([]);
+ expect(mocks.query).not.toHaveBeenCalled();
});
- // The video's own orgId must not grant download access: VideosPolicy.canView
- // requires an explicit sharedVideos row, and no creation path writes one, so
- // trusting orgId let org colleagues download videos they cannot open.
- it("denies an org colleague when the video was never explicitly shared", async () => {
- queued = [
- [], // sharedVideos: no explicit org share
- [], // spaceVideos: no space share
- ];
-
- expect(await call(OTHER)).toBe(false);
- expect(tablesRead).toContain("sharedVideos");
- expect(tablesRead).not.toContain("organizationMembers");
+ it.each([
+ [false, false, false, false],
+ [false, false, false, true],
+ [false, false, true, false],
+ [false, false, true, true],
+ [false, true, false, false],
+ [false, true, false, true],
+ [false, true, true, false],
+ [false, true, true, true],
+ [true, false, false, false],
+ [true, false, false, true],
+ [true, false, true, false],
+ [true, false, true, true],
+ [true, true, false, false],
+ [true, true, false, true],
+ [true, true, true, false],
+ [true, true, true, true],
+ ])(
+ "requires an explicit share and membership: org %s/%s, space %s/%s",
+ async (orgShared, orgMember, sharedSpace, memberOfSpace) => {
+ organizationShared = orgShared;
+ organizationMember = orgMember;
+ spaceShared = sharedSpace;
+ spaceMember = memberOfSpace;
+ expect(await call()).toBe(
+ (orgShared && orgMember) || (sharedSpace && memberOfSpace),
+ );
+ },
+ );
+
+ it("checks both memberships in one round trip without loading share lists", async () => {
+ const pending: Array<() => void> = [];
+ mocks.query.mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ pending.push(() => resolve({ rows: [] }));
+ }),
+ );
+ const result = call();
+ await vi.waitFor(() => expect(pending).toHaveLength(2));
+ for (const release of pending) release();
+ expect(await result).toBe(false);
+ expect(mocks.query).toHaveBeenCalledTimes(2);
+ expect(
+ mocks.query.mock.calls.every(([query]) => query.includes("inner join")),
+ ).toBe(true);
});
- it("allows a member of an org the video was explicitly shared with", async () => {
- queued = [
- [{ organizationId: VIDEO_ORG }], // sharedVideos
- [{ id: "membership-1" }], // organizationMembers
- ];
-
- expect(await call(OTHER)).toBe(true);
- expect(tablesRead).toEqual(["sharedVideos", "organizationMembers"]);
+ it("allows an org member even when the prefetched space lookup fails", async () => {
+ mocks.query.mockImplementation(async (query: string) => {
+ if (query.includes("`space_videos`"))
+ throw new Error("Space lookup failed");
+ return { rows: [["organization-member"]] };
+ });
+ expect(await call()).toBe(true);
});
- it("denies a non-member even when the video is shared with some org", async () => {
- queued = [
- [{ organizationId: VIDEO_ORG }], // sharedVideos
- [], // organizationMembers: not a member
- [], // spaceVideos
- ];
-
- expect(await call(OTHER)).toBe(false);
+ it("propagates an org lookup failure even when the space lookup succeeds", async () => {
+ const failure = new Error("Organization lookup failed");
+ mocks.query.mockImplementation(async (query: string) => {
+ if (query.includes("`shared_videos`")) throw failure;
+ return { rows: [["space-member"]] };
+ });
+ await expect(call()).rejects.toMatchObject({ cause: failure });
});
- it("allows a member of a space the video was shared into", async () => {
- queued = [
- [], // sharedVideos
- [{ spaceId: "space-1" }], // spaceVideos
- [{ id: "space-membership-1" }], // spaceMembers
- ];
-
- expect(await call(OTHER)).toBe(true);
- expect(tablesRead).toContain("spaceMembers");
+ it("propagates a space lookup failure when there is no org membership", async () => {
+ const failure = new Error("Space lookup failed");
+ mocks.query.mockImplementation(async (query: string) => {
+ if (query.includes("`space_videos`")) throw failure;
+ return { rows: [] };
+ });
+ await expect(call()).rejects.toMatchObject({ cause: failure });
});
- it("denies a non-member of the space the video was shared into", async () => {
- queued = [
- [], // sharedVideos
- [{ spaceId: "space-1" }], // spaceVideos
- [], // spaceMembers
- ];
-
- expect(await call(OTHER)).toBe(false);
+ it("propagates database failures", async () => {
+ mocks.query.mockRejectedValue(new Error("Database unavailable"));
+ await expect(call()).rejects.toThrow();
});
});
diff --git a/apps/web/lib/video-download-permissions.ts b/apps/web/lib/video-download-permissions.ts
index d7d3e10ab..90b4dcb05 100644
--- a/apps/web/lib/video-download-permissions.ts
+++ b/apps/web/lib/video-download-permissions.ts
@@ -6,7 +6,7 @@ import {
spaceVideos,
} from "@cap/database/schema";
import type { User, Video } from "@cap/web-domain";
-import { and, eq, inArray } from "drizzle-orm";
+import { and, eq } from "drizzle-orm";
// Download access must not be broader than view access. VideosPolicy.canView
// grants org members access only through an explicit sharedVideos row (see
@@ -24,49 +24,37 @@ export async function canUserDownloadVideo({
}): Promise<boolean> {
if (userId === ownerId) return true;
- const sharedOrgs = await db()
- .select({ organizationId: sharedVideos.organizationId })
- .from(sharedVideos)
- .where(eq(sharedVideos.videoId, videoId));
-
- if (sharedOrgs.length > 0) {
- const [orgMembership] = await db()
+ const [organizationMembership, spaceMembership] = await Promise.allSettled([
+ db()
.select({ id: organizationMembers.id })
- .from(organizationMembers)
- .where(
+ .from(sharedVideos)
+ .innerJoin(
+ organizationMembers,
and(
+ eq(sharedVideos.organizationId, organizationMembers.organizationId),
eq(organizationMembers.userId, userId),
- inArray(
- organizationMembers.organizationId,
- sharedOrgs.map((org) => org.organizationId),
- ),
),
)
- .limit(1);
-
- if (orgMembership) return true;
- }
-
- const sharedSpaces = await db()
- .select({ spaceId: spaceVideos.spaceId })
- .from(spaceVideos)
- .where(eq(spaceVideos.videoId, videoId));
-
- if (sharedSpaces.length === 0) return false;
-
- const [spaceMembership] = await db()
- .select({ id: spaceMembers.id })
- .from(spaceMembers)
- .where(
- and(
- eq(spaceMembers.userId, userId),
- inArray(
- spaceMembers.spaceId,
- sharedSpaces.map((space) => space.spaceId),
+ .where(eq(sharedVideos.videoId, videoId))
+ .limit(1),
+ db()
+ .select({ id: spaceMembers.id })
+ .from(spaceVideos)
+ .innerJoin(
+ spaceMembers,
+ and(
+ eq(spaceVideos.spaceId, spaceMembers.spaceId),
+ eq(spaceMembers.userId, userId),
),
- ),
- )
- .limit(1);
+ )
+ .where(eq(spaceVideos.videoId, videoId))
+ .limit(1),
+ ]);
+
+ if (organizationMembership.status === "rejected")
+ throw organizationMembership.reason;
+ if (organizationMembership.value[0]) return true;
+ if (spaceMembership.status === "rejected") throw spaceMembership.reason;
- return Boolean(spaceMembership);
+ return Boolean(spaceMembership.value[0]);
}