Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: Use thumbnail for video poster

Richie McIlroy0d26524e9299
diff --git a/apps/web/app/api/playlist/route.ts b/apps/web/app/api/playlist/route.ts
index 6ed96cb94..2c8070212 100644
--- a/apps/web/app/api/playlist/route.ts
+++ b/apps/web/app/api/playlist/route.ts
@@ -85,11 +85,54 @@ export async function GET(request: NextRequest) {
if (!bucket || video.awsBucket === clientEnv.NEXT_PUBLIC_CAP_AWS_BUCKET) {
if (video.source.type === "desktopMP4") {
+ if (videoType === "mp4") {
+ // Add specific headers for MP4 videos to enable embedding
+ const playlistUrl = await getSignedUrl(
+ s3Client,
+ new GetObjectCommand({
+ Bucket,
+ Key: `${userId}/${videoId}/result.mp4`,
+ }),
+ { expiresIn: 3600 }
+ );
+
+ // Check if this is a direct access from a third-party site by examining the Referer header
+ const referer = request.headers.get("referer");
+ const isEmbedded = referer && !referer.includes(request.headers.get("host") || "");
+
+ const corsHeaders = {
+ ...getHeaders(origin),
+ ...CACHE_CONTROL_HEADERS,
+ "Access-Control-Allow-Origin": "*",
+ "Access-Control-Allow-Methods": "GET, OPTIONS",
+ "Access-Control-Allow-Headers": "Content-Type, Authorization",
+ "Content-Type": "video/mp4",
+ "X-Content-Type-Options": "nosniff",
+ };
+
+ return new Response(null, {
+ status: 302,
+ headers: {
+ ...corsHeaders,
+ Location: playlistUrl,
+ },
+ });
+ }
+
+ const playlistUrl = await getSignedUrl(
+ s3Client,
+ new GetObjectCommand({
+ Bucket,
+ Key: `${userId}/${videoId}/result.mp4`,
+ }),
+ { expiresIn: 3600 }
+ );
+
return new Response(null, {
status: 302,
headers: {
...getHeaders(origin),
- Location: `${S3_BUCKET_URL}/${userId}/${videoId}/result.mp4`,
+ Location: playlistUrl,
...CACHE_CONTROL_HEADERS,
},
});
diff --git a/apps/web/app/s/[videoId]/_components/MP4VideoPlayer.tsx b/apps/web/app/s/[videoId]/_components/MP4VideoPlayer.tsx
index bdf8ffd9a..0ec42108d 100644
--- a/apps/web/app/s/[videoId]/_components/MP4VideoPlayer.tsx
+++ b/apps/web/app/s/[videoId]/_components/MP4VideoPlayer.tsx
@@ -7,6 +7,7 @@ import {
useRef,
useState,
} from "react";
+import { clientEnv } from "@cap/env";
interface MP4VideoPlayerProps {
videoSrc: string;
@@ -22,9 +23,34 @@ export const MP4VideoPlayer = memo(
const [isLoaded, setIsLoaded] = useState(false);
const [currentSrc, setCurrentSrc] = useState(videoSrc);
const lastAttemptTime = useRef<number>(Date.now());
+ const [thumbnailSrc, setThumbnailSrc] = useState<string | undefined>(
+ undefined
+ );
useImperativeHandle(ref, () => videoRef.current as HTMLVideoElement);
+ // Extract userId and videoId from the URL
+ const userId = videoSrc.split("userId=")[1]?.split("&")[0];
+ const videoId = videoSrc.split("videoId=")[1]?.split("&")[0];
+
+ // Fetch the thumbnail
+ useEffect(() => {
+ if (userId && videoId) {
+ fetch(
+ `${clientEnv.NEXT_PUBLIC_WEB_URL}/api/thumbnail?userId=${userId}&videoId=${videoId}`
+ )
+ .then((response) => response.json())
+ .then((data) => {
+ if (data.screen) {
+ setThumbnailSrc(data.screen);
+ }
+ })
+ .catch((error) => {
+ console.error("Error fetching thumbnail:", error);
+ });
+ }
+ }, [userId, videoId]);
+
const fetchNewUrl = useCallback(async () => {
try {
// Add timestamp to prevent caching
@@ -229,6 +255,8 @@ export const MP4VideoPlayer = memo(
playsInline
controls={false}
muted
+ crossOrigin="anonymous"
+ poster={thumbnailSrc}
>
<source src={currentSrc} type="video/mp4" />
</video>
diff --git a/apps/web/app/s/[videoId]/_components/ShareVideo.tsx b/apps/web/app/s/[videoId]/_components/ShareVideo.tsx
index ebcc5c6a5..3a08d5ce9 100644
--- a/apps/web/app/s/[videoId]/_components/ShareVideo.tsx
+++ b/apps/web/app/s/[videoId]/_components/ShareVideo.tsx
@@ -221,13 +221,20 @@ export const ShareVideo = forwardRef<
if (videoRef.current) {
setLongestDuration(videoRef.current.duration);
setVideoMetadataLoaded(true);
- // Don't set isLoading to false here
+
+ // If we have the metadata, we should be able to display the poster frame
+ // even if the video isn't fully playable yet
+ setTimeout(() => {
+ // Set a timeout to reduce flicker between black screen and poster
+ setIsLoading(false);
+ }, 100);
}
};
const onCanPlay = () => {
setVideoMetadataLoaded(true);
setVideoReadyToPlay(true);
+ setIsLoading(false); // Ensure loading is false once playable
// If the video is already playing (user clicked play before it was ready),
// ensure it actually starts playing now
@@ -244,11 +251,6 @@ export const ShareVideo = forwardRef<
videoRef.current.currentTime = currentPosition;
}
}
-
- // Set a small delay before removing the loading state to ensure smooth transition
- setTimeout(() => {
- setIsLoading(false);
- }, 100);
};
const videoElement = videoRef.current;
@@ -266,7 +268,7 @@ export const ShareVideo = forwardRef<
videoElement.removeEventListener("canplay", onCanPlay);
}
};
- }, []);
+ }, [isPlaying]);
const handlePlayPauseClick = async () => {
const videoElement = videoRef.current;
@@ -1052,14 +1054,14 @@ export const ShareVideo = forwardRef<
className="overflow-hidden relative w-full h-full rounded-lg shadow-lg group"
>
<div
- className={`absolute inset-0 flex items-center justify-center z-10 bg-black transition-opacity duration-300 ${
+ className={`absolute inset-0 flex items-center justify-center z-10 bg-black/50 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">
+ <div className="absolute inset-0">
{data.source.type === "desktopMP4" ? (
<MP4VideoPlayer ref={videoRef} videoSrc={videoSrc} />
) : (
diff --git a/apps/web/app/s/[videoId]/page.tsx b/apps/web/app/s/[videoId]/page.tsx
index 744e9224e..c2471fc93 100644
--- a/apps/web/app/s/[videoId]/page.tsx
+++ b/apps/web/app/s/[videoId]/page.tsx
@@ -81,6 +81,15 @@ export async function generateMetadata(
};
}
+ // Get thumbnail URL
+ const thumbnailUrl = `${clientEnv.NEXT_PUBLIC_WEB_URL}/api/video/og?videoId=${videoId}`;
+
+ // Get direct MP4 URL
+ const videoUrl = `${clientEnv.NEXT_PUBLIC_WEB_URL}/api/playlist?userId=${video.ownerId}&videoId=${video.id}&videoType=mp4`;
+
+ // Full page URL for embedding
+ const pageUrl = `${clientEnv.NEXT_PUBLIC_WEB_URL}/s/${videoId}`;
+
console.log(
"[generateMetadata] Returning public metadata for video:",
video.name
@@ -89,10 +98,58 @@ export async function generateMetadata(
title: video.name + " | Cap Recording",
description: "Watch this video on Cap",
openGraph: {
- images: [
- `${clientEnv.NEXT_PUBLIC_WEB_URL}/api/video/og?videoId=${videoId}`,
+ title: video.name,
+ description: "Watch this video on Cap",
+ url: pageUrl,
+ images: [thumbnailUrl],
+ type: "video.other",
+ videos: [
+ {
+ url: videoUrl,
+ width: 1280,
+ height: 720,
+ type: "video/mp4",
+ },
+ ],
+ },
+ twitter: {
+ card: "player",
+ site: "@cap_hq",
+ title: video.name,
+ description: "Watch this video on Cap",
+ images: [thumbnailUrl],
+ players: [
+ {
+ playerUrl: pageUrl,
+ streamUrl: videoUrl,
+ width: 1280,
+ height: 720,
+ },
],
},
+ other: {
+ "video:duration": Math.floor(video?.metadata?.duration || 0).toString(),
+ "og:video:duration": Math.floor(
+ video?.metadata?.duration || 0
+ ).toString(),
+ "og:video:url": videoUrl,
+ "og:video:secure_url": videoUrl,
+ "og:video:type": "video/mp4",
+ "og:video:width": "1280",
+ "og:video:height": "720",
+ },
+ metadataBase: new URL(clientEnv.NEXT_PUBLIC_WEB_URL),
+ alternates: {
+ canonical: `/s/${videoId}`,
+ },
+ icons: {
+ icon: "/favicon.ico",
+ },
+ viewport: {
+ width: "device-width",
+ initialScale: 1,
+ },
+ assets: [thumbnailUrl],
};
}