Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: Add /embed/ page + change SharingDialog to support embed copy (#649)

Richie McIlroy3262030a9c25
diff --git a/apps/web/app/dashboard/caps/components/SharingDialog.tsx b/apps/web/app/dashboard/caps/components/SharingDialog.tsx
index d43d660ef..aea7b958e 100644
--- a/apps/web/app/dashboard/caps/components/SharingDialog.tsx
+++ b/apps/web/app/dashboard/caps/components/SharingDialog.tsx
@@ -10,7 +10,7 @@ import {
Input,
Avatar,
} from "@cap/ui";
-import { faShareNodes } from "@fortawesome/free-solid-svg-icons";
+import { faShareNodes, faCopy } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import clsx from "clsx";
import { motion } from "framer-motion";
@@ -49,6 +49,7 @@ export const SharingDialog: React.FC<SharingDialogProps> = ({
Set<string>
>(new Set());
const [loading, setLoading] = useState(false);
+ const [activeTab, setActiveTab] = useState<"share" | "embed">("share");
const sharedSpaceIds = new Set(sharedSpaces?.map((space) => space.id) || []);
@@ -58,6 +59,7 @@ export const SharingDialog: React.FC<SharingDialogProps> = ({
setSelectedSpaces(spaceIds);
setInitialSelectedSpaces(spaceIds);
setSearchTerm("");
+ setActiveTab("share");
}
}, [isOpen, sharedSpaces]);
@@ -133,6 +135,21 @@ export const SharingDialog: React.FC<SharingDialogProps> = ({
}
};
+ const handleCopyEmbedCode = async () => {
+ const embedCode = `<div style="position: relative; padding-bottom: 56.25%; height: 0;"><iframe src="${
+ process.env.NODE_ENV === "development"
+ ? "http://localhost:3000"
+ : "https://cap.so"
+ }/embed/${capId}" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;"></iframe></div>`;
+
+ try {
+ await navigator.clipboard.writeText(embedCode);
+ toast.success("Embed code copied to clipboard");
+ } catch (error) {
+ toast.error("Failed to copy embed code");
+ }
+ };
+
const filteredSpaces = searchTerm
? spacesData?.filter((space) =>
space.name.toLowerCase().includes(searchTerm.toLowerCase())
@@ -144,64 +161,131 @@ export const SharingDialog: React.FC<SharingDialogProps> = ({
<DialogContent className="p-0 w-full max-w-md rounded-xl border bg-gray-2 border-gray-4">
<DialogHeader
icon={<FontAwesomeIcon icon={faShareNodes} className="size-3.5" />}
- description="Select the spaces you would like to share with"
+ description={
+ activeTab === "share"
+ ? "Select the spaces you would like to share with"
+ : "Copy the embed code to share your cap"
+ }
>
<DialogTitle className="truncate w-full max-w-[320px]">
- Share {capName}
+ {activeTab === "share" ? `Share ${capName}` : `Embed ${capName}`}
</DialogTitle>
</DialogHeader>
- <div className="p-5">
- <div className="relative mb-3">
- <Input
- type="text"
- placeholder="Search..."
- value={searchTerm}
- className="pr-8"
- onChange={(e) => setSearchTerm(e.target.value)}
- />
- <Search
- className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-10"
- size={20}
- />
+
+ <div className="px-5">
+ <div className="flex border-b border-gray-4">
+ <button
+ className={clsx(
+ "flex-1 py-3 text-sm font-medium transition-colors",
+ activeTab === "share"
+ ? "text-gray-12 border-b-2 border-blue-500"
+ : "text-gray-11 hover:text-gray-12"
+ )}
+ onClick={() => setActiveTab("share")}
+ >
+ Share to space
+ </button>
+ <button
+ className={clsx(
+ "flex-1 py-3 text-sm font-medium transition-colors",
+ activeTab === "embed"
+ ? "text-gray-12 border-b-2 border-blue-500"
+ : "text-gray-11 hover:text-gray-12"
+ )}
+ onClick={() => setActiveTab("embed")}
+ >
+ Embed
+ </button>
</div>
- <div className="grid overflow-y-auto grid-cols-5 gap-3 pt-2 max-h-60">
- {filteredSpaces && filteredSpaces.length > 0 ? (
- filteredSpaces.map((space) => (
- <SpaceCard
- key={space.id}
- space={space}
- selectedSpaces={selectedSpaces}
- handleToggleSpace={handleToggleSpace}
- isSharedViaOrganization={isSpaceSharedViaOrganization(
- space.id
- )}
+ </div>
+
+ <div className="p-5">
+ {activeTab === "share" ? (
+ <>
+ <div className="relative mb-3">
+ <Input
+ type="text"
+ placeholder="Search..."
+ value={searchTerm}
+ className="pr-8"
+ onChange={(e) => setSearchTerm(e.target.value)}
+ />
+ <Search
+ className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-10"
+ size={20}
/>
- ))
- ) : (
- <div className="flex col-span-5 gap-2 justify-center items-center text-sm">
- <p className="text-gray-12">
- {spacesData && spacesData.length > 0
- ? "No spaces match your search"
- : "No spaces available"}
- </p>
</div>
- )}
- </div>
+ <div className="grid overflow-y-auto grid-cols-5 gap-3 pt-2 max-h-60">
+ {filteredSpaces && filteredSpaces.length > 0 ? (
+ filteredSpaces.map((space) => (
+ <SpaceCard
+ key={space.id}
+ space={space}
+ selectedSpaces={selectedSpaces}
+ handleToggleSpace={handleToggleSpace}
+ isSharedViaOrganization={isSpaceSharedViaOrganization(
+ space.id
+ )}
+ />
+ ))
+ ) : (
+ <div className="flex col-span-5 gap-2 justify-center items-center text-sm">
+ <p className="text-gray-12">
+ {spacesData && spacesData.length > 0
+ ? "No spaces match your search"
+ : "No spaces available"}
+ </p>
+ </div>
+ )}
+ </div>
+ </>
+ ) : (
+ <div className="space-y-4">
+ <div className="p-3 rounded-lg bg-gray-3 border border-gray-4">
+ <code className="text-xs text-gray-11 break-all font-mono">
+ {`<div style="position: relative; padding-bottom: 56.25%; height: 0;"><iframe src="${
+ process.env.NODE_ENV === "development"
+ ? "http://localhost:3000"
+ : "https://cap.so"
+ }/embed/${capId}" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;"></iframe></div>`}
+ </code>
+ </div>
+ <Button
+ className="w-full"
+ variant="dark"
+ onClick={handleCopyEmbedCode}
+ >
+ <FontAwesomeIcon icon={faCopy} className="size-3.5 mr-2" />
+ Copy embed code
+ </Button>
+ </div>
+ )}
</div>
- <DialogFooter className="p-5 border-t border-gray-4">
- <Button size="sm" variant="gray" onClick={onClose}>
- Cancel
- </Button>
- <Button
- spinner={loading}
- disabled={loading}
- size="sm"
- variant="dark"
- onClick={handleSave}
- >
- {loading ? "Saving..." : "Save"}
- </Button>
- </DialogFooter>
+
+ {activeTab === "share" && (
+ <DialogFooter className="p-5 border-t border-gray-4">
+ <Button size="sm" variant="gray" onClick={onClose}>
+ Cancel
+ </Button>
+ <Button
+ spinner={loading}
+ disabled={loading}
+ size="sm"
+ variant="dark"
+ onClick={handleSave}
+ >
+ {loading ? "Saving..." : "Save"}
+ </Button>
+ </DialogFooter>
+ )}
+
+ {activeTab === "embed" && (
+ <DialogFooter className="p-5 border-t border-gray-4">
+ <Button size="sm" variant="gray" onClick={onClose}>
+ Close
+ </Button>
+ </DialogFooter>
+ )}
</DialogContent>
</Dialog>
);
diff --git a/apps/web/app/embed/[videoId]/_components/EmbedVideo.tsx b/apps/web/app/embed/[videoId]/_components/EmbedVideo.tsx
new file mode 100644
index 000000000..c0497b830
--- /dev/null
+++ b/apps/web/app/embed/[videoId]/_components/EmbedVideo.tsx
@@ -0,0 +1,1201 @@
+"use client";
+
+import { UpgradeModal } from "@/components/UpgradeModal";
+import { usePublicEnv } from "@/utils/public-env";
+import { useTranscript } from "hooks/use-transcript";
+import { userSelectProps } from "@cap/database/auth/session";
+import { comments as commentsSchema, videos } from "@cap/database/schema";
+import { NODE_ENV } from "@cap/env";
+import { Avatar, Logo, LogoSpinner } from "@cap/ui";
+import { isUserOnProPlan } from "@cap/utils";
+import { AnimatePresence, motion } from "framer-motion";
+import {
+ Maximize,
+ MessageSquare,
+ Pause,
+ Play,
+ Volume2,
+ VolumeX,
+} from "lucide-react";
+import {
+ forwardRef,
+ useEffect,
+ useImperativeHandle,
+ useRef,
+ useState,
+} from "react";
+import { Tooltip } from "react-tooltip";
+import { toast } from "sonner";
+import { fromVtt, Subtitle } from "subtitles-parser-vtt";
+import { MP4VideoPlayer } from "../../../s/[videoId]/_components/MP4VideoPlayer";
+import { VideoPlayer } from "../../../s/[videoId]/_components/VideoPlayer";
+import { useQuery } from "@tanstack/react-query";
+
+declare global {
+ interface Window {
+ MSStream: any;
+ }
+}
+
+const formatTime = (time: number) => {
+ const minutes = Math.floor(time / 60);
+ const seconds = Math.floor(time % 60);
+ return `${minutes.toString().padStart(2, "0")}:${seconds
+ .toString()
+ .padStart(2, "0")}`;
+};
+
+const formatTimeWithMilliseconds = (time: number) => {
+ const minutes = Math.floor(time / 60);
+ const seconds = Math.floor(time % 60);
+ const milliseconds = Math.floor((time % 1) * 100);
+ return `${minutes.toString().padStart(2, "0")}:${seconds
+ .toString()
+ .padStart(2, "0")}.${milliseconds.toString().padStart(2, "0")}`;
+};
+
+type CommentWithAuthor = typeof commentsSchema.$inferSelect & {
+ authorName: string | null;
+};
+
+export const EmbedVideo = forwardRef<
+ HTMLVideoElement,
+ {
+ data: typeof videos.$inferSelect;
+ user: typeof userSelectProps | null;
+ comments: CommentWithAuthor[];
+ chapters?: { title: string; start: number }[];
+ aiProcessing?: boolean;
+ ownerName?: string | null;
+ }
+>(
+ (
+ { data, user, comments, chapters = [], aiProcessing = false, ownerName },
+ ref
+ ) => {
+ useImperativeHandle(ref, () => videoRef.current as HTMLVideoElement);
+
+ const videoRef = useRef<HTMLVideoElement>(null);
+ const previewCanvasRef = useRef<HTMLCanvasElement>(null);
+ const [isPlaying, setIsPlaying] = useState(false);
+ const [currentTime, setCurrentTime] = useState(0);
+ const [isLoading, setIsLoading] = useState(true);
+ const [longestDuration, setLongestDuration] = useState(0);
+ const [seeking, setSeeking] = useState(false);
+ const [videoMetadataLoaded, setVideoMetadataLoaded] = useState(false);
+ const [videoReadyToPlay, setVideoReadyToPlay] = useState(false);
+ const [overlayVisible, setOverlayVisible] = useState(true);
+ const [subtitlesVisible, setSubtitlesVisible] = useState(true);
+ const [upgradeModalOpen, setUpgradeModalOpen] = useState(false);
+ const [tempOverlayVisible, setTempOverlayVisible] = useState(false);
+ const [showTitleOverlay, setShowTitleOverlay] = useState(true);
+
+ const [showPreview, setShowPreview] = useState(false);
+ const [previewTime, setPreviewTime] = useState(0);
+ const [previewPosition, setPreviewPosition] = useState(0);
+ const [previewLoaded, setPreviewLoaded] = useState(false);
+ const [previewWidth, setPreviewWidth] = useState(200);
+ const [previewHeight, setPreviewHeight] = useState(112);
+ const [isMP4Source, setIsMP4Source] = useState(false);
+ const [thumbnailUrl, setThumbnailUrl] = useState<string | null>(null);
+
+ const [videoSpeed, setVideoSpeed] = useState(1);
+ const [isHoveringVideo, setIsHoveringVideo] = useState(false);
+ const [isHoveringControls, setIsHoveringControls] = useState(false);
+ const hideControlsTimeoutRef = useRef<NodeJS.Timeout | null>(null);
+ const [userMuted, setUserMuted] = useState(false);
+
+ const [scrubbingVideo, setScrubbingVideo] =
+ useState<HTMLVideoElement | null>(null);
+
+ const [isPreviewSeeking, setIsPreviewSeeking] = useState(false);
+ const lastUpdateTimeRef = useRef<number>(0);
+ const lastMousePosRef = useRef<number>(0);
+ const [isDragging, setIsDragging] = useState(false);
+ const timelineRef = useRef<HTMLDivElement>(null);
+
+ const isLargeScreen = useScreenSize();
+
+ const { data: videoSourceData } = useVideoSourceValidation(
+ data,
+ videoMetadataLoaded
+ );
+
+ useEffect(() => {
+ if (videoSourceData) {
+ setIsMP4Source(videoSourceData.isMP4Source);
+ } else if (videoMetadataLoaded) {
+ setIsMP4Source(data.source.type === "desktopMP4");
+ }
+ }, [videoSourceData, videoMetadataLoaded, data.source.type]);
+
+ useEffect(() => {
+ if (videoRef.current) {
+ if (typeof ref === "function") {
+ ref(videoRef.current);
+ } else if (ref) {
+ ref.current = videoRef.current;
+ }
+ }
+ }, [ref]);
+
+ const showControls = () => {
+ setOverlayVisible(true);
+ if (!isPlaying) {
+ setShowTitleOverlay(true);
+ }
+ if (hideControlsTimeoutRef.current) {
+ clearTimeout(hideControlsTimeoutRef.current);
+ hideControlsTimeoutRef.current = null;
+ }
+ };
+
+ const scheduleHideControls = () => {
+ if (hideControlsTimeoutRef.current) {
+ clearTimeout(hideControlsTimeoutRef.current);
+ }
+
+ if (isPlaying && !isHoveringControls) {
+ hideControlsTimeoutRef.current = setTimeout(() => {
+ setOverlayVisible(false);
+ setShowTitleOverlay(false);
+ }, 2000);
+ }
+ };
+
+ useEffect(() => {
+ const handleMouseMove = () => {
+ showControls();
+ scheduleHideControls();
+ };
+
+ const handleMouseEnter = () => {
+ setIsHoveringVideo(true);
+ showControls();
+ };
+
+ const handleMouseLeave = () => {
+ setIsHoveringVideo(false);
+ if (!isHoveringControls) {
+ scheduleHideControls();
+ }
+ };
+
+ const videoContainer = document.getElementById("embed-video-container");
+ if (videoContainer) {
+ videoContainer.addEventListener("mousemove", handleMouseMove);
+ videoContainer.addEventListener("mouseenter", handleMouseEnter);
+ videoContainer.addEventListener("mouseleave", handleMouseLeave);
+ }
+
+ return () => {
+ if (videoContainer) {
+ videoContainer.removeEventListener("mousemove", handleMouseMove);
+ videoContainer.removeEventListener("mouseenter", handleMouseEnter);
+ videoContainer.removeEventListener("mouseleave", handleMouseLeave);
+ }
+ if (hideControlsTimeoutRef.current) {
+ clearTimeout(hideControlsTimeoutRef.current);
+ }
+ };
+ }, [isPlaying, isHoveringControls]);
+
+ useEffect(() => {
+ if (isPlaying) {
+ setShowTitleOverlay(false);
+ scheduleHideControls();
+ } else {
+ showControls();
+ setShowTitleOverlay(true);
+ }
+ }, [isPlaying, isHoveringControls]);
+
+ useEffect(() => {
+ if (isHoveringControls) {
+ showControls();
+ if (!isPlaying) {
+ setShowTitleOverlay(true);
+ }
+ } else if (isPlaying && !isHoveringVideo) {
+ scheduleHideControls();
+ }
+ }, [isHoveringControls, isPlaying, isHoveringVideo]);
+
+ useEffect(() => {
+ const handleShortcuts = (e: KeyboardEvent) => {
+ const target = e.target as HTMLElement;
+ const isFormElement =
+ target.tagName === "INPUT" ||
+ target.tagName === "TEXTAREA" ||
+ target.tagName === "SELECT" ||
+ target.isContentEditable ||
+ target.getAttribute("role") === "textbox";
+
+ if (!isFormElement && videoRef.current) {
+ if (e.code === "Space") {
+ e.preventDefault();
+ if (isPlaying) {
+ videoRef.current.pause();
+ setIsPlaying(false);
+ } else {
+ videoRef.current.play();
+ setIsPlaying(true);
+ }
+ }
+ }
+ };
+
+ window.addEventListener("keydown", handleShortcuts);
+
+ return () => {
+ window.removeEventListener("keydown", handleShortcuts);
+ };
+ }, [isPlaying, videoRef]);
+
+ useEffect(() => {
+ const onVideoLoadedMetadata = () => {
+ if (videoRef.current) {
+ setLongestDuration(videoRef.current.duration);
+ setVideoMetadataLoaded(true);
+ }
+ };
+
+ const onCanPlay = () => {
+ setVideoMetadataLoaded(true);
+ setVideoReadyToPlay(true);
+
+ setTimeout(() => {
+ setIsLoading(false);
+ }, 100);
+ };
+
+ const videoElement = videoRef.current;
+ if (videoElement) {
+ videoElement.addEventListener("loadedmetadata", onVideoLoadedMetadata);
+ videoElement.addEventListener("canplay", onCanPlay);
+ }
+
+ return () => {
+ if (videoElement) {
+ videoElement.removeEventListener(
+ "loadedmetadata",
+ onVideoLoadedMetadata
+ );
+ videoElement.removeEventListener("canplay", onCanPlay);
+ }
+ };
+ }, []);
+
+ useEffect(() => {
+ const videoElement = videoRef.current;
+ if (!videoElement || !videoReadyToPlay) return;
+
+ const handleTimeUpdate = () => {
+ setCurrentTime(videoElement.currentTime);
+ };
+
+ videoElement.addEventListener("timeupdate", handleTimeUpdate);
+
+ return () => {
+ videoElement.removeEventListener("timeupdate", handleTimeUpdate);
+ };
+ }, [videoReadyToPlay]);
+
+ useEffect(() => {
+ setTempOverlayVisible(true);
+
+ const timer = setTimeout(() => {
+ setTempOverlayVisible(false);
+ }, 500);
+
+ return () => clearTimeout(timer);
+ }, [isPlaying]);
+
+ const publicEnv = usePublicEnv();
+
+ let videoSrc: string;
+ if (data.source.type === "desktopMP4") {
+ videoSrc = `/api/playlist?userId=${data.ownerId}&videoId=${data.id}&videoType=mp4`;
+ } else if (
+ NODE_ENV === "development" ||
+ ((data.skipProcessing === true || data.jobStatus !== "COMPLETE") &&
+ data.source.type === "MediaConvert")
+ ) {
+ videoSrc = `/api/playlist?userId=${data.ownerId}&videoId=${data.id}&videoType=master`;
+ } else if (data.source.type === "MediaConvert") {
+ videoSrc = `${publicEnv.s3BucketUrl}/${data.ownerId}/${data.id}/output/video_recording_000.m3u8`;
+ } else {
+ videoSrc = `${publicEnv.s3BucketUrl}/${data.ownerId}/${data.id}/combined-source/stream.m3u8`;
+ }
+
+ const handlePlayPauseClick = async () => {
+ const videoElement = videoRef.current;
+
+ if (!videoElement) return;
+
+ if (isPlaying) {
+ videoElement.pause();
+ setIsPlaying(false);
+ } else {
+ try {
+ if (!videoReadyToPlay) {
+ setIsPlaying(true);
+ } else {
+ if (!userMuted) {
+ videoElement.muted = false;
+ }
+
+ const currentPosition = videoElement.currentTime;
+
+ const playPromise = videoElement.play();
+
+ if (playPromise !== undefined) {
+ playPromise
+ .then(() => {
+ setIsPlaying(true);
+
+ if (videoElement.currentTime === 0 && currentPosition > 0) {
+ videoElement.currentTime = currentPosition;
+ }
+ })
+ .catch((error) => {
+ console.error("Error with playing:", error);
+
+ if (error.name === "NotAllowedError") {
+ videoElement.muted = true;
+ videoElement
+ .play()
+ .then(() => {
+ setIsPlaying(true);
+ if (!userMuted) {
+ setTimeout(() => {
+ videoElement.muted = false;
+ }, 100);
+ }
+
+ if (
+ videoElement.currentTime === 0 &&
+ currentPosition > 0
+ ) {
+ videoElement.currentTime = currentPosition;
+ }
+ })
+ .catch((innerError) => {
+ console.error(
+ "Still can't play even with muted:",
+ innerError
+ );
+ });
+ }
+ });
+ } else {
+ setIsPlaying(true);
+
+ if (videoElement.currentTime === 0 && currentPosition > 0) {
+ videoElement.currentTime = currentPosition;
+ }
+ }
+ }
+ } catch (error) {
+ console.error("Error with playing:", error);
+ }
+ }
+ };
+
+ const handleMuteClick = () => {
+ if (videoRef.current) {
+ const newMutedState = !videoRef.current.muted;
+ videoRef.current.muted = newMutedState;
+ setUserMuted(newMutedState);
+ }
+ };
+
+ const handleFullscreenClick = () => {
+ const player = document.getElementById("embed-video-container");
+ const video = videoRef.current;
+
+ if (!video) return;
+
+ const isIOS =
+ /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
+ const isAndroid = /Android/.test(navigator.userAgent);
+
+ if (isIOS || isAndroid) {
+ if (video.requestFullscreen) {
+ video
+ .requestFullscreen()
+ .catch((err) =>
+ console.error(
+ `Error attempting to enable full-screen mode on mobile: ${err.message} (${err.name})`
+ )
+ );
+ } else if ("webkitEnterFullscreen" in video) {
+ (video as any).webkitEnterFullscreen();
+ } else if ("mozRequestFullScreen" in video) {
+ (video as any).mozRequestFullScreen();
+ } else if ("msRequestFullscreen" in video) {
+ (video as any).msRequestFullscreen();
+ }
+ } else {
+ if (!document.fullscreenElement) {
+ if (player && player.requestFullscreen) {
+ player
+ .requestFullscreen()
+ .catch((err) =>
+ console.error(
+ `Error attempting to enable full-screen mode: ${err.message} (${err.name})`
+ )
+ );
+ } else if (player && "webkitRequestFullscreen" in player) {
+ (player as any).webkitRequestFullscreen();
+ } else if (player && "mozRequestFullScreen" in player) {
+ (player as any).mozRequestFullScreen();
+ } else if (player && "msRequestFullscreen" in player) {
+ (player as any).msRequestFullscreen();
+ }
+ } else {
+ if (document.exitFullscreen) {
+ document.exitFullscreen();
+ } else if ("webkitExitFullscreen" in document) {
+ (document as any).webkitExitFullscreen();
+ } else if ("mozCancelFullScreen" in document) {
+ (document as any).mozCancelFullScreen();
+ } else if ("msExitFullscreen" in document) {
+ (document as any).msExitFullscreen();
+ }
+ }
+ }
+ };
+
+ const handleSpeedChange = () => {
+ let newSpeed;
+ if (videoSpeed === 1) {
+ newSpeed = 1.5;
+ } else if (videoSpeed === 1.5) {
+ newSpeed = 2;
+ } else {
+ newSpeed = 1;
+ }
+ setVideoSpeed(newSpeed);
+ if (videoRef.current) {
+ videoRef.current.playbackRate = newSpeed;
+ }
+ };
+
+ const handleSeek = (e: React.MouseEvent<HTMLDivElement>) => {
+ if (!timelineRef.current || !videoRef.current || longestDuration === 0)
+ return;
+
+ const rect = timelineRef.current.getBoundingClientRect();
+ const clickX = e.clientX - rect.left;
+ const percentage = Math.max(0, Math.min(1, clickX / rect.width));
+ const seekTime = percentage * longestDuration;
+
+ videoRef.current.currentTime = seekTime;
+ setCurrentTime(seekTime);
+ };
+
+ const handleMouseDown = (e: React.MouseEvent<HTMLDivElement>) => {
+ e.preventDefault();
+ setIsDragging(true);
+ handleSeek(e);
+ };
+
+ const handleMouseMove = (e: React.MouseEvent<HTMLDivElement>) => {
+ if (isDragging) {
+ handleSeek(e);
+ }
+ };
+
+ const handleMouseUp = () => {
+ setIsDragging(false);
+ };
+
+ useEffect(() => {
+ if (isDragging) {
+ const handleGlobalMouseUp = () => setIsDragging(false);
+ document.addEventListener("mouseup", handleGlobalMouseUp);
+ return () =>
+ document.removeEventListener("mouseup", handleGlobalMouseUp);
+ }
+ }, [isDragging]);
+
+ const handleChapterSeek = (chapterStart: number) => {
+ if (!videoRef.current) return;
+ videoRef.current.currentTime = chapterStart;
+ setCurrentTime(chapterStart);
+ };
+
+ const watchedPercentage =
+ longestDuration > 0 ? (currentTime / longestDuration) * 100 : 0;
+
+ const { data: transcriptContent, error: transcriptError } = useTranscript(
+ data.id,
+ data.transcriptionStatus
+ );
+
+ const { isTranscriptionProcessing, subtitles } = useTranscriptionProcessing(
+ data,
+ transcriptContent,
+ transcriptError
+ );
+
+ const parseSubTime = (timeString: number) => {
+ const timeStr = timeString.toString();
+ const timeParts = timeStr.split(":");
+
+ const hoursValue = timeParts.length > 2 ? Number(timeParts[0]) || 0 : 0;
+ const minutesValue =
+ timeParts.length > 1 ? Number(timeParts[timeParts.length - 2]) || 0 : 0;
+ const secondsValue = Number(timeParts[timeParts.length - 1]) || 0;
+
+ return hoursValue * 3600 + minutesValue * 60 + secondsValue;
+ };
+
+ const currentSubtitle = subtitles.find(
+ (subtitle) =>
+ parseSubTime(subtitle.startTime) <= currentTime &&
+ parseSubTime(subtitle.endTime) >= currentTime
+ );
+
+ if (data.jobStatus === "ERROR") {
+ return (
+ <div className="flex overflow-hidden justify-center items-center w-full h-screen bg-black">
+ <p className="text-xl text-white">
+ There was an error when processing the video. Please contact
+ support.
+ </p>
+ </div>
+ );
+ }
+
+ return (
+ <div
+ id="embed-video-container"
+ className="relative w-screen h-screen bg-black overflow-hidden group"
+ >
+ <div
+ className={`absolute inset-0 flex items-center justify-center z-10 bg-black transition-opacity duration-300 ${
+ isLoading ? "opacity-100" : "opacity-0 pointer-events-none"
+ }`}
+ >
+ <LogoSpinner className="w-8 h-auto animate-spin sm:w-10" />
+ </div>
+ <div className="relative w-full h-full">
+ <div className="absolute inset-0 bg-black">
+ {data.source.type === "desktopMP4" ? (
+ <MP4VideoPlayer ref={videoRef} videoSrc={videoSrc} />
+ ) : (
+ <VideoPlayer ref={videoRef} videoSrc={videoSrc} />
+ )}
+ </div>
+ {!isLoading && (
+ <div
+ className={`absolute inset-0 z-20 flex flex-col items-center justify-center transition-opacity duration-300 ${
+ (overlayVisible && isPlaying) ||
+ tempOverlayVisible ||
+ !isPlaying
+ ? "opacity-100"
+ : "opacity-0"
+ }`}
+ >
+ <button
+ aria-label={isPlaying ? "Pause video" : "Play video"}
+ className="flex justify-center items-center w-full h-full"
+ onClick={() => {
+ if (!videoReadyToPlay) {
+ setIsPlaying(true);
+ } else {
+ handlePlayPauseClick();
+ }
+ }}
+ >
+ <div className="flex flex-col items-center gap-4">
+ <AnimatePresence initial={false} mode="popLayout">
+ {isPlaying ? (
+ <motion.div
+ key="pause-button"
+ className="flex relative z-30 justify-center items-center size-20 bg-black bg-opacity-60 rounded-full"
+ initial={{ opacity: 0, scale: 0 }}
+ animate={{
+ scale: 1,
+ opacity: overlayVisible || tempOverlayVisible ? 1 : 0,
+ }}
+ style={{ transformOrigin: "center center" }}
+ transition={{ duration: 0.4, ease: "easeOut" }}
+ >
+ <Pause className="w-auto h-8 text-white sm:h-10 md:h-12" />
+ </motion.div>
+ ) : (
+ <motion.div
+ key="play-button"
+ className="flex relative z-30 justify-center items-center size-20 bg-black bg-opacity-60 rounded-full"
+ initial={{ opacity: 0, scale: 0 }}
+ animate={{
+ scale: 1,
+ opacity: 1,
+ }}
+ style={{ transformOrigin: "center center" }}
+ transition={{ duration: 0.4, ease: "easeOut" }}
+ >
+ <Play className="w-auto h-8 text-white sm:h-10 md:h-12 ml-0.5" />
+ </motion.div>
+ )}
+ </AnimatePresence>
+
+ {!isPlaying && (
+ <motion.button
+ initial={{ opacity: 0, y: 10 }}
+ animate={{ opacity: 1, y: 0 }}
+ exit={{ opacity: 0, y: 10 }}
+ transition={{ duration: 0.3, delay: 0.1 }}
+ onClick={(e) => {
+ e.stopPropagation();
+ window.open("https://cap.so", "_blank");
+ }}
+ className="flex items-center gap-2 text-white/80 hover:text-white transition-colors duration-200 text-sm bg-black/50 px-3 py-2 rounded-full backdrop-blur-sm"
+ aria-label="Powered by Cap"
+ >
+ <span className="text-sm text-white/80">Powered by</span>
+ <Logo className="w-auto h-4" white={true} />
+ </motion.button>
+ )}
+ </div>
+ </button>
+ </div>
+ )}
+
+ <AnimatePresence>
+ {!isLoading && showTitleOverlay && (
+ <motion.div
+ initial={{ opacity: 0, y: -20 }}
+ animate={{ opacity: 1, y: 0 }}
+ exit={{ opacity: 0, y: -20 }}
+ transition={{ duration: 0.3 }}
+ className="absolute top-4 left-4 sm:top-6 sm:left-6 z-30 max-w-[calc(100%-2rem)] sm:max-w-2xl"
+ >
+ <div className="bg-gradient-to-r from-black/70 to-black/50 backdrop-blur-md rounded-xl px-3 py-3 sm:px-4 sm:py-3 border border-white/10 shadow-2xl">
+ <div className="flex items-center gap-3">
+ {ownerName && (
+ <Avatar
+ name={ownerName}
+ className="size-8 sm:size-10 flex-shrink-0"
+ letterClass="text-sm sm:text-base font-medium"
+ />
+ )}
+ <div className="min-w-0 flex-1">
+ <h1 className="text-white text-lg sm:text-xl md:text-2xl font-semibold leading-tight truncate">
+ {data.name}
+ </h1>
+ <div className="flex items-center gap-2 mt-1">
+ {ownerName && (
+ <p className="text-gray-300 text-xs sm:text-sm font-medium truncate">
+ {ownerName}
+ </p>
+ )}
+ {ownerName && longestDuration > 0 && (
+ <span className="text-gray-400 text-xs">•</span>
+ )}
+ {longestDuration > 0 && (
+ <p className="text-gray-300 text-xs sm:text-sm">
+ {formatTime(longestDuration)}
+ </p>
+ )}
+ </div>
+ </div>
+ </div>
+ </div>
+ </motion.div>
+ )}
+ </AnimatePresence>
+
+ {currentSubtitle && currentSubtitle.text && subtitlesVisible && (
+ <div
+ className={`absolute z-10 p-2 w-full text-center transition-all duration-300 ease-in-out ${
+ overlayVisible
+ ? "bottom-20 sm:bottom-24"
+ : "bottom-6 sm:bottom-8"
+ }`}
+ >
+ <div className="inline px-2 py-1 text-sm text-white bg-black bg-opacity-75 rounded-xl sm:text-lg md:text-2xl">
+ {currentSubtitle.text
+ .replace("- ", "")
+ .replace(".", "")
+ .replace(",", "")}
+ </div>
+ </div>
+ )}
+
+ <AnimatePresence>
+ {isPlaying && !showTitleOverlay && (
+ <motion.div
+ initial={{ opacity: 0 }}
+ animate={{ opacity: 1 }}
+ exit={{ opacity: 0 }}
+ transition={{ duration: 0.3 }}
+ className="absolute top-4 left-4 sm:top-6 sm:left-6 z-30"
+ >
+ <button
+ onClick={() => window.open("https://cap.so", "_blank")}
+ className="opacity-30 hover:opacity-100 transition-opacity duration-200 cursor-pointer"
+ aria-label="Powered by Cap"
+ >
+ <Logo className="w-auto h-6 sm:h-8" white={true} />
+ </button>
+ </motion.div>
+ )}
+ </AnimatePresence>
+ </div>
+
+ <div
+ className={`absolute left-0 right-0 z-30 transition-all duration-300 ease-in-out ${
+ overlayVisible ? "bottom-[60px]" : "bottom-0"
+ }`}
+ >
+ <div
+ ref={timelineRef}
+ className="h-6 cursor-pointer px-4"
+ onMouseDown={handleMouseDown}
+ onMouseMove={handleMouseMove}
+ onMouseUp={handleMouseUp}
+ >
+ {!isLoading && comments && comments.length > 0 && (
+ <div className="-mt-6 w-full md:-mt-6">
+ {comments.map((comment) => {
+ const commentPosition =
+ comment.timestamp === null
+ ? 0
+ : (comment.timestamp / longestDuration) * 100;
+
+ let tooltipContent = "";
+ if (comment.type === "text") {
+ tooltipContent =
+ comment.authorId === "anonymous"
+ ? `Anonymous: ${comment.content}`
+ : `${comment.authorName || "User"}: ${comment.content}`;
+ } else {
+ tooltipContent =
+ comment.authorId === "anonymous"
+ ? "Anonymous"
+ : comment.authorName || "User";
+ }
+
+ return (
+ <div
+ key={comment.id}
+ className="absolute z-10 text-sm transition-all hover:scale-125 -mt-5 md:-mt-5"
+ style={{
+ left: `${commentPosition}%`,
+ }}
+ data-tooltip-id={comment.id}
+ data-tooltip-content={tooltipContent}
+ >
+ <span>
+ {comment.type === "text" ? (
+ <MessageSquare
+ fill="#646464"
+ className="w-auto h-[18px] sm:h-[22px] text-white"
+ />
+ ) : (
+ comment.content
+ )}
+ </span>
+ <Tooltip id={comment.id} />
+ </div>
+ );
+ })}
+ </div>
+ )}
+
+ <div className="relative w-full h-full">
+ {chapters.length > 0 && longestDuration > 0 ? (
+ <div className="absolute top-2.5 w-full h-1 sm:h-1.5 z-10 flex">
+ {chapters.map((chapter, index) => {
+ const nextChapter = chapters[index + 1];
+ const chapterStart = chapter.start;
+ const chapterEnd = nextChapter
+ ? nextChapter.start
+ : longestDuration;
+ const chapterDuration = chapterEnd - chapterStart;
+ const chapterWidth =
+ (chapterDuration / longestDuration) * 100;
+
+ const chapterProgress = Math.max(
+ 0,
+ Math.min(
+ (currentTime - chapterStart) / chapterDuration,
+ 1
+ )
+ );
+
+ const isCurrentChapter =
+ currentTime >= chapterStart && currentTime < chapterEnd;
+
+ return (
+ <div
+ key={chapter.start}
+ className="relative h-full cursor-pointer group"
+ style={{ width: `${chapterWidth}%` }}
+ onClick={(e) => {
+ e.stopPropagation();
+ handleChapterSeek(chapterStart);
+ }}
+ >
+ <div
+ className="w-full h-full bg-gray-400 bg-opacity-50 group-hover:bg-opacity-70 transition-colors"
+ style={{
+ boxShadow: "0 0 20px rgba(0,0,0,0.6)",
+ borderRight:
+ index < chapters.length - 1
+ ? "1px solid rgba(255,255,255,0.3)"
+ : "none",
+ }}
+ />
+ {isCurrentChapter && (
+ <div
+ className="absolute top-0 left-0 h-full bg-white transition-all duration-100"
+ style={{ width: `${chapterProgress * 100}%` }}
+ />
+ )}
+ {currentTime > chapterEnd && (
+ <div className="absolute top-0 left-0 w-full h-full bg-white" />
+ )}
+ </div>
+ );
+ })}
+ </div>
+ ) : (
+ <>
+ <div
+ style={{ boxShadow: "0 0 20px rgba(0,0,0,0.6)" }}
+ className="absolute top-2.5 w-full h-1 sm:h-1.5 bg-gray-400 bg-opacity-50 z-10 cursor-pointer"
+ onClick={handleSeek}
+ />
+ <div
+ className="absolute top-2.5 h-1 sm:h-1.5 bg-white cursor-pointer z-10 pointer-events-none"
+ style={{ width: `${watchedPercentage}%` }}
+ />
+ </>
+ )}
+
+ <div
+ style={{
+ boxShadow: "0 0 20px rgba(0,0,0,0.1)",
+ left: `${watchedPercentage}%`,
+ }}
+ className="absolute top-2 z-20 -mt-1.5 -ml-2 w-5 h-5 bg-white rounded-full cursor-pointer focus:outline-none border-2 border-gray-5"
+ tabIndex={0}
+ />
+ </div>
+ </div>
+ </div>
+
+ <div
+ className={`absolute bottom-0 left-0 right-0 bg-black bg-opacity-60 z-20 transition-transform duration-300 ease-in-out ${
+ overlayVisible ? "translate-y-0" : "translate-y-full"
+ }`}
+ onMouseEnter={() => {
+ setIsHoveringControls(true);
+ }}
+ onMouseLeave={() => {
+ setIsHoveringControls(false);
+ }}
+ >
+ <div className="flex justify-between items-center px-4 py-3">
+ <div className="flex items-center space-x-3">
+ <button
+ aria-label="Play video"
+ className="inline-flex justify-center items-center px-2 py-2 text-sm font-medium text-gray-100 rounded-lg border border-transparent transition duration-150 ease-in-out focus:outline-none hover:text-white focus:border-white hover:bg-gray-100 hover:bg-opacity-10 active:bg-gray-100 active:bg-opacity-10"
+ tabIndex={0}
+ type="button"
+ onClick={() => handlePlayPauseClick()}
+ >
+ {isPlaying ? (
+ <Pause className="w-auto h-5 sm:h-6" />
+ ) : (
+ <Play className="w-auto h-5 sm:h-6" />
+ )}
+ </button>
+ <div className="text-sm text-white font-medium select-none tabular">
+ {formatTime(currentTime)} / {formatTime(longestDuration)}
+ </div>
+ </div>
+
+ <div className="flex justify-end space-x-2">
+ <button
+ aria-label={`Change video speed to ${videoSpeed}x`}
+ className="inline-flex min-w-[45px] items-center text-sm font-medium transition ease-in-out duration-150 focus:outline-none border text-gray-100 border-transparent hover:text-white focus:border-white hover:bg-gray-100 hover:bg-opacity-10 active:bg-gray-100 active:bg-opacity-10 px-2 py-2 justify-center rounded-lg"
+ tabIndex={0}
+ type="button"
+ onClick={handleSpeedChange}
+ >
+ {videoSpeed}x
+ </button>
+
+ {isTranscriptionProcessing && subtitles.length === 0 && (
+ <button
+ aria-label="Transcription is processing"
+ className="inline-flex justify-center items-center px-2 py-2 text-sm font-medium text-gray-100 rounded-lg border border-transparent transition duration-150 ease-in-out focus:outline-none hover:text-white focus:border-white hover:bg-gray-100 hover:bg-opacity-10 active:bg-gray-100 active:bg-opacity-10"
+ tabIndex={0}
+ type="button"
+ onClick={() => {
+ toast.error("Transcription is processing");
+ }}
+ >
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ className="w-5 h-5 sm:w-6 sm:h-6"
+ viewBox="0 0 24 24"
+ >
+ <style>
+ {"@keyframes spinner_AtaB{to{transform:rotate(360deg)}}"}
+ </style>
+ <path
+ fill="#FFF"
+ d="M12 1a11 11 0 1 0 11 11A11 11 0 0 0 12 1Zm0 19a8 8 0 1 1 8-8 8 8 0 0 1-8 8Z"
+ opacity={0.25}
+ />
+ <path
+ fill="#FFF"
+ d="M10.14 1.16a11 11 0 0 0-9 8.92A1.59 1.59 0 0 0 2.46 12a1.52 1.52 0 0 0 1.65-1.3 8 8 0 0 1 6.66-6.61A1.42 1.42 0 0 0 12 2.69a1.57 1.57 0 0 0-1.86-1.53Z"
+ style={{
+ transformOrigin: "center",
+ animation: "spinner_AtaB .75s infinite linear",
+ }}
+ />
+ </svg>
+ </button>
+ )}
+
+ {aiProcessing && (
+ <button
+ aria-label="AI summary is processing"
+ className="inline-flex justify-center items-center px-2 py-2 text-sm font-medium text-gray-100 rounded-lg border border-transparent transition duration-150 ease-in-out focus:outline-none hover:text-white focus:border-white hover:bg-gray-100 hover:bg-opacity-10 active:bg-gray-100 active:bg-opacity-10"
+ tabIndex={0}
+ type="button"
+ onClick={() => {
+ toast.info("AI summary is being generated");
+ }}
+ >
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ className="w-5 h-5 sm:w-6 sm:h-6"
+ viewBox="0 0 24 24"
+ >
+ <style>
+ {"@keyframes spinner_AtaB{to{transform:rotate(360deg)}}"}
+ </style>
+ <path
+ fill="#FFF"
+ d="M12 1a11 11 0 1 0 11 11A11 11 0 0 0 12 1Zm0 19a8 8 0 1 1 8-8 8 8 0 0 1-8 8Z"
+ opacity={0.25}
+ />
+ <path
+ fill="#FFF"
+ d="M10.14 1.16a11 11 0 0 0-9 8.92A1.59 1.59 0 0 0 2.46 12a1.52 1.52 0 0 0 1.65-1.3 8 8 0 0 1 6.66-6.61A1.42 1.42 0 0 0 12 2.69a1.57 1.57 0 0 0-1.86-1.53Z"
+ style={{
+ transformOrigin: "center",
+ animation: "spinner_AtaB .75s infinite linear",
+ }}
+ />
+ </svg>
+ </button>
+ )}
+
+ {subtitles.length > 0 && (
+ <button
+ aria-label={
+ subtitlesVisible ? "Hide subtitles" : "Show subtitles"
+ }
+ className="inline-flex justify-center items-center px-2 py-2 text-sm font-medium text-gray-100 rounded-lg border border-transparent transition duration-150 ease-in-out focus:outline-none hover:text-white focus:border-white hover:bg-gray-100 hover:bg-opacity-10 active:bg-gray-100 active:bg-opacity-10"
+ tabIndex={0}
+ type="button"
+ onClick={() => setSubtitlesVisible(!subtitlesVisible)}
+ >
+ {subtitlesVisible ? (
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ fill="none"
+ stroke="currentColor"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth="2"
+ className="w-auto h-5 sm:h-6"
+ viewBox="0 0 24 24"
+ >
+ <rect
+ width="18"
+ height="14"
+ x="3"
+ y="5"
+ rx="2"
+ ry="2"
+ ></rect>
+ <path d="M7 15h4m4 0h2m4 0h2"></path>
+ </svg>
+ ) : (
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ fill="none"
+ stroke="currentColor"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth="2"
+ className="w-auto h-5 sm:h-6"
+ viewBox="0 0 24 24"
+ >
+ <path d="M10.5 5H19a2 2 0 012 2v8.5M17 11h-.5M19 19H5a2 2 0 01-2-2V7a2 2 0 012-2M2 2l20 20M7 11h4M7 15h2.5"></path>
+ </svg>
+ )}
+ </button>
+ )}
+
+ <button
+ aria-label={videoRef?.current?.muted ? "Unmute" : "Mute"}
+ className="inline-flex justify-center items-center px-2 py-2 text-sm font-medium text-gray-100 rounded-lg border border-transparent transition duration-150 ease-in-out focus:outline-none hover:text-white focus:border-white hover:bg-gray-100 hover:bg-opacity-10 active:bg-gray-100 active:bg-opacity-10"
+ tabIndex={0}
+ type="button"
+ onClick={() => handleMuteClick()}
+ >
+ {videoRef?.current?.muted ? (
+ <VolumeX className="w-auto h-5 sm:h-6" />
+ ) : (
+ <Volume2 className="w-auto h-5 sm:h-6" />
+ )}
+ </button>
+
+ <button
+ aria-label="Go fullscreen"
+ className="inline-flex justify-center items-center px-2 py-2 text-sm font-medium text-gray-100 rounded-lg border border-transparent transition duration-150 ease-in-out focus:outline-none hover:text-white focus:border-white hover:bg-gray-100 hover:bg-opacity-10 active:bg-gray-100 active:bg-opacity-10"
+ tabIndex={0}
+ type="button"
+ onClick={handleFullscreenClick}
+ >
+ <Maximize className="w-auto h-5 sm:h-6" />
+ </button>
+ </div>
+ </div>
+ </div>
+
+ {user &&
+ !isUserOnProPlan({
+ subscriptionStatus: user.stripeSubscriptionStatus,
+ }) && (
+ <div
+ className={`absolute top-4 z-30 transition-all duration-300 ${
+ showTitleOverlay ? "right-4" : "left-4"
+ }`}
+ >
+ <div
+ className="block cursor-pointer"
+ onClick={(e) => {
+ e.stopPropagation();
+ setUpgradeModalOpen(true);
+ }}
+ >
+ <div className="relative">
+ <div className="opacity-50 transition-opacity hover:opacity-100 peer">
+ <Logo className="w-auto h-4 sm:h-8" white={true} />
+ </div>
+
+ <div
+ className={`absolute top-8 transition-transform duration-300 ease-in-out origin-top scale-y-0 peer-hover:scale-y-100 ${
+ showTitleOverlay ? "right-0" : "left-0"
+ }`}
+ >
+ <p className="text-white text-xs font-medium whitespace-nowrap bg-black bg-opacity-50 px-2 py-0.5 rounded">
+ Remove watermark
+ </p>
+ </div>
+ </div>
+ </div>
+ </div>
+ )}
+
+ <UpgradeModal
+ open={upgradeModalOpen}
+ onOpenChange={setUpgradeModalOpen}
+ />
+ </div>
+ );
+ }
+);
+
+const useVideoSourceValidation = (
+ data: typeof videos.$inferSelect,
+ videoMetadataLoaded: boolean
+) => {
+ return useQuery({
+ queryKey: ["video-source-validation", data.id, data.source.type],
+ queryFn: async () => {
+ if (data.source.type !== "desktopMP4") {
+ return { isMP4Source: false };
+ }
+
+ const thumbUrl = `/api/playlist?userId=${data.ownerId}&videoId=${data.id}&thumbnailTime=0`;
+
+ try {
+ const response = await fetch(thumbUrl, { method: "HEAD" });
+ return { isMP4Source: response.ok };
+ } catch (error) {
+ console.error("Error checking thumbnails:", error);
+ return { isMP4Source: false };
+ }
+ },
+ enabled: videoMetadataLoaded && data.source.type === "desktopMP4",
+ staleTime: 5 * 60 * 1000,
+ gcTime: 10 * 60 * 1000,
+ });
+};
+
+const useScreenSize = () => {
+ const [isLargeScreen, setIsLargeScreen] = useState(false);
+
+ useEffect(() => {
+ const checkScreenSize = () => {
+ setIsLargeScreen(window.innerWidth >= 1024);
+ };
+
+ checkScreenSize();
+ window.addEventListener("resize", checkScreenSize);
+
+ return () => window.removeEventListener("resize", checkScreenSize);
+ }, []);
+
+ return isLargeScreen;
+};
+
+const useTranscriptionProcessing = (
+ data: typeof videos.$inferSelect,
+ transcriptContent: string | undefined,
+ transcriptError: any
+) => {
+ const [isTranscriptionProcessing, setIsTranscriptionProcessing] = useState(
+ data.transcriptionStatus === "PROCESSING"
+ );
+ const [subtitles, setSubtitles] = useState<Subtitle[]>([]);
+
+ useEffect(() => {
+ if (transcriptContent) {
+ const parsedSubtitles = fromVtt(transcriptContent);
+ setSubtitles(parsedSubtitles);
+ setIsTranscriptionProcessing(false);
+ } else if (transcriptError) {
+ console.error(
+ "[EmbedVideo] Subtitle error from React Query:",
+ transcriptError.message
+ );
+ if (transcriptError.message === "TRANSCRIPT_NOT_READY") {
+ setIsTranscriptionProcessing(true);
+ } else {
+ setIsTranscriptionProcessing(false);
+ }
+ } else if (data.transcriptionStatus === "PROCESSING") {
+ setIsTranscriptionProcessing(true);
+ } else if (data.transcriptionStatus === "ERROR") {
+ setIsTranscriptionProcessing(false);
+ }
+ }, [transcriptContent, transcriptError, data.transcriptionStatus]);
+
+ return { isTranscriptionProcessing, subtitles };
+};
diff --git a/apps/web/app/embed/[videoId]/_components/PasswordOverlay.tsx b/apps/web/app/embed/[videoId]/_components/PasswordOverlay.tsx
new file mode 100644
index 000000000..2483ddfad
--- /dev/null
+++ b/apps/web/app/embed/[videoId]/_components/PasswordOverlay.tsx
@@ -0,0 +1,88 @@
+"use client";
+
+import { Button, Dialog, DialogContent, Input, Logo } from "@cap/ui";
+import { useState } from "react";
+import { toast } from "sonner";
+import { verifyVideoPassword } from "@/actions/videos/password";
+import { useMutation } from "@tanstack/react-query";
+import { useRouter } from "next/navigation";
+
+interface PasswordOverlayProps {
+ isOpen: boolean;
+ videoId: string;
+}
+
+export const PasswordOverlay: React.FC<PasswordOverlayProps> = ({
+ isOpen,
+ videoId,
+}) => {
+ const [password, setPassword] = useState("");
+ const router = useRouter();
+
+ const verifyPassword = useMutation({
+ mutationFn: () =>
+ verifyVideoPassword(videoId, password).then((v) => {
+ if (v.success) return v.value;
+ throw new Error(v.error);
+ }),
+ onSuccess: (result) => {
+ toast.success(result);
+ router.refresh();
+ },
+ onError: (e) => {
+ toast.error(e.message);
+ },
+ });
+
+ return (
+ <Dialog open={isOpen}>
+ <DialogContent className="w-[95vw] max-w-sm p-4 sm:p-6 md:p-8 sm:max-w-md">
+ <div className="flex flex-col items-center space-y-4 sm:space-y-6">
+ <div className="flex flex-col items-center space-y-3 sm:space-y-4">
+ <Logo className="w-16 sm:w-20 md:w-24 h-auto" />
+ <div className="text-center space-y-2">
+ <h2 className="text-lg sm:text-xl font-semibold text-gray-12">
+ Protected Video
+ </h2>
+ <p className="text-xs sm:text-sm text-gray-10 max-w-xs sm:max-w-sm px-2 sm:px-0">
+ This video is password protected. Please enter the password to
+ continue watching.
+ </p>
+ </div>
+ </div>
+
+ <div className="w-full space-y-3 sm:space-y-4">
+ <div className="space-y-2">
+ <label
+ htmlFor="password"
+ className="text-sm font-medium text-gray-12"
+ >
+ Password
+ </label>
+ <Input
+ id="password"
+ type="password"
+ value={password}
+ onChange={(e) => setPassword(e.target.value)}
+ placeholder="Enter password"
+ className="w-full"
+ autoFocus
+ />
+ </div>
+ <Button
+ type="button"
+ variant="dark"
+ size="lg"
+ className="w-full"
+ spinner={verifyPassword.isPending}
+ disabled={verifyPassword.isPending || !password.trim()}
+ onClick={() => verifyPassword.mutate()}
+ >
+ {verifyPassword.isPending ? "Verifying..." : "Access Video"}
+ </Button>
+ </div>
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+};
diff --git a/apps/web/app/embed/[videoId]/page.tsx b/apps/web/app/embed/[videoId]/page.tsx
new file mode 100644
index 000000000..48e553beb
--- /dev/null
+++ b/apps/web/app/embed/[videoId]/page.tsx
@@ -0,0 +1,303 @@
+import { db } from "@cap/database";
+import { eq } from "drizzle-orm";
+import {
+ videos,
+ users,
+ sharedVideos,
+ organizations,
+ comments,
+} from "@cap/database/schema";
+import { VideoMetadata } from "@cap/database/types";
+import { getCurrentUser } from "@cap/database/auth/session";
+import type { Metadata } from "next";
+import { notFound } from "next/navigation";
+import { buildEnv } from "@cap/env";
+import { transcribeVideo } from "@/actions/videos/transcribe";
+import { isAiGenerationEnabled } from "@/utils/flags";
+import { userHasAccessToVideo } from "@/utils/auth";
+import { EmbedVideo } from "./_components/EmbedVideo";
+import { PasswordOverlay } from "./_components/PasswordOverlay";
+
+export const dynamic = "auto";
+export const dynamicParams = true;
+export const revalidate = 30;
+
+type Props = {
+ params: { [key: string]: string | string[] | undefined };
+};
+
+export async function generateMetadata({ params }: Props): Promise<Metadata> {
+ const videoId = params.videoId as string;
+ const query = await db().select().from(videos).where(eq(videos.id, videoId));
+
+ if (query.length === 0) {
+ return notFound();
+ }
+
+ const video = query[0];
+
+ if (!video) {
+ return notFound();
+ }
+
+ if (video.public === false) {
+ return {
+ title: "Cap: This video is private",
+ description: "This video is private and cannot be shared.",
+ robots: "noindex, nofollow",
+ };
+ }
+
+ if (video.password !== null) {
+ return {
+ title: "Cap: Password Protected Video",
+ description: "This video is password protected.",
+ robots: "noindex, nofollow",
+ };
+ }
+
+ return {
+ 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?userId=${video.ownerId}&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(
+ `/embed/${videoId}`,
+ buildEnv.NEXT_PUBLIC_WEB_URL
+ ).toString(),
+ streamUrl: new URL(
+ `/api/playlist?userId=${video.ownerId}&videoId=${video.id}`,
+ buildEnv.NEXT_PUBLIC_WEB_URL
+ ).toString(),
+ width: 1280,
+ height: 720,
+ },
+ },
+ robots: "index, follow",
+ };
+}
+
+export default async function EmbedVideoPage(props: Props) {
+ const params = props.params;
+ const videoId = params.videoId as string;
+
+ const user = await getCurrentUser();
+
+ const videoWithOrganization = await db()
+ .select({
+ id: videos.id,
+ name: videos.name,
+ ownerId: videos.ownerId,
+ createdAt: videos.createdAt,
+ updatedAt: videos.updatedAt,
+ awsRegion: videos.awsRegion,
+ awsBucket: videos.awsBucket,
+ 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,
+ password: videos.password,
+ source: videos.source,
+ sharedOrganization: {
+ organizationId: sharedVideos.organizationId,
+ },
+ })
+ .from(videos)
+ .leftJoin(sharedVideos, eq(videos.id, sharedVideos.videoId))
+ .where(eq(videos.id, videoId))
+ .execute();
+
+ const video = videoWithOrganization[0];
+
+ if (!video) {
+ return notFound();
+ }
+
+ const userAccess = await userHasAccessToVideo(user, video);
+
+ if (userAccess === "private") {
+ return (
+ <div className="min-h-screen flex items-center justify-center bg-black text-white">
+ <p>This video is private</p>
+ </div>
+ );
+ }
+
+ return (
+ <div className="min-h-screen bg-black">
+ <PasswordOverlay
+ isOpen={userAccess === "needs-password"}
+ videoId={video.id}
+ />
+ {userAccess === "has-access" && (
+ <EmbedContent video={video} user={user} />
+ )}
+ </div>
+ );
+}
+
+async function EmbedContent({
+ video,
+ user,
+}: {
+ video: typeof videos.$inferSelect & {
+ sharedOrganization: { organizationId: string } | null;
+ };
+ user: typeof users.$inferSelect | null;
+}) {
+ let aiGenerationEnabled = false;
+ const videoOwnerQuery = await db()
+ .select({
+ email: users.email,
+ stripeSubscriptionStatus: users.stripeSubscriptionStatus,
+ })
+ .from(users)
+ .where(eq(users.id, video.ownerId))
+ .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}`)
+ ) {
+ return (
+ <div className="flex flex-col justify-center items-center min-h-screen text-center bg-black text-white">
+ <h1 className="mb-4 text-2xl font-bold">Access Restricted</h1>
+ <p className="mb-2 text-gray-300">
+ This video is only accessible to members of this organization.
+ </p>
+ <p className="text-gray-400">
+ Please sign in with your organization email address to access this
+ content.
+ </p>
+ </div>
+ );
+ }
+ }
+ }
+
+ if (
+ video.transcriptionStatus !== "COMPLETE" &&
+ video.transcriptionStatus !== "PROCESSING"
+ ) {
+ await transcribeVideo(video.id, video.ownerId, aiGenerationEnabled);
+ }
+
+ const currentMetadata = (video.metadata as VideoMetadata) || {};
+ let initialAiData = null;
+
+ if (
+ currentMetadata.summary ||
+ currentMetadata.chapters ||
+ currentMetadata.aiTitle
+ ) {
+ initialAiData = {
+ title: currentMetadata.aiTitle || null,
+ summary: currentMetadata.summary || null,
+ chapters: currentMetadata.chapters || null,
+ processing: currentMetadata.aiProcessing || false,
+ };
+ } else if (currentMetadata.aiProcessing) {
+ initialAiData = {
+ title: null,
+ summary: null,
+ chapters: null,
+ processing: true,
+ };
+ }
+
+ if (video.isScreenshot === true) {
+ return (
+ <div className="flex items-center justify-center min-h-screen bg-black text-white">
+ <p>Screenshots cannot be embedded</p>
+ </div>
+ );
+ }
+
+ const commentsQuery = await 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,
+ })
+ .from(comments)
+ .leftJoin(users, eq(comments.authorId, users.id))
+ .where(eq(comments.videoId, video.id));
+
+ const videoOwner = await db()
+ .select({
+ name: users.name,
+ })
+ .from(users)
+ .where(eq(users.id, video.ownerId))
+ .limit(1);
+
+ return (
+ <EmbedVideo
+ data={video}
+ user={user}
+ comments={commentsQuery}
+ chapters={initialAiData?.chapters || []}
+ aiProcessing={initialAiData?.processing || false}
+ ownerName={videoOwner[0]?.name || null}
+ />
+ );
+}
diff --git a/apps/web/app/embed/page.tsx b/apps/web/app/embed/page.tsx
new file mode 100644
index 000000000..292a88c8a
--- /dev/null
+++ b/apps/web/app/embed/page.tsx
@@ -0,0 +1,6 @@
+"use server";
+import { redirect } from "next/navigation";
+
+export default async function EmbedPage() {
+ redirect("/");
+}
diff --git a/apps/web/app/providers.tsx b/apps/web/app/providers.tsx
index cb05cccc2..c327ea515 100644
--- a/apps/web/app/providers.tsx
+++ b/apps/web/app/providers.tsx
@@ -65,7 +65,8 @@ export function AnalyticsProvider({
email?: string;
}) {
const pathname = usePathname();
- const isSharePage = pathname?.startsWith("/s/");
+ const isSharePage =
+ pathname?.startsWith("/s/") || pathname?.startsWith("/embed/");
useEffect(() => {
if (!isSharePage) {
diff --git a/apps/web/app/s/[videoId]/_components/PasswordOverlay.tsx b/apps/web/app/s/[videoId]/_components/PasswordOverlay.tsx
index 55f7a3dfb..2483ddfad 100644
--- a/apps/web/app/s/[videoId]/_components/PasswordOverlay.tsx
+++ b/apps/web/app/s/[videoId]/_components/PasswordOverlay.tsx
@@ -36,22 +36,22 @@ export const PasswordOverlay: React.FC<PasswordOverlayProps> = ({
return (
<Dialog open={isOpen}>
- <DialogContent className="w-[90vw] sm:max-w-md p-8 rounded-xl border border-gray-200 bg-white shadow-xl">
- <div className="flex flex-col items-center space-y-6">
- <div className="flex flex-col items-center space-y-4">
- <Logo className="w-24 h-auto" />
+ <DialogContent className="w-[95vw] max-w-sm p-4 sm:p-6 md:p-8 sm:max-w-md">
+ <div className="flex flex-col items-center space-y-4 sm:space-y-6">
+ <div className="flex flex-col items-center space-y-3 sm:space-y-4">
+ <Logo className="w-16 sm:w-20 md:w-24 h-auto" />
<div className="text-center space-y-2">
- <h2 className="text-xl font-semibold text-gray-12">
+ <h2 className="text-lg sm:text-xl font-semibold text-gray-12">
Protected Video
</h2>
- <p className="text-sm text-gray-10 max-w-sm">
+ <p className="text-xs sm:text-sm text-gray-10 max-w-xs sm:max-w-sm px-2 sm:px-0">
This video is password protected. Please enter the password to
continue watching.
</p>
</div>
</div>
- <div className="w-full space-y-4">
+ <div className="w-full space-y-3 sm:space-y-4">
<div className="space-y-2">
<label
htmlFor="password"
diff --git a/apps/web/components/Footer.tsx b/apps/web/components/Footer.tsx
index cfaed92ef..67bb90ae6 100644
--- a/apps/web/components/Footer.tsx
+++ b/apps/web/components/Footer.tsx
@@ -100,9 +100,11 @@ export const Footer = () => {
if (
pathname === "/login" ||
pathname === "/s" ||
+ pathname === "/embed" ||
pathname.includes("/dashboard") ||
pathname.includes("/invite") ||
pathname.includes("/s/") ||
+ pathname.includes("/embed/") ||
pathname.includes("/onboarding") ||
(typeof window !== "undefined" && window.location.href.includes("cap.link"))
)
diff --git a/apps/web/components/Navbar.tsx b/apps/web/components/Navbar.tsx
index ff95499da..8c86ea9c6 100644
--- a/apps/web/components/Navbar.tsx
+++ b/apps/web/components/Navbar.tsx
@@ -101,9 +101,11 @@ export const Navbar = ({ auth }: { auth: boolean }) => {
if (
pathname === "/login" ||
pathname === "/s" ||
+ pathname === "/embed" ||
pathname.includes("/dashboard") ||
pathname.includes("/invite") ||
pathname.includes("/s/") ||
+ pathname.includes("/embed/") ||
pathname.includes("/onboarding") ||
(typeof window !== "undefined" && window.location.href.includes("cap.link"))
)
diff --git a/apps/web/content/docs/self-hosting.mdx b/apps/web/content/docs/self-hosting.mdx
index 764292985..9ab72c4a8 100644
--- a/apps/web/content/docs/self-hosting.mdx
+++ b/apps/web/content/docs/self-hosting.mdx
@@ -11,6 +11,22 @@ You can upload videos to it from the dashboard or from Cap Desktop.
This guide describes our two supported deployment methods, how to connect Cap Desktop,
and how to configure email login links.
+<div style={{ position: "relative", paddingBottom: "56.25%", height: 0 }}>
+ <iframe
+ src="https://cap.so/embed/k310v2vf41d6ffp"
+ frameBorder="0"
+ allowFullScreen
+ style={{
+ position: "absolute",
+ top: 0,
+ left: 0,
+ width: "100%",
+ height: "100%",
+ borderRadius: "15px",
+ }}
+ ></iframe>
+</div>
+
## Deployment Methods
### Deploying with Railway
diff --git a/packages/ui/src/components/icons/Logo.tsx b/packages/ui/src/components/icons/Logo.tsx
index ed6c4ffcc..d82697766 100644
--- a/packages/ui/src/components/icons/Logo.tsx
+++ b/packages/ui/src/components/icons/Logo.tsx
@@ -54,7 +54,7 @@ export const Logo = ({
/>
{!hideLogoName && (
<path
- className="fill-gray-12"
+ className={`${white ? "fill-white" : "fill-gray-12"}`}
fill={white ? "#ffffff" : "#12161F"}
d="M58.416 30.448c-5.404 0-9.212-3.864-9.212-10.36 0-6.384 3.668-10.416 9.268-10.416 5.068 0 7.784 2.66 8.624 7.168l-3.808.196c-.476-2.604-2.072-4.2-4.816-4.2-3.388 0-5.488 2.828-5.488 7.252 0 4.48 2.156 7.196 5.46 7.196 2.94 0 4.508-1.708 4.956-4.564l3.808.196c-.784 4.676-3.752 7.532-8.792 7.532zm16.23-.112c-3.137 0-5.209-1.484-5.209-4.088 0-2.576 1.596-3.948 4.872-4.592l4.956-.98c0-2.1-.98-3.192-2.856-3.192-1.764 0-2.716.812-3.052 2.324l-3.668-.168c.588-3.136 2.996-4.928 6.72-4.928 4.256 0 6.44 2.24 6.44 6.216v5.432c0 .812.28 1.036.84 1.036h.476V30c-.224.056-.812.112-1.288.112-1.624 0-2.828-.588-3.136-2.436-.728 1.596-2.632 2.66-5.096 2.66zm.727-2.604c2.38 0 3.892-1.512 3.892-3.78v-.84l-3.864.784c-1.596.308-2.24.98-2.24 2.016 0 1.176.784 1.82 2.212 1.82zM86.874 34.2V15.048h3.444l.056 2.212c.868-1.652 2.52-2.548 4.48-2.548 4.256 0 6.356 3.5 6.356 7.812s-2.128 7.812-6.384 7.812c-1.904 0-3.556-.924-4.368-2.38V34.2h-3.584zm7.112-6.776c2.184 0 3.5-1.82 3.5-4.9s-1.316-4.9-3.5-4.9-3.528 1.652-3.528 4.9 1.316 4.9 3.528 4.9z"
/>