Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Refactor ShareVideoPage error handling and code style

Richie McIlroycf1787b02654
diff --git a/apps/web/app/(org)/dashboard/caps/Caps.tsx b/apps/web/app/(org)/dashboard/caps/Caps.tsx
index bb4a846e2..fc8a2b95c 100644
--- a/apps/web/app/(org)/dashboard/caps/Caps.tsx
+++ b/apps/web/app/(org)/dashboard/caps/Caps.tsx
@@ -13,11 +13,11 @@ import { useEffectMutation, useRpcClient } from "@/lib/EffectRuntime";
import { useVideosAnalyticsQuery } from "@/lib/Queries/Analytics";
import { useDashboardContext } from "../Contexts";
import {
- NewFolderDialog,
- SelectedCapsBar,
- UploadCapButton,
- UploadPlaceholderCard,
- WebRecorderDialog,
+ NewFolderDialog,
+ SelectedCapsBar,
+ UploadCapButton,
+ UploadPlaceholderCard,
+ WebRecorderDialog,
} from "./components";
import { CapCard } from "./components/CapCard/CapCard";
import { CapPagination } from "./components/CapPagination";
@@ -27,306 +27,306 @@ import Folder from "./components/Folder";
import { useUploadingStatus } from "./UploadingContext";
export type VideoData = {
- id: Video.VideoId;
- ownerId: string;
- name: string;
- createdAt: Date;
- public: boolean;
- totalComments: number;
- totalReactions: number;
- foldersData: FolderDataType[];
- sharedOrganizations: {
- id: string;
- name: string;
- iconUrl?: ImageUpload.ImageUrl | null;
- }[];
- sharedSpaces?: {
- id: string;
- name: string;
- isOrg: boolean;
- organizationId: string;
- }[];
- ownerName: string;
- metadata?: VideoMetadata;
- hasPassword: boolean;
- hasActiveUpload: boolean;
+ id: Video.VideoId;
+ ownerId: string;
+ name: string;
+ createdAt: Date;
+ public: boolean;
+ totalComments: number;
+ totalReactions: number;
+ foldersData: FolderDataType[];
+ sharedOrganizations: {
+ id: string;
+ name: string;
+ iconUrl?: ImageUpload.ImageUrl | null;
+ }[];
+ sharedSpaces?: {
+ id: string;
+ name: string;
+ isOrg: boolean;
+ organizationId: string;
+ }[];
+ ownerName: string;
+ metadata?: VideoMetadata;
+ hasPassword: boolean;
+ hasActiveUpload: boolean;
}[];
export const Caps = ({
- data,
- count,
- analyticsEnabled,
- folders,
+ data,
+ count,
+ analyticsEnabled,
+ folders,
}: {
- data: VideoData;
- count: number;
- folders: FolderDataType[];
- analyticsEnabled: boolean;
+ data: VideoData;
+ count: number;
+ folders: FolderDataType[];
+ analyticsEnabled: boolean;
}) => {
- const router = useRouter();
- const params = useSearchParams();
- const page = Number(params.get("page")) || 1;
- const { user } = useDashboardContext();
- const limit = 15;
- const [openNewFolderDialog, setOpenNewFolderDialog] = useState(false);
- const totalPages = Math.ceil(count / limit);
- const previousCountRef = useRef<number>(0);
- const [selectedCaps, setSelectedCaps] = useState<Video.VideoId[]>([]);
- const [isDraggingCap, setIsDraggingCap] = useState(false);
+ const router = useRouter();
+ const params = useSearchParams();
+ const page = Number(params.get("page")) || 1;
+ const { user } = useDashboardContext();
+ const limit = 15;
+ const [openNewFolderDialog, setOpenNewFolderDialog] = useState(false);
+ const totalPages = Math.ceil(count / limit);
+ const previousCountRef = useRef<number>(0);
+ const [selectedCaps, setSelectedCaps] = useState<Video.VideoId[]>([]);
+ const [isDraggingCap, setIsDraggingCap] = useState(false);
- const anyCapSelected = selectedCaps.length > 0;
+ const anyCapSelected = selectedCaps.length > 0;
- const analyticsQuery = useVideosAnalyticsQuery(
- data.map((video) => video.id),
- analyticsEnabled,
- );
- const analytics: Partial<Record<Video.VideoId, number>> =
- analyticsQuery.data || {};
- const isLoadingAnalytics = analyticsEnabled && analyticsQuery.isLoading;
+ const analyticsQuery = useVideosAnalyticsQuery(
+ data.map((video) => video.id),
+ analyticsEnabled
+ );
+ const analytics: Partial<Record<Video.VideoId, number>> =
+ analyticsQuery.data || {};
+ const isLoadingAnalytics = analyticsEnabled && analyticsQuery.isLoading;
- const handleCapSelection = (capId: Video.VideoId) => {
- setSelectedCaps((prev) => {
- const newSelection = prev.includes(capId)
- ? prev.filter((id) => id !== capId)
- : [...prev, capId];
+ const handleCapSelection = (capId: Video.VideoId) => {
+ setSelectedCaps((prev) => {
+ const newSelection = prev.includes(capId)
+ ? prev.filter((id) => id !== capId)
+ : [...prev, capId];
- previousCountRef.current = prev.length;
+ previousCountRef.current = prev.length;
- return newSelection;
- });
- };
+ return newSelection;
+ });
+ };
- const rpc = useRpcClient() as {
- VideoDelete: (id: Video.VideoId) => Effect.Effect<void, unknown, never>;
- };
+ const rpc = useRpcClient() as {
+ VideoDelete: (id: Video.VideoId) => Effect.Effect<void, unknown, never>;
+ };
- const { mutate: deleteCaps, isPending: isDeletingCaps } = useEffectMutation({
- mutationFn: Effect.fn(function* (ids: Video.VideoId[]) {
- if (ids.length === 0) return { success: 0 };
+ const { mutate: deleteCaps, isPending: isDeletingCaps } = useEffectMutation({
+ mutationFn: Effect.fn(function* (ids: Video.VideoId[]) {
+ if (ids.length === 0) return { success: 0 };
- const results = yield* Effect.all(
- ids.map((id) => rpc.VideoDelete(id).pipe(Effect.exit)),
- { concurrency: 10 },
- );
+ const results = yield* Effect.all(
+ ids.map((id) => rpc.VideoDelete(id).pipe(Effect.exit)),
+ { concurrency: 10 }
+ );
- const successCount = results.filter(Exit.isSuccess).length;
+ const successCount = results.filter(Exit.isSuccess).length;
- const errorCount = ids.length - successCount;
+ const errorCount = ids.length - successCount;
- if (successCount > 0 && errorCount > 0) {
- return { success: successCount, error: errorCount };
- } else if (successCount > 0) {
- return { success: successCount };
- } else {
- return yield* Effect.fail(
- new Error(
- `Failed to delete ${errorCount} cap${errorCount === 1 ? "" : "s"}`,
- ),
- );
- }
- }),
- onMutate: (ids: Video.VideoId[]) => {
- toast.loading(
- `Deleting ${ids.length} cap${ids.length === 1 ? "" : "s"}...`,
- );
- },
- onSuccess: (data: { success: number; error?: number }) => {
- setSelectedCaps([]);
- router.refresh();
- if (data.error) {
- toast.success(
- `Successfully deleted ${data.success} cap${
- data.success === 1 ? "" : "s"
- }, but failed to delete ${data.error} cap${
- data.error === 1 ? "" : "s"
- }`,
- );
- } else {
- toast.success(
- `Successfully deleted ${data.success} cap${
- data.success === 1 ? "" : "s"
- }`,
- );
- }
- },
- onError: (error: unknown) => {
- const message =
- error instanceof Error
- ? error.message
- : "An error occurred while deleting caps";
- toast.error(message);
- },
- });
+ if (successCount > 0 && errorCount > 0) {
+ return { success: successCount, error: errorCount };
+ } else if (successCount > 0) {
+ return { success: successCount };
+ } else {
+ return yield* Effect.fail(
+ new Error(
+ `Failed to delete ${errorCount} cap${errorCount === 1 ? "" : "s"}`
+ )
+ );
+ }
+ }),
+ onMutate: (ids: Video.VideoId[]) => {
+ toast.loading(
+ `Deleting ${ids.length} cap${ids.length === 1 ? "" : "s"}...`
+ );
+ },
+ onSuccess: (data: { success: number; error?: number }) => {
+ setSelectedCaps([]);
+ router.refresh();
+ if (data.error) {
+ toast.success(
+ `Successfully deleted ${data.success} cap${
+ data.success === 1 ? "" : "s"
+ }, but failed to delete ${data.error} cap${
+ data.error === 1 ? "" : "s"
+ }`
+ );
+ } else {
+ toast.success(
+ `Successfully deleted ${data.success} cap${
+ data.success === 1 ? "" : "s"
+ }`
+ );
+ }
+ },
+ onError: (error: unknown) => {
+ const message =
+ error instanceof Error
+ ? error.message
+ : "An error occurred while deleting caps";
+ toast.error(message);
+ },
+ });
- const { mutate: deleteCap, isPending: isDeletingCap } = useEffectMutation({
- mutationFn: Effect.fn(function* (id: Video.VideoId) {
- yield* rpc.VideoDelete(id);
- }),
- onSuccess: () => {
- toast.success("Cap deleted successfully");
- router.refresh();
- },
- onError: (_error: unknown) => toast.error("Failed to delete cap"),
- });
+ const { mutate: deleteCap, isPending: isDeletingCap } = useEffectMutation({
+ mutationFn: Effect.fn(function* (id: Video.VideoId) {
+ yield* rpc.VideoDelete(id);
+ }),
+ onSuccess: () => {
+ toast.success("Cap deleted successfully");
+ router.refresh();
+ },
+ onError: (_error: unknown) => toast.error("Failed to delete cap"),
+ });
- useEffect(() => {
- const handleKeyDown = (e: KeyboardEvent) => {
- if (e.key === "Escape" && selectedCaps.length > 0) {
- setSelectedCaps([]);
- }
+ useEffect(() => {
+ const handleKeyDown = (e: KeyboardEvent) => {
+ if (e.key === "Escape" && selectedCaps.length > 0) {
+ setSelectedCaps([]);
+ }
- if (
- (e.key === "Delete" || e.key === "Backspace") &&
- selectedCaps.length > 0
- ) {
- if (e.key === "Backspace") {
- e.preventDefault();
- }
+ if (
+ (e.key === "Delete" || e.key === "Backspace") &&
+ selectedCaps.length > 0
+ ) {
+ if (e.key === "Backspace") {
+ e.preventDefault();
+ }
- if (
- !["INPUT", "TEXTAREA", "SELECT"].includes(
- document.activeElement?.tagName || "",
- )
- ) {
- deleteCaps(selectedCaps);
- }
- }
+ if (
+ !["INPUT", "TEXTAREA", "SELECT"].includes(
+ document.activeElement?.tagName || ""
+ )
+ ) {
+ deleteCaps(selectedCaps);
+ }
+ }
- if (e.key === "a" && (e.ctrlKey || e.metaKey) && data.length > 0) {
- if (
- !["INPUT", "TEXTAREA", "SELECT"].includes(
- document.activeElement?.tagName || "",
- )
- ) {
- e.preventDefault();
- setSelectedCaps(data.map((cap) => cap.id));
- }
- }
- };
+ if (e.key === "a" && (e.ctrlKey || e.metaKey) && data.length > 0) {
+ if (
+ !["INPUT", "TEXTAREA", "SELECT"].includes(
+ document.activeElement?.tagName || ""
+ )
+ ) {
+ e.preventDefault();
+ setSelectedCaps(data.map((cap) => cap.id));
+ }
+ }
+ };
- window.addEventListener("keydown", handleKeyDown);
+ window.addEventListener("keydown", handleKeyDown);
- return () => {
- window.removeEventListener("keydown", handleKeyDown);
- };
- }, [selectedCaps, data, deleteCaps]);
+ return () => {
+ window.removeEventListener("keydown", handleKeyDown);
+ };
+ }, [selectedCaps, data, deleteCaps]);
- useEffect(() => {
- const handleDragStart = () => setIsDraggingCap(true);
- const handleDragEnd = () => setIsDraggingCap(false);
+ useEffect(() => {
+ const handleDragStart = () => setIsDraggingCap(true);
+ const handleDragEnd = () => setIsDraggingCap(false);
- window.addEventListener("dragstart", handleDragStart);
- window.addEventListener("dragend", handleDragEnd);
+ window.addEventListener("dragstart", handleDragStart);
+ window.addEventListener("dragend", handleDragEnd);
- return () => {
- window.removeEventListener("dragstart", handleDragStart);
- window.removeEventListener("dragend", handleDragEnd);
- };
- }, []);
+ return () => {
+ window.removeEventListener("dragstart", handleDragStart);
+ window.removeEventListener("dragend", handleDragEnd);
+ };
+ }, []);
- const [isUploading, uploadingCapId] = useUploadingStatus();
- const visibleVideos = useMemo(
- () =>
- isUploading && uploadingCapId
- ? data.filter((video) => video.id !== uploadingCapId)
- : data,
- [data, isUploading, uploadingCapId],
- );
+ const [isUploading, uploadingCapId] = useUploadingStatus();
+ const visibleVideos = useMemo(
+ () =>
+ isUploading && uploadingCapId
+ ? data.filter((video) => video.id !== uploadingCapId)
+ : data,
+ [data, isUploading, uploadingCapId]
+ );
- if (count === 0 && folders.length === 0) return <EmptyCapState />;
+ if (count === 0 && folders.length === 0) return <EmptyCapState />;
- return (
- <div className="flex relative flex-col w-full h-full">
- <NewFolderDialog
- open={openNewFolderDialog}
- onOpenChange={setOpenNewFolderDialog}
- />
- <div className="flex gap-3 items-center mb-10 w-full">
- <Button
- onClick={() => setOpenNewFolderDialog(true)}
- size="sm"
- variant="dark"
- className="flex gap-2 items-center w-fit"
- >
- <FontAwesomeIcon className="size-3.5" icon={faFolderPlus} />
- New Folder
- </Button>
- <UploadCapButton size="sm" />
- <WebRecorderDialog />
- </div>
- {folders.length > 0 && (
- <>
- <div className="flex gap-3 items-center mb-6 w-full">
- <h1 className="text-2xl font-medium text-gray-12">Folders</h1>
- </div>
- <div className="grid grid-cols-[repeat(auto-fill,minmax(250px,1fr))] gap-4 mb-10">
- {folders.map((folder) => (
- <Folder key={folder.id} {...folder} />
- ))}
- </div>
- </>
- )}
- {visibleVideos.length > 0 && (
- <>
- <div className="flex justify-between items-center mb-6 w-full">
- <h1 className="text-2xl font-medium text-gray-12">Videos</h1>
- </div>
+ return (
+ <div className="flex relative flex-col w-full h-full">
+ <NewFolderDialog
+ open={openNewFolderDialog}
+ onOpenChange={setOpenNewFolderDialog}
+ />
+ <div className="flex gap-3 items-center mb-10 w-full">
+ <Button
+ onClick={() => setOpenNewFolderDialog(true)}
+ size="sm"
+ variant="dark"
+ className="flex gap-2 items-center w-fit"
+ >
+ <FontAwesomeIcon className="size-3.5" icon={faFolderPlus} />
+ New Folder
+ </Button>
+ <UploadCapButton size="sm" />
+ <WebRecorderDialog />
+ </div>
+ {folders.length > 0 && (
+ <>
+ <div className="flex gap-3 items-center mb-6 w-full">
+ <h1 className="text-2xl font-medium text-gray-12">Folders</h1>
+ </div>
+ <div className="grid grid-cols-[repeat(auto-fill,minmax(250px,1fr))] gap-4 mb-10">
+ {folders.map((folder) => (
+ <Folder key={folder.id} {...folder} />
+ ))}
+ </div>
+ </>
+ )}
+ {visibleVideos.length > 0 && (
+ <>
+ <div className="flex justify-between items-center mb-6 w-full">
+ <h1 className="text-2xl font-medium text-gray-12">Videos</h1>
+ </div>
- <div className="grid grid-cols-1 gap-4 sm:gap-6 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-5">
- {isUploading && (
- <UploadPlaceholderCard key={"upload-placeholder"} />
- )}
- {visibleVideos.map((video) => {
- const videoAnalytics = analytics[video.id];
- return (
- <CapCard
- key={video.id}
- cap={video}
- analytics={videoAnalytics ?? 0}
- onDelete={() => {
- if (selectedCaps.length > 0) {
- deleteCaps(selectedCaps);
- } else {
- deleteCap(video.id);
- }
- }}
- userId={user?.id}
- isLoadingAnalytics={isLoadingAnalytics}
- isSelected={selectedCaps.includes(video.id)}
- anyCapSelected={anyCapSelected}
- onSelectToggle={() => handleCapSelection(video.id)}
- />
- );
- })}
- </div>
- </>
- )}
- {(data.length > limit || data.length === limit || page !== 1) && (
- <div className="mt-7">
- <CapPagination currentPage={page} totalPages={totalPages} />
- </div>
- )}
- <SelectedCapsBar
- selectedCaps={selectedCaps}
- setSelectedCaps={setSelectedCaps}
- deleteSelectedCaps={() => deleteCaps(selectedCaps)}
- isDeleting={isDeletingCaps || isDeletingCap}
- />
- {isDraggingCap && (
- <div className="fixed inset-0 z-50 pointer-events-none">
- <div className="flex justify-center items-center w-full h-full">
- <div className="flex gap-2 items-center px-5 py-3 text-sm font-medium text-white rounded-xl bg-blue-12">
- <FontAwesomeIcon
- className="size-3.5 text-white opacity-50"
- icon={faInfoCircle}
- />
- <p className="text-white">
- Drag to a space to share or folder to move
- </p>
- </div>
- </div>
- </div>
- )}
- </div>
- );
+ <div className="grid grid-cols-1 gap-4 sm:gap-6 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-5">
+ {isUploading && (
+ <UploadPlaceholderCard key={"upload-placeholder"} />
+ )}
+ {visibleVideos.map((video) => {
+ const videoAnalytics = analytics[video.id];
+ return (
+ <CapCard
+ key={video.id}
+ cap={video}
+ analytics={videoAnalytics ?? 0}
+ onDelete={() => {
+ if (selectedCaps.length > 0) {
+ deleteCaps(selectedCaps);
+ } else {
+ deleteCap(video.id);
+ }
+ }}
+ userId={user?.id}
+ isLoadingAnalytics={isLoadingAnalytics}
+ isSelected={selectedCaps.includes(video.id)}
+ anyCapSelected={anyCapSelected}
+ onSelectToggle={() => handleCapSelection(video.id)}
+ />
+ );
+ })}
+ </div>
+ </>
+ )}
+ {(data.length > limit || data.length === limit || page !== 1) && (
+ <div className="mt-7">
+ <CapPagination currentPage={page} totalPages={totalPages} />
+ </div>
+ )}
+ <SelectedCapsBar
+ selectedCaps={selectedCaps}
+ setSelectedCaps={setSelectedCaps}
+ deleteSelectedCaps={() => deleteCaps(selectedCaps)}
+ isDeleting={isDeletingCaps || isDeletingCap}
+ />
+ {isDraggingCap && (
+ <div className="fixed inset-0 z-50 pointer-events-none">
+ <div className="flex justify-center items-center w-full h-full">
+ <div className="flex gap-2 items-center px-5 py-3 text-sm font-medium text-white rounded-xl bg-blue-12">
+ <FontAwesomeIcon
+ className="size-3.5 text-white opacity-50"
+ icon={faInfoCircle}
+ />
+ <p className="text-white">
+ Drag to a space to share or folder to move
+ </p>
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+ );
};
diff --git a/apps/web/app/s/[videoId]/page.tsx b/apps/web/app/s/[videoId]/page.tsx
index 12de03c20..7d1200fac 100644
--- a/apps/web/app/s/[videoId]/page.tsx
+++ b/apps/web/app/s/[videoId]/page.tsx
@@ -1,33 +1,32 @@
import { db } from "@cap/database";
import { getCurrentUser } from "@cap/database/auth/session";
import {
- comments,
- organizationMembers,
- organizations,
- sharedVideos,
- spaces,
- spaceVideos,
- users,
- videos,
- videoUploads,
+ comments,
+ organizationMembers,
+ organizations,
+ sharedVideos,
+ spaces,
+ spaceVideos,
+ users,
+ videos,
+ videoUploads,
} from "@cap/database/schema";
import type { VideoMetadata } from "@cap/database/types";
import { buildEnv } from "@cap/env";
import { Logo } from "@cap/ui";
import { userIsPro } from "@cap/utils";
import {
- Database,
- ImageUploads,
- provideOptionalAuth,
- Videos,
+ Database,
+ ImageUploads,
+ provideOptionalAuth,
+ Videos,
} from "@cap/web-backend";
import { VideosPolicy } from "@cap/web-backend/src/Videos/VideosPolicy";
import {
- Comment,
- type ImageUpload,
- type Organisation,
- Policy,
- type Video,
+ Comment,
+ type Organisation,
+ Policy,
+ type Video,
} from "@cap/web-domain";
import { and, eq, type InferSelectModel, isNull, sql } from "drizzle-orm";
import { Effect, Option } from "effect";
@@ -38,8 +37,8 @@ import { notFound } from "next/navigation";
import { generateAiMetadata } from "@/actions/videos/generate-ai-metadata";
import { getVideoAnalytics } from "@/actions/videos/get-analytics";
import {
- getDashboardData,
- type OrganizationSettings,
+ getDashboardData,
+ type OrganizationSettings,
} from "@/app/(org)/dashboard/dashboard-data";
import { createNotification } from "@/lib/Notification";
import * as EffectRuntime from "@/lib/server";
@@ -53,716 +52,720 @@ import { Share } from "./Share";
// Helper function to fetch shared spaces data for a video
async function getSharedSpacesForVideo(videoId: Video.VideoId) {
- // Fetch space-level sharing
- const spaceSharing = await db()
- .select({
- id: spaces.id,
- name: spaces.name,
- organizationId: spaces.organizationId,
- iconUrl: organizations.iconUrl,
- })
- .from(spaceVideos)
- .innerJoin(spaces, eq(spaceVideos.spaceId, spaces.id))
- .innerJoin(organizations, eq(spaces.organizationId, organizations.id))
- .where(eq(spaceVideos.videoId, videoId));
-
- // Fetch organization-level sharing
- const orgSharing = await db()
- .select({
- id: organizations.id,
- name: organizations.name,
- organizationId: organizations.id,
- iconUrl: organizations.iconUrl,
- })
- .from(sharedVideos)
- .innerJoin(organizations, eq(sharedVideos.organizationId, organizations.id))
- .where(eq(sharedVideos.videoId, videoId));
-
- const sharedSpaces: Array<{
- id: string;
- name: string;
- organizationId: string;
- iconUrl?: string;
- }> = [];
-
- // Add space-level sharing
- spaceSharing.forEach((space) => {
- sharedSpaces.push({
- id: space.id,
- name: space.name,
- organizationId: space.organizationId,
- iconUrl: space.iconUrl || undefined,
- });
- });
-
- // Add organization-level sharing
- orgSharing.forEach((org) => {
- sharedSpaces.push({
- id: org.id,
- name: org.name,
- organizationId: org.organizationId,
- iconUrl: org.iconUrl || undefined,
- });
- });
-
- return sharedSpaces;
+ // Fetch space-level sharing
+ const spaceSharing = await db()
+ .select({
+ id: spaces.id,
+ name: spaces.name,
+ organizationId: spaces.organizationId,
+ iconUrl: organizations.iconUrl,
+ })
+ .from(spaceVideos)
+ .innerJoin(spaces, eq(spaceVideos.spaceId, spaces.id))
+ .innerJoin(organizations, eq(spaces.organizationId, organizations.id))
+ .where(eq(spaceVideos.videoId, videoId));
+
+ // Fetch organization-level sharing
+ const orgSharing = await db()
+ .select({
+ id: organizations.id,
+ name: organizations.name,
+ organizationId: organizations.id,
+ iconUrl: organizations.iconUrl,
+ })
+ .from(sharedVideos)
+ .innerJoin(organizations, eq(sharedVideos.organizationId, organizations.id))
+ .where(eq(sharedVideos.videoId, videoId));
+
+ const sharedSpaces: Array<{
+ id: string;
+ name: string;
+ organizationId: string;
+ iconUrl?: string;
+ }> = [];
+
+ // Add space-level sharing
+ spaceSharing.forEach((space) => {
+ sharedSpaces.push({
+ id: space.id,
+ name: space.name,
+ organizationId: space.organizationId,
+ iconUrl: space.iconUrl || undefined,
+ });
+ });
+
+ // Add organization-level sharing
+ orgSharing.forEach((org) => {
+ sharedSpaces.push({
+ id: org.id,
+ name: org.name,
+ organizationId: org.organizationId,
+ iconUrl: org.iconUrl || undefined,
+ });
+ });
+
+ return sharedSpaces;
}
const ALLOWED_REFERRERS = [
- "x.com",
- "twitter.com",
- "facebook.com",
- "fb.com",
- "slack.com",
- "notion.so",
- "linkedin.com",
+ "x.com",
+ "twitter.com",
+ "facebook.com",
+ "fb.com",
+ "slack.com",
+ "notion.so",
+ "linkedin.com",
];
+function PolicyDeniedView() {
+ return (
+ <div className="flex flex-col justify-center items-center p-4 min-h-screen text-center">
+ <Logo className="size-32" />
+ <h1 className="mb-2 text-2xl font-semibold">This video is private</h1>
+ <p className="text-gray-400">
+ If you own this video, please <Link href="/login">sign in</Link> to
+ manage sharing.
+ </p>
+ </div>
+ );
+}
+
+const renderPolicyDenied = (videoId: Video.VideoId) =>
+ Effect.succeed(<PolicyDeniedView key={videoId} />);
+
+const renderNoSuchElement = () => Effect.sync(() => notFound());
+
+const getShareVideoPageCatchers = (videoId: Video.VideoId) => ({
+ PolicyDenied: () => renderPolicyDenied(videoId),
+ NoSuchElementException: renderNoSuchElement,
+});
+
export async function generateMetadata(
- props: PageProps<"/s/[videoId]">,
+ props: PageProps<"/s/[videoId]">
): Promise<Metadata> {
- const params = await props.params;
- const videoId = params.videoId as Video.VideoId;
-
- const referrer = (await headers()).get("x-referrer") || "";
- const isAllowedReferrer = ALLOWED_REFERRERS.some((domain) =>
- referrer.includes(domain),
- );
-
- return Effect.flatMap(Videos, (v) => v.getByIdForViewing(videoId)).pipe(
- Effect.map(
- Option.match({
- onNone: () => notFound(),
- onSome: ([video]) => ({
- title: video.name + " | Cap Recording",
- description: "Watch this video on Cap",
- openGraph: {
- images: [
- {
- url: new URL(
- `/api/video/og?videoId=${videoId}`,
- buildEnv.NEXT_PUBLIC_WEB_URL,
- ).toString(),
- width: 1200,
- height: 630,
- },
- ],
- videos: [
- {
- url: new URL(
- `/api/playlist?videoId=${video.id}`,
- buildEnv.NEXT_PUBLIC_WEB_URL,
- ).toString(),
- width: 1280,
- height: 720,
- type: "video/mp4",
- },
- ],
- },
- twitter: {
- card: "player",
- title: video.name + " | Cap Recording",
- description: "Watch this video on Cap",
- images: [
- new URL(
- `/api/video/og?videoId=${videoId}`,
- buildEnv.NEXT_PUBLIC_WEB_URL,
- ).toString(),
- ],
- players: {
- playerUrl: new URL(
- `/s/${videoId}`,
- buildEnv.NEXT_PUBLIC_WEB_URL,
- ).toString(),
- streamUrl: new URL(
- `/api/playlist?videoId=${video.id}`,
- buildEnv.NEXT_PUBLIC_WEB_URL,
- ).toString(),
- width: 1280,
- height: 720,
- },
- },
- robots: isAllowedReferrer ? "index, follow" : "noindex, nofollow",
- }),
- }),
- ),
- Effect.catchTags({
- PolicyDenied: () =>
- Effect.succeed({
- title: "Cap: This video is private",
- description: "This video is private and cannot be shared.",
- openGraph: {
- images: [
- {
- url: new URL(
- `/api/video/og?videoId=${videoId}`,
- buildEnv.NEXT_PUBLIC_WEB_URL,
- ).toString(),
- width: 1200,
- height: 630,
- },
- ],
- videos: [
- {
- url: new URL(
- `/api/playlist?videoId=${videoId}`,
- buildEnv.NEXT_PUBLIC_WEB_URL,
- ).toString(),
- width: 1280,
- height: 720,
- type: "video/mp4",
- },
- ],
- },
- robots: "noindex, nofollow",
- }),
- VerifyVideoPasswordError: () =>
- Effect.succeed({
- title: "Cap: Password Protected Video",
- description: "This video is password protected.",
- openGraph: {
- images: [
- {
- url: new URL(
- `/api/video/og?videoId=${videoId}`,
- buildEnv.NEXT_PUBLIC_WEB_URL,
- ).toString(),
- width: 1200,
- height: 630,
- },
- ],
- },
- twitter: {
- card: "summary_large_image",
- title: "Cap: Password Protected Video",
- description: "This video is password protected.",
- images: [
- new URL(
- `/api/video/og?videoId=${videoId}`,
- buildEnv.NEXT_PUBLIC_WEB_URL,
- ).toString(),
- ],
- },
- robots: "noindex, nofollow",
- }),
- }),
- provideOptionalAuth,
- EffectRuntime.runPromise,
- );
+ const params = await props.params;
+ const videoId = params.videoId as Video.VideoId;
+
+ const referrer = (await headers()).get("x-referrer") || "";
+ const isAllowedReferrer = ALLOWED_REFERRERS.some((domain) =>
+ referrer.includes(domain)
+ );
+
+ return Effect.flatMap(Videos, (v) => v.getByIdForViewing(videoId)).pipe(
+ Effect.map(
+ Option.match({
+ onNone: () => notFound(),
+ onSome: ([video]) => ({
+ title: `${video.name} | Cap Recording`,
+ description: "Watch this video on Cap",
+ openGraph: {
+ images: [
+ {
+ url: new URL(
+ `/api/video/og?videoId=${videoId}`,
+ buildEnv.NEXT_PUBLIC_WEB_URL
+ ).toString(),
+ width: 1200,
+ height: 630,
+ },
+ ],
+ videos: [
+ {
+ url: new URL(
+ `/api/playlist?videoId=${video.id}`,
+ buildEnv.NEXT_PUBLIC_WEB_URL
+ ).toString(),
+ width: 1280,
+ height: 720,
+ type: "video/mp4",
+ },
+ ],
+ },
+ twitter: {
+ card: "player",
+ title: `${video.name} | Cap Recording`,
+ description: "Watch this video on Cap",
+ images: [
+ new URL(
+ `/api/video/og?videoId=${videoId}`,
+ buildEnv.NEXT_PUBLIC_WEB_URL
+ ).toString(),
+ ],
+ players: {
+ playerUrl: new URL(
+ `/s/${videoId}`,
+ buildEnv.NEXT_PUBLIC_WEB_URL
+ ).toString(),
+ streamUrl: new URL(
+ `/api/playlist?videoId=${video.id}`,
+ buildEnv.NEXT_PUBLIC_WEB_URL
+ ).toString(),
+ width: 1280,
+ height: 720,
+ },
+ },
+ robots: isAllowedReferrer ? "index, follow" : "noindex, nofollow",
+ }),
+ })
+ ),
+ Effect.catchTags({
+ PolicyDenied: () =>
+ Effect.succeed({
+ title: "Cap: This video is private",
+ description: "This video is private and cannot be shared.",
+ openGraph: {
+ images: [
+ {
+ url: new URL(
+ `/api/video/og?videoId=${videoId}`,
+ buildEnv.NEXT_PUBLIC_WEB_URL
+ ).toString(),
+ width: 1200,
+ height: 630,
+ },
+ ],
+ videos: [
+ {
+ url: new URL(
+ `/api/playlist?videoId=${videoId}`,
+ buildEnv.NEXT_PUBLIC_WEB_URL
+ ).toString(),
+ width: 1280,
+ height: 720,
+ type: "video/mp4",
+ },
+ ],
+ },
+ robots: "noindex, nofollow",
+ }),
+ VerifyVideoPasswordError: () =>
+ Effect.succeed({
+ title: "Cap: Password Protected Video",
+ description: "This video is password protected.",
+ openGraph: {
+ images: [
+ {
+ url: new URL(
+ `/api/video/og?videoId=${videoId}`,
+ buildEnv.NEXT_PUBLIC_WEB_URL
+ ).toString(),
+ width: 1200,
+ height: 630,
+ },
+ ],
+ },
+ twitter: {
+ card: "summary_large_image",
+ title: "Cap: Password Protected Video",
+ description: "This video is password protected.",
+ images: [
+ new URL(
+ `/api/video/og?videoId=${videoId}`,
+ buildEnv.NEXT_PUBLIC_WEB_URL
+ ).toString(),
+ ],
+ },
+ robots: "noindex, nofollow",
+ }),
+ }),
+ provideOptionalAuth,
+ EffectRuntime.runPromise
+ );
}
export default async function ShareVideoPage(props: PageProps<"/s/[videoId]">) {
- const params = await props.params;
- const searchParams = await props.searchParams;
- const videoId = params.videoId as Video.VideoId;
-
- return Effect.gen(function* () {
- const videosPolicy = yield* VideosPolicy;
-
- const [video] = yield* Effect.promise(() =>
- db()
- .select({
- id: videos.id,
- name: videos.name,
- orgId: videos.orgId,
- createdAt: videos.createdAt,
- updatedAt: videos.updatedAt,
- effectiveCreatedAt: videos.effectiveCreatedAt,
- bucket: videos.bucket,
- metadata: videos.metadata,
- public: videos.public,
- videoStartTime: videos.videoStartTime,
- audioStartTime: videos.audioStartTime,
- awsRegion: videos.awsRegion,
- awsBucket: videos.awsBucket,
- xStreamInfo: videos.xStreamInfo,
- jobId: videos.jobId,
- jobStatus: videos.jobStatus,
- isScreenshot: videos.isScreenshot,
- skipProcessing: videos.skipProcessing,
- transcriptionStatus: videos.transcriptionStatus,
- source: videos.source,
- videoSettings: videos.settings,
- width: videos.width,
- height: videos.height,
- duration: videos.duration,
- fps: videos.fps,
- hasPassword: sql`${videos.password} IS NOT NULL`.mapWith(Boolean),
- sharedOrganization: {
- organizationId: sharedVideos.organizationId,
- },
- orgSettings: organizations.settings,
- hasActiveUpload: sql`${videoUploads.videoId} IS NOT NULL`.mapWith(
- Boolean,
- ),
- owner: users,
- })
- .from(videos)
- .leftJoin(sharedVideos, eq(videos.id, sharedVideos.videoId))
- .innerJoin(users, eq(videos.ownerId, users.id))
- .leftJoin(videoUploads, eq(videos.id, videoUploads.videoId))
- .leftJoin(organizations, eq(videos.orgId, organizations.id))
- .where(and(eq(videos.id, videoId), isNull(organizations.tombstoneAt))),
- ).pipe(Policy.withPublicPolicy(videosPolicy.canView(videoId)));
-
- return Option.fromNullable(video);
- }).pipe(
- Effect.flatten,
- Effect.map((video) => ({ needsPassword: false, video }) as const),
- Effect.catchTag("VerifyVideoPasswordError", () =>
- Effect.succeed({ needsPassword: true } as const),
- ),
- Effect.map((data) => (
- <div key={videoId} className="flex flex-col min-h-screen bg-gray-2">
- <PasswordOverlay isOpen={data.needsPassword} videoId={videoId} />
- {!data.needsPassword && (
- <AuthorizedContent video={data.video} searchParams={searchParams} />
- )}
- </div>
- )),
- Effect.catchTags({
- PolicyDenied: () =>
- Effect.succeed(
- <div
- key={videoId}
- className="flex flex-col justify-center items-center p-4 min-h-screen text-center"
- >
- <Logo className="size-32" />
- <h1 className="mb-2 text-2xl font-semibold">
- This video is private
- </h1>
- <p className="text-gray-400">
- If you own this video, please <Link href="/login">sign in</Link>{" "}
- to manage sharing.
- </p>
- </div>,
- ),
- NoSuchElementException: () => Effect.sync(() => notFound()),
- }),
- provideOptionalAuth,
- EffectRuntime.runPromise,
- );
+ const params = await props.params;
+ const searchParams = await props.searchParams;
+ const videoId = params.videoId as Video.VideoId;
+
+ return Effect.gen(function* () {
+ const videosPolicy = yield* VideosPolicy;
+
+ const [video] = yield* Effect.promise(() =>
+ db()
+ .select({
+ id: videos.id,
+ name: videos.name,
+ orgId: videos.orgId,
+ createdAt: videos.createdAt,
+ updatedAt: videos.updatedAt,
+ effectiveCreatedAt: videos.effectiveCreatedAt,
+ bucket: videos.bucket,
+ metadata: videos.metadata,
+ public: videos.public,
+ videoStartTime: videos.videoStartTime,
+ audioStartTime: videos.audioStartTime,
+ awsRegion: videos.awsRegion,
+ awsBucket: videos.awsBucket,
+ xStreamInfo: videos.xStreamInfo,
+ jobId: videos.jobId,
+ jobStatus: videos.jobStatus,
+ isScreenshot: videos.isScreenshot,
+ skipProcessing: videos.skipProcessing,
+ transcriptionStatus: videos.transcriptionStatus,
+ source: videos.source,
+ videoSettings: videos.settings,
+ width: videos.width,
+ height: videos.height,
+ duration: videos.duration,
+ fps: videos.fps,
+ hasPassword: sql`${videos.password} IS NOT NULL`.mapWith(Boolean),
+ sharedOrganization: {
+ organizationId: sharedVideos.organizationId,
+ },
+ orgSettings: organizations.settings,
+ hasActiveUpload: sql`${videoUploads.videoId} IS NOT NULL`.mapWith(
+ Boolean
+ ),
+ owner: users,
+ })
+ .from(videos)
+ .leftJoin(sharedVideos, eq(videos.id, sharedVideos.videoId))
+ .innerJoin(users, eq(videos.ownerId, users.id))
+ .leftJoin(videoUploads, eq(videos.id, videoUploads.videoId))
+ .leftJoin(organizations, eq(videos.orgId, organizations.id))
+ .where(and(eq(videos.id, videoId), isNull(organizations.tombstoneAt)))
+ ).pipe(Policy.withPublicPolicy(videosPolicy.canView(videoId)));
+
+ return Option.fromNullable(video);
+ }).pipe(
+ Effect.flatten,
+ Effect.map((video) => ({ needsPassword: false, video } as const)),
+ Effect.catchTag("VerifyVideoPasswordError", () =>
+ Effect.succeed({ needsPassword: true } as const)
+ ),
+ Effect.map((data) => (
+ <div key={videoId} className="flex flex-col min-h-screen bg-gray-2">
+ <PasswordOverlay isOpen={data.needsPassword} videoId={videoId} />
+ {!data.needsPassword && (
+ <AuthorizedContent video={data.video} searchParams={searchParams} />
+ )}
+ </div>
+ )),
+ Effect.catchTags(getShareVideoPageCatchers(videoId)),
+ provideOptionalAuth,
+ EffectRuntime.runPromise
+ );
}
async function AuthorizedContent({
- video,
- searchParams,
+ video,
+ searchParams,
}: {
- video: Omit<
- InferSelectModel<typeof videos>,
- "folderId" | "password" | "settings" | "ownerId"
- > & {
- owner: InferSelectModel<typeof users>;
- sharedOrganization: { organizationId: Organisation.OrganisationId } | null;
- hasPassword: boolean;
- orgSettings?: OrganizationSettings | null;
- videoSettings?: OrganizationSettings | null;
- };
- searchParams: { [key: string]: string | string[] | undefined };
+ video: Omit<
+ InferSelectModel<typeof videos>,
+ "folderId" | "password" | "settings" | "ownerId"
+ > & {
+ owner: InferSelectModel<typeof users>;
+ sharedOrganization: { organizationId: Organisation.OrganisationId } | null;
+ hasPassword: boolean;
+ orgSettings?: OrganizationSettings | null;
+ videoSettings?: OrganizationSettings | null;
+ };
+ searchParams: { [key: string]: string | string[] | undefined };
}) {
- // will have already been fetched if auth is required
- const user = await getCurrentUser();
- const videoId = video.id;
-
- if (user && video && user.id !== video.owner.id) {
- try {
- await createNotification({
- type: "view",
- videoId: video.id,
- authorId: user.id,
- });
- } catch (error) {
- console.warn("Failed to create view notification:", error);
- }
- }
-
- const userId = user?.id;
- const commentId = optionFromTOrFirst(searchParams.comment).pipe(
- Option.map(Comment.CommentId.make),
- );
- const replyId = optionFromTOrFirst(searchParams.reply).pipe(
- Option.map(Comment.CommentId.make),
- );
-
- // Fetch spaces data for the sharing dialog
- let spacesData = null;
- if (user) {
- try {
- const dashboardData = await getDashboardData(user);
- spacesData = dashboardData.spacesData;
- } catch (error) {
- console.error("Failed to fetch spaces data for sharing dialog:", error);
- spacesData = [];
- }
- }
-
- // Fetch shared spaces data for this video
- const sharedSpaces = await getSharedSpacesForVideo(videoId);
-
- let aiGenerationEnabled = false;
- const videoOwnerQuery = await db()
- .select({
- email: users.email,
- stripeSubscriptionStatus: users.stripeSubscriptionStatus,
- })
- .from(users)
- .where(eq(users.id, video.owner.id))
- .limit(1);
-
- if (videoOwnerQuery.length > 0 && videoOwnerQuery[0]) {
- const videoOwner = videoOwnerQuery[0];
- aiGenerationEnabled = await isAiGenerationEnabled(videoOwner);
- }
-
- if (video.sharedOrganization?.organizationId) {
- const organization = await db()
- .select()
- .from(organizations)
- .where(eq(organizations.id, video.sharedOrganization.organizationId))
- .limit(1);
-
- if (organization[0]?.allowedEmailDomain) {
- if (
- !user?.email ||
- !user.email.endsWith(`@${organization[0].allowedEmailDomain}`)
- ) {
- console.log(
- "[ShareVideoPage] Access denied - domain restriction:",
- organization[0].allowedEmailDomain,
- );
- return (
- <div className="flex flex-col justify-center items-center p-4 min-h-screen text-center">
- <h1 className="mb-4 text-2xl font-bold">Access Restricted</h1>
- <p className="mb-2 text-gray-10">
- This video is only accessible to members of this organization.
- </p>
- <p className="text-gray-600">
- Please sign in with your organization email address to access this
- content.
- </p>
- </div>
- );
- }
- }
- }
-
- if (
- video.transcriptionStatus !== "COMPLETE" &&
- video.transcriptionStatus !== "PROCESSING"
- ) {
- console.log("[ShareVideoPage] Starting transcription for video:", videoId);
- await transcribeVideo(videoId, video.owner.id, aiGenerationEnabled);
-
- const updatedVideoQuery = await db()
- .select({
- id: videos.id,
- name: videos.name,
- createdAt: videos.createdAt,
- updatedAt: videos.updatedAt,
- effectiveCreatedAt: videos.effectiveCreatedAt,
- bucket: videos.bucket,
- metadata: videos.metadata,
- public: videos.public,
- videoStartTime: videos.videoStartTime,
- audioStartTime: videos.audioStartTime,
- xStreamInfo: videos.xStreamInfo,
- jobId: videos.jobId,
- jobStatus: videos.jobStatus,
- isScreenshot: videos.isScreenshot,
- skipProcessing: videos.skipProcessing,
- transcriptionStatus: videos.transcriptionStatus,
- source: videos.source,
- sharedOrganization: {
- organizationId: sharedVideos.organizationId,
- },
- orgSettings: organizations.settings,
- videoSettings: videos.settings,
- })
- .from(videos)
- .leftJoin(sharedVideos, eq(videos.id, sharedVideos.videoId))
- .innerJoin(users, eq(videos.ownerId, users.id))
- .leftJoin(organizations, eq(videos.orgId, organizations.id))
- .where(eq(videos.id, videoId))
- .execute();
-
- if (updatedVideoQuery[0]) {
- Object.assign(video, updatedVideoQuery[0]);
- console.log(
- "[ShareVideoPage] Updated transcription status:",
- video.transcriptionStatus,
- );
- }
- }
-
- const currentMetadata = (video.metadata as VideoMetadata) || {};
- const metadata = currentMetadata;
- let initialAiData = null;
-
- if (metadata.summary || metadata.chapters || metadata.aiTitle) {
- initialAiData = {
- title: metadata.aiTitle || null,
- summary: metadata.summary || null,
- chapters: metadata.chapters || null,
- processing: metadata.aiProcessing || false,
- };
- } else if (metadata.aiProcessing) {
- initialAiData = {
- title: null,
- summary: null,
- chapters: null,
- processing: true,
- };
- }
-
- if (
- video.transcriptionStatus === "COMPLETE" &&
- !currentMetadata.aiProcessing &&
- !currentMetadata.summary &&
- !currentMetadata.chapters &&
- // !currentMetadata.generationError &&
- aiGenerationEnabled
- ) {
- try {
- generateAiMetadata(videoId, video.owner.id).catch((error) => {
- console.error(
- `[ShareVideoPage] Error generating AI metadata for video ${videoId}:`,
- error,
- );
- });
- } catch (error) {
- console.error(
- `[ShareVideoPage] Error starting AI metadata generation for video ${videoId}:`,
- error,
- );
- }
- }
-
- const customDomainPromise = (async () => {
- if (!user) {
- return { customDomain: null, domainVerified: false };
- }
- const activeOrganizationId = user.activeOrganizationId;
- if (!activeOrganizationId) {
- return { customDomain: null, domainVerified: false };
- }
-
- // Fetch the active org
- const orgArr = await db()
- .select({
- customDomain: organizations.customDomain,
- domainVerified: organizations.domainVerified,
- })
- .from(organizations)
- .where(eq(organizations.id, activeOrganizationId))
- .limit(1);
-
- const org = orgArr[0];
- if (
- org &&
- org.customDomain &&
- org.domainVerified !== null &&
- user.id === video.owner.id
- ) {
- return { customDomain: org.customDomain, domainVerified: true };
- }
- return { customDomain: null, domainVerified: false };
- })();
-
- const sharedOrganizationsPromise = db()
- .select({ id: sharedVideos.organizationId, name: organizations.name })
- .from(sharedVideos)
- .innerJoin(organizations, eq(sharedVideos.organizationId, organizations.id))
- .where(eq(sharedVideos.videoId, videoId));
-
- const userOrganizationsPromise = (async () => {
- if (!userId) return [];
-
- const [ownedOrganizations, memberOrganizations] = await Promise.all([
- db()
- .select({ id: organizations.id, name: organizations.name })
- .from(organizations)
- .where(eq(organizations.ownerId, userId)),
- db()
- .select({ id: organizations.id, name: organizations.name })
- .from(organizations)
- .innerJoin(
- organizationMembers,
- eq(organizations.id, organizationMembers.organizationId),
- )
- .where(eq(organizationMembers.userId, userId)),
- ]);
-
- const allOrganizations = [...ownedOrganizations, ...memberOrganizations];
- const uniqueOrganizationIds = new Set();
-
- return allOrganizations.filter((organization) => {
- if (uniqueOrganizationIds.has(organization.id)) return false;
- uniqueOrganizationIds.add(organization.id);
- return true;
- });
- })();
-
- const membersListPromise = video.sharedOrganization?.organizationId
- ? db()
- .select({ userId: organizationMembers.userId })
- .from(organizationMembers)
- .where(
- eq(
- organizationMembers.organizationId,
- video.sharedOrganization.organizationId,
- ),
- )
- : Promise.resolve([]);
-
- const commentsPromise = Effect.gen(function* () {
- const db = yield* Database;
- const imageUploads = yield* ImageUploads;
-
- let toplLevelCommentId = Option.none<Comment.CommentId>();
-
- if (Option.isSome(replyId)) {
- const [parentComment] = yield* db.use((db) =>
- db
- .select({ parentCommentId: comments.parentCommentId })
- .from(comments)
- .where(eq(comments.id, replyId.value))
- .limit(1),
- );
- toplLevelCommentId = Option.fromNullable(parentComment?.parentCommentId);
- }
-
- const commentToBringToTheTop = Option.orElse(
- toplLevelCommentId,
- () => commentId,
- );
-
- return yield* db
- .use((db) =>
- db
- .select({
- id: comments.id,
- content: comments.content,
- timestamp: comments.timestamp,
- type: comments.type,
- authorId: comments.authorId,
- videoId: comments.videoId,
- createdAt: comments.createdAt,
- updatedAt: comments.updatedAt,
- parentCommentId: comments.parentCommentId,
- authorName: users.name,
- authorImage: users.image,
- })
- .from(comments)
- .leftJoin(users, eq(comments.authorId, users.id))
- .where(eq(comments.videoId, videoId))
- .orderBy(
- Option.match(commentToBringToTheTop, {
- onSome: (commentId) =>
- sql`CASE WHEN ${comments.id} = ${commentId} THEN 0 ELSE 1 END, ${comments.createdAt}`,
- onNone: () => comments.createdAt,
- }),
- ),
- )
- .pipe(
- Effect.map((comments) =>
- comments.map(
- Effect.fn(function* (c) {
- return Object.assign(c, {
- authorImage: yield* Option.fromNullable(c.authorImage).pipe(
- Option.map(imageUploads.resolveImageUrl),
- Effect.transposeOption,
- Effect.map(Option.getOrNull),
- ),
- });
- }),
- ),
- ),
- Effect.flatMap(Effect.all),
- );
- }).pipe(EffectRuntime.runPromise);
-
- const viewsPromise = getVideoAnalytics(videoId).then((v) => v.count);
-
- const [
- membersList,
- userOrganizations,
- sharedOrganizations,
- { customDomain, domainVerified },
- ] = await Promise.all([
- membersListPromise,
- userOrganizationsPromise,
- sharedOrganizationsPromise,
- customDomainPromise,
- ]);
-
- const videoWithOrganizationInfo = await Effect.gen(function* () {
- const imageUploads = yield* ImageUploads;
-
- return {
- ...video,
- owner: {
- id: video.owner.id,
- name: video.owner.name,
- isPro: userIsPro(video.owner),
- image: video.owner.image
- ? yield* imageUploads.resolveImageUrl(video.owner.image)
- : null,
- },
- organization: {
- organizationMembers: membersList.map((member) => member.userId),
- organizationId: video.sharedOrganization?.organizationId ?? undefined,
- },
- sharedOrganizations: sharedOrganizations,
- password: null,
- folderId: null,
- orgSettings: video.orgSettings || null,
- settings: video.videoSettings || null,
- };
- }).pipe(runPromise);
-
- return (
- <>
- <div className="container flex-1 px-4 mx-auto">
- <ShareHeader
- data={{
- ...videoWithOrganizationInfo,
- createdAt: video.metadata?.customCreatedAt
- ? new Date(video.metadata.customCreatedAt)
- : video.createdAt,
- }}
- customDomain={customDomain}
- domainVerified={domainVerified}
- sharedOrganizations={
- videoWithOrganizationInfo.sharedOrganizations || []
- }
- sharedSpaces={sharedSpaces}
- userOrganizations={userOrganizations}
- spacesData={spacesData}
- />
-
- <Share
- data={videoWithOrganizationInfo}
- videoSettings={videoWithOrganizationInfo.settings}
- comments={commentsPromise}
- views={viewsPromise}
- customDomain={customDomain}
- domainVerified={domainVerified}
- userOrganizations={userOrganizations}
- viewerId={user?.id ?? null}
- initialAiData={initialAiData}
- aiGenerationEnabled={aiGenerationEnabled}
- />
- </div>
- <div className="py-4 mt-auto">
- <a
- target="_blank"
- href={`/?ref=video_${video.id}`}
- className="flex justify-center items-center px-4 py-2 mx-auto mb-2 space-x-2 bg-white rounded-full border border-gray-5 w-fit"
- >
- <span className="text-sm">Recorded with</span>
- <Logo className="w-14 h-auto" />
- </a>
- </div>
- </>
- );
+ // will have already been fetched if auth is required
+ const user = await getCurrentUser();
+ const videoId = video.id;
+
+ if (user && video && user.id !== video.owner.id) {
+ try {
+ await createNotification({
+ type: "view",
+ videoId: video.id,
+ authorId: user.id,
+ });
+ } catch (error) {
+ console.warn("Failed to create view notification:", error);
+ }
+ }
+
+ const userId = user?.id;
+ const commentId = optionFromTOrFirst(searchParams.comment).pipe(
+ Option.map(Comment.CommentId.make)
+ );
+ const replyId = optionFromTOrFirst(searchParams.reply).pipe(
+ Option.map(Comment.CommentId.make)
+ );
+
+ // Fetch spaces data for the sharing dialog
+ let spacesData = null;
+ if (user) {
+ try {
+ const dashboardData = await getDashboardData(user);
+ spacesData = dashboardData.spacesData;
+ } catch (error) {
+ console.error("Failed to fetch spaces data for sharing dialog:", error);
+ spacesData = [];
+ }
+ }
+
+ // Fetch shared spaces data for this video
+ const sharedSpaces = await getSharedSpacesForVideo(videoId);
+
+ let aiGenerationEnabled = false;
+ const videoOwnerQuery = await db()
+ .select({
+ email: users.email,
+ stripeSubscriptionStatus: users.stripeSubscriptionStatus,
+ })
+ .from(users)
+ .where(eq(users.id, video.owner.id))
+ .limit(1);
+
+ if (videoOwnerQuery.length > 0 && videoOwnerQuery[0]) {
+ const videoOwner = videoOwnerQuery[0];
+ aiGenerationEnabled = await isAiGenerationEnabled(videoOwner);
+ }
+
+ if (video.sharedOrganization?.organizationId) {
+ const organization = await db()
+ .select()
+ .from(organizations)
+ .where(eq(organizations.id, video.sharedOrganization.organizationId))
+ .limit(1);
+
+ if (organization[0]?.allowedEmailDomain) {
+ if (
+ !user?.email ||
+ !user.email.endsWith(`@${organization[0].allowedEmailDomain}`)
+ ) {
+ console.log(
+ "[ShareVideoPage] Access denied - domain restriction:",
+ organization[0].allowedEmailDomain
+ );
+ return (
+ <div className="flex flex-col justify-center items-center p-4 min-h-screen text-center">
+ <h1 className="mb-4 text-2xl font-bold">Access Restricted</h1>
+ <p className="mb-2 text-gray-10">
+ This video is only accessible to members of this organization.
+ </p>
+ <p className="text-gray-600">
+ Please sign in with your organization email address to access this
+ content.
+ </p>
+ </div>
+ );
+ }
+ }
+ }
+
+ if (
+ video.transcriptionStatus !== "COMPLETE" &&
+ video.transcriptionStatus !== "PROCESSING"
+ ) {
+ console.log("[ShareVideoPage] Starting transcription for video:", videoId);
+ await transcribeVideo(videoId, video.owner.id, aiGenerationEnabled);
+
+ const updatedVideoQuery = await db()
+ .select({
+ id: videos.id,
+ name: videos.name,
+ createdAt: videos.createdAt,
+ updatedAt: videos.updatedAt,
+ effectiveCreatedAt: videos.effectiveCreatedAt,
+ bucket: videos.bucket,
+ metadata: videos.metadata,
+ public: videos.public,
+ videoStartTime: videos.videoStartTime,
+ audioStartTime: videos.audioStartTime,
+ xStreamInfo: videos.xStreamInfo,
+ jobId: videos.jobId,
+ jobStatus: videos.jobStatus,
+ isScreenshot: videos.isScreenshot,
+ skipProcessing: videos.skipProcessing,
+ transcriptionStatus: videos.transcriptionStatus,
+ source: videos.source,
+ sharedOrganization: {
+ organizationId: sharedVideos.organizationId,
+ },
+ orgSettings: organizations.settings,
+ videoSettings: videos.settings,
+ })
+ .from(videos)
+ .leftJoin(sharedVideos, eq(videos.id, sharedVideos.videoId))
+ .innerJoin(users, eq(videos.ownerId, users.id))
+ .leftJoin(organizations, eq(videos.orgId, organizations.id))
+ .where(eq(videos.id, videoId))
+ .execute();
+
+ if (updatedVideoQuery[0]) {
+ Object.assign(video, updatedVideoQuery[0]);
+ console.log(
+ "[ShareVideoPage] Updated transcription status:",
+ video.transcriptionStatus
+ );
+ }
+ }
+
+ const currentMetadata = (video.metadata as VideoMetadata) || {};
+ const metadata = currentMetadata;
+ let initialAiData = null;
+
+ if (metadata.summary || metadata.chapters || metadata.aiTitle) {
+ initialAiData = {
+ title: metadata.aiTitle || null,
+ summary: metadata.summary || null,
+ chapters: metadata.chapters || null,
+ processing: metadata.aiProcessing || false,
+ };
+ } else if (metadata.aiProcessing) {
+ initialAiData = {
+ title: null,
+ summary: null,
+ chapters: null,
+ processing: true,
+ };
+ }
+
+ if (
+ video.transcriptionStatus === "COMPLETE" &&
+ !currentMetadata.aiProcessing &&
+ !currentMetadata.summary &&
+ !currentMetadata.chapters &&
+ // !currentMetadata.generationError &&
+ aiGenerationEnabled
+ ) {
+ try {
+ generateAiMetadata(videoId, video.owner.id).catch((error) => {
+ console.error(
+ `[ShareVideoPage] Error generating AI metadata for video ${videoId}:`,
+ error
+ );
+ });
+ } catch (error) {
+ console.error(
+ `[ShareVideoPage] Error starting AI metadata generation for video ${videoId}:`,
+ error
+ );
+ }
+ }
+
+ const customDomainPromise = (async () => {
+ if (!user) {
+ return { customDomain: null, domainVerified: false };
+ }
+ const activeOrganizationId = user.activeOrganizationId;
+ if (!activeOrganizationId) {
+ return { customDomain: null, domainVerified: false };
+ }
+
+ // Fetch the active org
+ const orgArr = await db()
+ .select({
+ customDomain: organizations.customDomain,
+ domainVerified: organizations.domainVerified,
+ })
+ .from(organizations)
+ .where(eq(organizations.id, activeOrganizationId))
+ .limit(1);
+
+ const org = orgArr[0];
+ if (
+ org?.customDomain &&
+ org.domainVerified !== null &&
+ user.id === video.owner.id
+ ) {
+ return { customDomain: org.customDomain, domainVerified: true };
+ }
+ return { customDomain: null, domainVerified: false };
+ })();
+
+ const sharedOrganizationsPromise = db()
+ .select({ id: sharedVideos.organizationId, name: organizations.name })
+ .from(sharedVideos)
+ .innerJoin(organizations, eq(sharedVideos.organizationId, organizations.id))
+ .where(eq(sharedVideos.videoId, videoId));
+
+ const userOrganizationsPromise = (async () => {
+ if (!userId) return [];
+
+ const [ownedOrganizations, memberOrganizations] = await Promise.all([
+ db()
+ .select({ id: organizations.id, name: organizations.name })
+ .from(organizations)
+ .where(eq(organizations.ownerId, userId)),
+ db()
+ .select({ id: organizations.id, name: organizations.name })
+ .from(organizations)
+ .innerJoin(
+ organizationMembers,
+ eq(organizations.id, organizationMembers.organizationId)
+ )
+ .where(eq(organizationMembers.userId, userId)),
+ ]);
+
+ const allOrganizations = [...ownedOrganizations, ...memberOrganizations];
+ const uniqueOrganizationIds = new Set();
+
+ return allOrganizations.filter((organization) => {
+ if (uniqueOrganizationIds.has(organization.id)) return false;
+ uniqueOrganizationIds.add(organization.id);
+ return true;
+ });
+ })();
+
+ const membersListPromise = video.sharedOrganization?.organizationId
+ ? db()
+ .select({ userId: organizationMembers.userId })
+ .from(organizationMembers)
+ .where(
+ eq(
+ organizationMembers.organizationId,
+ video.sharedOrganization.organizationId
+ )
+ )
+ : Promise.resolve([]);
+
+ const commentsPromise = Effect.gen(function* () {
+ const db = yield* Database;
+ const imageUploads = yield* ImageUploads;
+
+ let toplLevelCommentId = Option.none<Comment.CommentId>();
+
+ if (Option.isSome(replyId)) {
+ const [parentComment] = yield* db.use((db) =>
+ db
+ .select({ parentCommentId: comments.parentCommentId })
+ .from(comments)
+ .where(eq(comments.id, replyId.value))
+ .limit(1)
+ );
+ toplLevelCommentId = Option.fromNullable(parentComment?.parentCommentId);
+ }
+
+ const commentToBringToTheTop = Option.orElse(
+ toplLevelCommentId,
+ () => commentId
+ );
+
+ return yield* db
+ .use((db) =>
+ db
+ .select({
+ id: comments.id,
+ content: comments.content,
+ timestamp: comments.timestamp,
+ type: comments.type,
+ authorId: comments.authorId,
+ videoId: comments.videoId,
+ createdAt: comments.createdAt,
+ updatedAt: comments.updatedAt,
+ parentCommentId: comments.parentCommentId,
+ authorName: users.name,
+ authorImage: users.image,
+ })
+ .from(comments)
+ .leftJoin(users, eq(comments.authorId, users.id))
+ .where(eq(comments.videoId, videoId))
+ .orderBy(
+ Option.match(commentToBringToTheTop, {
+ onSome: (commentId) =>
+ sql`CASE WHEN ${comments.id} = ${commentId} THEN 0 ELSE 1 END, ${comments.createdAt}`,
+ onNone: () => comments.createdAt,
+ })
+ )
+ )
+ .pipe(
+ Effect.map((comments) =>
+ comments.map(
+ Effect.fn(function* (c) {
+ return Object.assign(c, {
+ authorImage: yield* Option.fromNullable(c.authorImage).pipe(
+ Option.map(imageUploads.resolveImageUrl),
+ Effect.transposeOption,
+ Effect.map(Option.getOrNull)
+ ),
+ });
+ })
+ )
+ ),
+ Effect.flatMap(Effect.all)
+ );
+ }).pipe(EffectRuntime.runPromise);
+
+ const viewsPromise = getVideoAnalytics(videoId).then((v) => v.count);
+
+ const [
+ membersList,
+ userOrganizations,
+ sharedOrganizations,
+ { customDomain, domainVerified },
+ ] = await Promise.all([
+ membersListPromise,
+ userOrganizationsPromise,
+ sharedOrganizationsPromise,
+ customDomainPromise,
+ ]);
+
+ const videoWithOrganizationInfo = await Effect.gen(function* () {
+ const imageUploads = yield* ImageUploads;
+
+ return {
+ ...video,
+ owner: {
+ id: video.owner.id,
+ name: video.owner.name,
+ isPro: userIsPro(video.owner),
+ image: video.owner.image
+ ? yield* imageUploads.resolveImageUrl(video.owner.image)
+ : null,
+ },
+ organization: {
+ organizationMembers: membersList.map((member) => member.userId),
+ organizationId: video.sharedOrganization?.organizationId ?? undefined,
+ },
+ sharedOrganizations: sharedOrganizations,
+ password: null,
+ folderId: null,
+ orgSettings: video.orgSettings || null,
+ settings: video.videoSettings || null,
+ };
+ }).pipe(runPromise);
+
+ return (
+ <>
+ <div className="container flex-1 px-4 mx-auto">
+ <ShareHeader
+ data={{
+ ...videoWithOrganizationInfo,
+ createdAt: video.metadata?.customCreatedAt
+ ? new Date(video.metadata.customCreatedAt)
+ : video.createdAt,
+ }}
+ customDomain={customDomain}
+ domainVerified={domainVerified}
+ sharedOrganizations={
+ videoWithOrganizationInfo.sharedOrganizations || []
+ }
+ sharedSpaces={sharedSpaces}
+ userOrganizations={userOrganizations}
+ spacesData={spacesData}
+ />
+
+ <Share
+ data={videoWithOrganizationInfo}
+ videoSettings={videoWithOrganizationInfo.settings}
+ comments={commentsPromise}
+ views={viewsPromise}
+ customDomain={customDomain}
+ domainVerified={domainVerified}
+ userOrganizations={userOrganizations}
+ viewerId={user?.id ?? null}
+ initialAiData={initialAiData}
+ aiGenerationEnabled={aiGenerationEnabled}
+ />
+ </div>
+ <div className="py-4 mt-auto">
+ <a
+ target="_blank"
+ href={`/?ref=video_${video.id}`}
+ className="flex justify-center items-center px-4 py-2 mx-auto mb-2 space-x-2 bg-white rounded-full border border-gray-5 w-fit"
+ >
+ <span className="text-sm">Recorded with</span>
+ <Logo className="w-14 h-auto" />
+ </a>
+ </div>
+ </>
+ );
}
diff --git a/packages/web-backend/src/Videos/VideosRpcs.ts b/packages/web-backend/src/Videos/VideosRpcs.ts
index 5bcf1ea1d..d762b9021 100644
--- a/packages/web-backend/src/Videos/VideosRpcs.ts
+++ b/packages/web-backend/src/Videos/VideosRpcs.ts
@@ -1,4 +1,4 @@
-import { InternalError, Video } from "@cap/web-domain";
+import { InternalError, Policy, Video } from "@cap/web-domain";
import { Effect, Exit, Schema, Unify } from "effect";
import { provideOptionalAuth } from "../Auth.ts";
@@ -110,7 +110,23 @@ export const VideosRpcsLive = Video.VideoRpcs.toLayer(
VideosGetAnalytics: (videoIds) =>
videos.getAnalyticsBulk(videoIds).pipe(
- Effect.map((results) => results.map((result) => Unify.unify(result))),
+ Effect.map((results) =>
+ results.map((result) =>
+ Exit.mapError(
+ Exit.map(result, (v) => ({ count: v.count } as const)),
+ (error) => {
+ if (Schema.is(Video.NotFoundError)(error)) return error;
+ if (Schema.is(Policy.PolicyDeniedError)(error)) return error;
+ if (Schema.is(Video.VerifyVideoPasswordError)(error))
+ return error;
+ return error as Video.NotFoundError | Policy.PolicyDeniedError | Video.VerifyVideoPasswordError;
+ },
+ ),
+ ) as readonly Exit.Exit<
+ { readonly count: number },
+ Video.NotFoundError | Policy.PolicyDeniedError | Video.VerifyVideoPasswordError
+ >[],
+ ),
provideOptionalAuth,
Effect.catchTag(
"DatabaseError",