Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

15.9 KB
Raw Blame
import { db } from "@cap/database";
import { getCurrentUser } from "@cap/database/auth/session";
import {
	comments,
	folders,
	organizationMembers,
	organizations,
	sharedVideos,
	spaceMembers,
	spaces,
	spaceVideos,
	users,
	videos,
	videoUploads,
} from "@cap/database/schema";
import { serverEnv } from "@cap/env";
import {
	Database,
	ImageUploads,
	makeCurrentUserLayer,
	resolveEffectiveVideoRules,
	Spaces,
} from "@cap/web-backend";
import {
	type ImageUpload,
	type Organisation,
	Space,
	type User,
	Video,
} from "@cap/web-domain";
import { and, count, desc, eq, inArray, isNull, or, sql } from "drizzle-orm";
import { Effect } from "effect";
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { runPromise } from "@/lib/server";
import { SharedCaps } from "./SharedCaps";

export const metadata: Metadata = {
	title: "Shared Caps — Cap",
};

export type SpaceMemberData = {
	id: string;
	userId: string;
	role: string;
	image?: ImageUpload.ImageUrl | null;
	name: string | null;
	email: string;
};

// --- Helper functions ---
async function fetchFolders(
	spaceId: Space.SpaceIdOrOrganisationId,
	allSpacesEntry: boolean,
) {
	const table = allSpacesEntry ? sharedVideos : spaceVideos;
	return db()
		.select({
			id: folders.id,
			name: folders.name,
			color: folders.color,
			public: folders.public,
			parentId: folders.parentId,
			spaceId: folders.spaceId,
			createdAt: folders.createdAt,
			videoCount: sql<number>`(
          SELECT COUNT(*) FROM ${table} WHERE ${table}.folderId = folders.id
        )`,
		})
		.from(folders)
		.where(and(eq(folders.spaceId, spaceId), isNull(folders.parentId)));
}

async function fetchOrganizationSettings(orgId: Organisation.OrganisationId) {
	const [row] = await db()
		.select({ settings: organizations.settings })
		.from(organizations)
		.where(eq(organizations.id, orgId))
		.limit(1);
	return row?.settings ?? null;
}

const fetchSpaceMembers = Effect.fn(function* (
	spaceId: Space.SpaceIdOrOrganisationId,
) {
	const db = yield* Database;
	const imageUploads = yield* ImageUploads;

	return yield* db
		.use((db) =>
			db
				.select({
					id: spaceMembers.id,
					userId: spaceMembers.userId,
					role: spaceMembers.role,
					name: users.name,
					email: users.email,
					image: users.image,
				})
				.from(spaceMembers)
				.innerJoin(users, eq(spaceMembers.userId, users.id))
				.where(eq(spaceMembers.spaceId, spaceId)),
		)
		.pipe(
			Effect.map((v) =>
				v.map(
					Effect.fn(function* (v) {
						return {
							...v,
							image: v.image
								? yield* imageUploads.resolveImageUrl(v.image)
								: null,
						};
					}),
				),
			),
			Effect.flatMap(Effect.all),
		);
});

const fetchOrganizationMembers = Effect.fn(function* (
	orgId: Organisation.OrganisationId,
) {
	const db = yield* Database;
	const imageUploads = yield* ImageUploads;

	return yield* db
		.use((db) =>
			db
				.select({
					id: organizationMembers.id,
					userId: organizationMembers.userId,
					role: organizationMembers.role,
					name: users.name,
					email: users.email,
					image: users.image,
				})
				.from(organizationMembers)
				.innerJoin(users, eq(organizationMembers.userId, users.id))
				.where(eq(organizationMembers.organizationId, orgId)),
		)
		.pipe(
			Effect.map((v) =>
				v.map(
					Effect.fn(function* (v) {
						return {
							...v,
							image: v.image
								? yield* imageUploads.resolveImageUrl(v.image)
								: null,
						};
					}),
				),
			),
			Effect.flatMap(Effect.all),
		);
});

type SharedSpaceRow = {
	videoId: string;
	id: string;
	name: string;
	organizationId: string;
	isOrg: boolean;
	iconUrl: ImageUpload.ImageUrlOrKey | null;
	settings: (typeof spaces.$inferSelect)["settings"] | null;
	hasPassword: boolean;
};

type SharedSpaceEntry = Omit<SharedSpaceRow, "videoId" | "iconUrl"> & {
	iconUrl: ImageUpload.ImageUrl | null;
};

// Sharing is stored in two places: `space_videos` for named spaces and
// `shared_videos` for the org-wide "All <Org>" entry. Both have to be read
// here, otherwise the sharing dialog opens with the org-wide entry unchecked
// and saving would drop it. The `shared_videos` read is limited to the page's
// organization plus the viewer's own memberships so other organizations'
// metadata never reaches the client, while an owner's dialog seed still covers
// every org share `shareCap` is able to preserve (it drops orgs the saver
// left, regardless of what was submitted).
async function fetchSharedSpacesForVideos(
	videoIds: Video.VideoId[],
	viewer: {
		userId: User.UserId;
		organizationId: Organisation.OrganisationId;
	},
): Promise<Record<string, SharedSpaceEntry[]>> {
	if (videoIds.length === 0) return {};

	const [spaceRows, organizationRows] = await Promise.all([
		db()
			.select({
				videoId: spaceVideos.videoId,
				id: spaces.id,
				name: spaces.name,
				organizationId: spaces.organizationId,
				iconUrl: spaces.iconUrl,
				settings: spaces.settings,
				hasPassword: sql`${spaces.password} IS NOT NULL`.mapWith(Boolean),
			})
			.from(spaceVideos)
			.innerJoin(spaces, eq(spaceVideos.spaceId, spaces.id))
			.where(inArray(spaceVideos.videoId, videoIds)),
		db()
			.select({
				videoId: sharedVideos.videoId,
				id: organizations.id,
				name: organizations.name,
				organizationId: organizations.id,
				iconUrl: organizations.iconUrl,
			})
			.from(sharedVideos)
			.innerJoin(
				organizations,
				eq(sharedVideos.organizationId, organizations.id),
			)
			.where(
				and(
					inArray(sharedVideos.videoId, videoIds),
					or(
						eq(sharedVideos.organizationId, viewer.organizationId),
						inArray(
							sharedVideos.organizationId,
							db()
								.select({ organizationId: organizationMembers.organizationId })
								.from(organizationMembers)
								.where(eq(organizationMembers.userId, viewer.userId)),
						),
					),
				),
			),
	]);

	const rows: SharedSpaceRow[] = [
		...spaceRows.map((row) => ({
			videoId: row.videoId,
			id: row.id,
			name: row.name,
			organizationId: row.organizationId,
			isOrg: false,
			iconUrl: row.iconUrl ?? null,
			settings: row.settings ?? null,
			hasPassword: row.hasPassword,
		})),
		...organizationRows.map((row) => ({
			videoId: row.videoId,
			id: row.id,
			name: row.name,
			organizationId: row.organizationId,
			isOrg: true,
			iconUrl: row.iconUrl ?? null,
			settings: null,
			hasPassword: false,
		})),
	];

	const resolvedRows = await Effect.gen(function* () {
		const imageUploads = yield* ImageUploads;

		return yield* Effect.all(
			rows.map(
				Effect.fn(function* (row: SharedSpaceRow) {
					return {
						...row,
						iconUrl: row.iconUrl
							? yield* imageUploads.resolveImageUrl(row.iconUrl)
							: null,
					};
				}),
			),
		);
	}).pipe(runPromise);

	return resolvedRows.reduce<Record<string, SharedSpaceEntry[]>>((acc, row) => {
		const entries = acc[row.videoId] ?? [];
		acc[row.videoId] = entries;
		const { videoId: _videoId, ...entry } = row;
		entries.push(entry);
		return acc;
	}, {});
}

export default async function SharedCapsPage(props: {
	params: Promise<{ spaceId: string }>;
	searchParams: Promise<{ [key: string]: string | string[] | undefined }>;
}) {
	const searchParams = await props.searchParams;
	const params = await props.params;
	const page = Number(searchParams.page) || 1;
	const limit = Number(searchParams.limit) || 15;
	const user = await getCurrentUser();
	if (!user) notFound();

	const spaceOrOrg = await Effect.flatMap(Spaces, (s) =>
		s.getSpaceOrOrg(Space.SpaceId.make(params.spaceId)),
	).pipe(
		Effect.catchTag("PolicyDenied", () => Effect.sync(() => notFound())),
		Effect.provide(makeCurrentUserLayer(user)),
		runPromise,
	);

	if (!spaceOrOrg) notFound();

	if (spaceOrOrg.variant === "space") {
		const { space } = spaceOrOrg;

		async function fetchSpaceVideos(
			spaceId: Space.SpaceIdOrOrganisationId,
			page: number,
			limit: number,
		) {
			const offset = (page - 1) * limit;
			const [videoRows, totalCountResult] = await Promise.all([
				db()
					.select({
						id: videos.id,
						ownerId: videos.ownerId,
						name: videos.name,
						createdAt: videos.createdAt,
						metadata: videos.metadata,
						isScreenshot: videos.isScreenshot,
						duration: videos.duration,
						public: videos.public,
						settings: videos.settings,
						hasPassword: sql`${videos.password} IS NOT NULL`.mapWith(Boolean),
						totalComments: sql<number>`COUNT(DISTINCT CASE WHEN ${comments.type} = 'text' THEN ${comments.id} END)`,
						totalReactions: sql<number>`COUNT(DISTINCT CASE WHEN ${comments.type} = 'emoji' THEN ${comments.id} END)`,
						ownerName: users.name,
						effectiveDate: videos.effectiveCreatedAt,
						hasActiveUpload:
							sql`${videoUploads.videoId} IS NOT NULL AND ${videos.isScreenshot} = false`.mapWith(
								Boolean,
							),
					})
					.from(spaceVideos)
					.innerJoin(videos, eq(spaceVideos.videoId, videos.id))
					.leftJoin(comments, eq(videos.id, comments.videoId))
					.leftJoin(users, eq(videos.ownerId, users.id))
					.leftJoin(videoUploads, eq(videos.id, videoUploads.videoId))
					.leftJoin(organizations, eq(videos.orgId, organizations.id))
					.where(
						and(
							eq(spaceVideos.spaceId, spaceId),
							isNull(spaceVideos.folderId),
							isNull(organizations.tombstoneAt),
						),
					)
					.groupBy(
						videos.id,
						videos.ownerId,
						videos.name,
						videos.createdAt,
						videos.metadata,
						videos.isScreenshot,
						videos.duration,
						videos.public,
						videos.settings,
						videos.password,
						users.name,
					)
					.orderBy(desc(videos.effectiveCreatedAt))
					.limit(limit)
					.offset(offset),
				db()
					.select({ count: count() })
					.from(spaceVideos)
					.where(
						and(eq(spaceVideos.spaceId, spaceId), isNull(spaceVideos.folderId)),
					),
			]);
			return {
				videos: videoRows,
				totalCount: totalCountResult[0]?.count || 0,
			};
		}

		const [
			spaceMembersData,
			organizationMembersData,
			foldersData,
			{ videos: spaceVideoData, totalCount },
			organizationSettings,
		] = await Promise.all([
			fetchSpaceMembers(space.id).pipe(runPromise),
			fetchOrganizationMembers(space.organizationId).pipe(runPromise),
			fetchFolders(space.id, false),
			fetchSpaceVideos(space.id, page, limit),
			fetchOrganizationSettings(space.organizationId),
		]);
		const resolvedSpace = await Effect.gen(function* () {
			const imageUploads = yield* ImageUploads;
			return {
				...space,
				iconUrl: space.iconUrl
					? yield* imageUploads.resolveImageUrl(space.iconUrl)
					: null,
			};
		}).pipe(runPromise);
		const sharedSpacesMap = await fetchSharedSpacesForVideos(
			spaceVideoData.map((video) => Video.VideoId.make(video.id)),
			{ userId: user.id, organizationId: space.organizationId },
		);
		const processedVideoData = spaceVideoData.map((video) => {
			const { effectiveDate: _effectiveDate, ...videoWithoutEffectiveDate } =
				video;
			const sharedSpaces = sharedSpacesMap[video.id] ?? [];
			const rules = resolveEffectiveVideoRules({
				videoSettings: video.settings,
				organizationSettings,
				// Org-wide entries are not spaces; their rules already come in
				// through `organizationSettings`.
				spaces: sharedSpaces.filter((space) => !space.isOrg),
			});
			return {
				...videoWithoutEffectiveDate,
				id: Video.VideoId.make(video.id),
				hasInheritedPassword: rules.hasInheritedPassword,
				inheritedPasswordSources: rules.inheritedPasswordSources,
				inheritedSpaceSettings: rules.inheritedSettings,
				sharedSpaces,
				ownerName: video.ownerName ?? null,
				metadata: video.metadata as
					| { customCreatedAt?: string; [key: string]: unknown }
					| undefined,
			};
		});

		return (
			<SharedCaps
				data={processedVideoData}
				count={totalCount}
				spaceData={resolvedSpace}
				spaceId={params.spaceId as Space.SpaceIdOrOrganisationId}
				analyticsEnabled={Boolean(
					serverEnv().TINYBIRD_TOKEN && serverEnv().TINYBIRD_HOST,
				)}
				spaceMembers={spaceMembersData}
				organizationMembers={organizationMembersData}
				currentUserId={user.id}
				folders={foldersData}
			/>
		);
	}

	if (spaceOrOrg.variant === "organization") {
		const { organization } = spaceOrOrg;

		async function fetchOrganizationVideos(
			orgId: Organisation.OrganisationId,
			page: number,
			limit: number,
		) {
			const offset = (page - 1) * limit;
			const [videoRows, totalCountResult] = await Promise.all([
				db()
					.select({
						id: videos.id,
						ownerId: videos.ownerId,
						name: videos.name,
						createdAt: videos.createdAt,
						metadata: videos.metadata,
						isScreenshot: videos.isScreenshot,
						duration: videos.duration,
						public: videos.public,
						settings: videos.settings,
						hasPassword: sql`${videos.password} IS NOT NULL`.mapWith(Boolean),
						totalComments: sql<number>`COUNT(DISTINCT CASE WHEN ${comments.type} = 'text' THEN ${comments.id} END)`,
						totalReactions: sql<number>`COUNT(DISTINCT CASE WHEN ${comments.type} = 'emoji' THEN ${comments.id} END)`,
						ownerName: users.name,
						effectiveDate: videos.effectiveCreatedAt,
						hasActiveUpload:
							sql`${videoUploads.videoId} IS NOT NULL AND ${videos.isScreenshot} = false`.mapWith(
								Boolean,
							),
					})
					.from(sharedVideos)
					.innerJoin(videos, eq(sharedVideos.videoId, videos.id))
					.leftJoin(comments, eq(videos.id, comments.videoId))
					.leftJoin(users, eq(videos.ownerId, users.id))
					.leftJoin(videoUploads, eq(videos.id, videoUploads.videoId))
					.where(
						and(
							eq(sharedVideos.organizationId, orgId),
							isNull(sharedVideos.folderId),
						),
					)
					.groupBy(
						videos.id,
						videos.ownerId,
						videos.name,
						videos.createdAt,
						videos.metadata,
						videos.isScreenshot,
						users.name,
						videos.duration,
						videos.public,
						videos.settings,
						videos.password,
					)
					.orderBy(desc(videos.effectiveCreatedAt))
					.limit(limit)
					.offset(offset),
				db()
					.select({ count: count() })
					.from(sharedVideos)
					.innerJoin(videos, eq(sharedVideos.videoId, videos.id))
					.where(
						and(
							eq(sharedVideos.organizationId, orgId),
							isNull(sharedVideos.folderId),
						),
					),
			]);
			return {
				videos: videoRows,
				totalCount: totalCountResult[0]?.count || 0,
			};
		}

		const [
			{ videos: orgVideoData, totalCount },
			organizationMembersData,
			foldersData,
			organizationSettings,
		] = await Promise.all([
			fetchOrganizationVideos(organization.id, page, limit),
			fetchOrganizationMembers(organization.id).pipe(runPromise),
			fetchFolders(organization.id, true),
			fetchOrganizationSettings(organization.id),
		]);
		const sharedSpacesMap = await fetchSharedSpacesForVideos(
			orgVideoData.map((video) => Video.VideoId.make(video.id)),
			{ userId: user.id, organizationId: organization.id },
		);
		const processedVideoData = orgVideoData.map((video) => {
			const { effectiveDate: _effectiveDate, ...videoWithoutEffectiveDate } =
				video;
			const sharedSpaces = sharedSpacesMap[video.id] ?? [];
			const rules = resolveEffectiveVideoRules({
				videoSettings: video.settings,
				organizationSettings,
				// Org-wide entries are not spaces; their rules already come in
				// through `organizationSettings`.
				spaces: sharedSpaces.filter((space) => !space.isOrg),
			});
			return {
				...videoWithoutEffectiveDate,
				id: Video.VideoId.make(video.id),
				hasInheritedPassword: rules.hasInheritedPassword,
				inheritedPasswordSources: rules.inheritedPasswordSources,
				inheritedSpaceSettings: rules.inheritedSettings,
				sharedSpaces,
				ownerName: video.ownerName ?? null,
				metadata: video.metadata as
					| { customCreatedAt?: string; [key: string]: unknown }
					| undefined,
			};
		});

		return (
			<SharedCaps
				data={processedVideoData}
				count={totalCount}
				hideSharedWith
				organizationData={organization}
				spaceId={params.spaceId as Space.SpaceIdOrOrganisationId}
				analyticsEnabled={Boolean(
					serverEnv().TINYBIRD_TOKEN && serverEnv().TINYBIRD_HOST,
				)}
				organizationMembers={organizationMembersData}
				currentUserId={user.id}
				folders={foldersData}
			/>
		);
	}
}