Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: Edit transcript + Video player UX goodies (#596)

Richie McIlroy4ba76a95efb3
diff --git a/apps/web/actions/videos/edit-transcript.ts b/apps/web/actions/videos/edit-transcript.ts
new file mode 100644
index 000000000..707620c64
--- /dev/null
+++ b/apps/web/actions/videos/edit-transcript.ts
@@ -0,0 +1,163 @@
+"use server";
+
+import { GetObjectCommand, PutObjectCommand } from "@aws-sdk/client-s3";
+import { getCurrentUser } from "@cap/database/auth/session";
+import { videos, s3Buckets } from "@cap/database/schema";
+import { db } from "@cap/database";
+import { eq } from "drizzle-orm";
+import { revalidatePath } from "next/cache";
+import { createS3Client } from "@/utils/s3";
+
+export async function editTranscriptEntry(
+ videoId: string,
+ entryId: number,
+ newText: string
+): Promise<{ success: boolean; message: string }> {
+
+ const user = await getCurrentUser();
+
+ if (!user || !videoId || entryId === undefined || !newText?.trim()) {
+ return {
+ success: false,
+ message: "Missing required data for updating transcript entry",
+ };
+ }
+
+ const userId = user.id;
+ const query = await db()
+ .select({
+ video: videos,
+ bucket: s3Buckets,
+ })
+ .from(videos)
+ .leftJoin(s3Buckets, eq(videos.bucket, s3Buckets.id))
+ .where(eq(videos.id, videoId));
+
+ if (query.length === 0) {
+ return { success: false, message: "Video not found" };
+ }
+
+ const result = query[0];
+ if (!result?.video) {
+ return { success: false, message: "Video information is missing" };
+ }
+
+ const { video, bucket } = result;
+
+ if (video.ownerId !== userId) {
+ return {
+ success: false,
+ message: "You don't have permission to edit this transcript",
+ };
+ }
+
+ const awsRegion = video.awsRegion;
+ const awsBucket = video.awsBucket;
+
+ if (!awsRegion || !awsBucket) {
+ return {
+ success: false,
+ message: "AWS region or bucket information is missing",
+ };
+ }
+ const [s3Client] = await createS3Client(bucket);
+
+ try {
+ const transcriptKey = `${video.ownerId}/${videoId}/transcription.vtt`;
+
+ const getCommand = new GetObjectCommand({
+ Bucket: awsBucket,
+ Key: transcriptKey,
+ });
+
+ const response = await s3Client.send(getCommand);
+ const vttContent = await response.Body?.transformToString();
+
+ if (!vttContent) {
+ return { success: false, message: "Transcript file not found" };
+ }
+ const updatedVttContent = updateVttEntry(vttContent, entryId, newText);
+ const putCommand = new PutObjectCommand({
+ Bucket: awsBucket,
+ Key: transcriptKey,
+ Body: updatedVttContent,
+ ContentType: "text/vtt",
+ });
+
+ await s3Client.send(putCommand);
+ revalidatePath(`/s/${videoId}`);
+
+ return {
+ success: true,
+ message: "Transcript entry updated successfully",
+ };
+ } catch (error) {
+ console.error("Error updating transcript entry:", {
+ error: error instanceof Error ? error.message : error,
+ videoId,
+ entryId,
+ userId
+ });
+ return {
+ success: false,
+ message: "Failed to update transcript entry",
+ };
+ }
+}
+
+function updateVttEntry(vttContent: string, entryId: number, newText: string): string {
+
+ const lines = vttContent.split("\n");
+ const updatedLines: string[] = [];
+ let currentEntryId: number | null = null;
+ let foundEntry = false;
+ let isNextLineText = false;
+
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i] || "";
+ const trimmedLine = line.trim();
+
+ if (!trimmedLine) {
+ updatedLines.push(line);
+ isNextLineText = false;
+ continue;
+ }
+
+ if (trimmedLine === "WEBVTT") {
+ updatedLines.push(line);
+ continue;
+ }
+
+ if (/^\d+$/.test(trimmedLine)) {
+ currentEntryId = parseInt(trimmedLine, 10);
+ updatedLines.push(line);
+ isNextLineText = false;
+ continue;
+ }
+
+ if (trimmedLine.includes("-->")) {
+ updatedLines.push(line);
+ isNextLineText = true;
+ continue;
+ }
+
+ if (currentEntryId === entryId && isNextLineText && !foundEntry) {
+ updatedLines.push(newText.trim());
+ foundEntry = true;
+ isNextLineText = false;
+ } else {
+ updatedLines.push(line);
+ if (isNextLineText) {
+ isNextLineText = false;
+ }
+ }
+ }
+
+ if (!foundEntry) {
+ console.warn("Target entry not found in VTT content", { entryId, totalEntries: lines.filter(line => /^\d+$/.test(line.trim())).length });
+ }
+
+ const result = updatedLines.join("\n");
+
+ return result;
+}
\ No newline at end of file
diff --git a/apps/web/actions/videos/get-status.ts b/apps/web/actions/videos/get-status.ts
new file mode 100644
index 000000000..5a036aa41
--- /dev/null
+++ b/apps/web/actions/videos/get-status.ts
@@ -0,0 +1,192 @@
+"use server";
+
+import { getCurrentUser } from "@cap/database/auth/session";
+import { db } from "@cap/database";
+import { videos, users } from "@cap/database/schema";
+import { VideoMetadata } from "@cap/database/types";
+import { eq } from "drizzle-orm";
+import { generateAiMetadata } from "./generate-ai-metadata";
+import { transcribeVideo } from "./transcribe";
+import { isAiGenerationEnabled } from "@/utils/flags";
+
+const MAX_AI_PROCESSING_TIME = 10 * 60 * 1000;
+
+export interface VideoStatusResult {
+ transcriptionStatus: "PROCESSING" | "COMPLETE" | "ERROR" | null;
+ aiProcessing: boolean;
+ aiTitle: string | null;
+ summary: string | null;
+ chapters: { title: string; start: number }[] | null;
+ generationError: string | null;
+ error?: string;
+}
+
+export async function getVideoStatus(videoId: string): Promise<VideoStatusResult> {
+ const user = await getCurrentUser();
+
+ if (!user) {
+ throw new Error("Authentication required");
+ }
+
+ if (!videoId) {
+ throw new Error("Video ID not provided");
+ }
+
+ const result = await db().select().from(videos).where(eq(videos.id, videoId));
+ if (result.length === 0 || !result[0]) {
+ throw new Error("Video not found");
+ }
+
+ const video = result[0];
+ const metadata: VideoMetadata = (video.metadata as VideoMetadata) || {};
+
+ if (!video.transcriptionStatus) {
+ console.log(`[Get Status] Transcription not started for video ${videoId}, triggering transcription`);
+ try {
+ transcribeVideo(videoId, video.ownerId).catch(error => {
+ console.error(`[Get Status] Error starting transcription for video ${videoId}:`, error);
+ });
+
+ return {
+ transcriptionStatus: "PROCESSING",
+ aiProcessing: false,
+ aiTitle: metadata.aiTitle || null,
+ summary: metadata.summary || null,
+ chapters: metadata.chapters || null,
+ generationError: metadata.generationError || null,
+ };
+ } catch (error) {
+ console.error(`[Get Status] Error triggering transcription for video ${videoId}:`, error);
+ return {
+ transcriptionStatus: "ERROR",
+ aiProcessing: false,
+ aiTitle: metadata.aiTitle || null,
+ summary: metadata.summary || null,
+ chapters: metadata.chapters || null,
+ generationError: metadata.generationError || null,
+ error: "Failed to start transcription"
+ };
+ }
+ }
+
+ if (video.transcriptionStatus === "ERROR") {
+ return {
+ transcriptionStatus: "ERROR",
+ aiProcessing: false,
+ aiTitle: metadata.aiTitle || null,
+ summary: metadata.summary || null,
+ chapters: metadata.chapters || null,
+ generationError: metadata.generationError || null,
+ error: "Transcription failed"
+ };
+ }
+
+ if (metadata.aiProcessing) {
+ const updatedAtTime = new Date(video.updatedAt).getTime();
+ const currentTime = new Date().getTime();
+
+ if (currentTime - updatedAtTime > MAX_AI_PROCESSING_TIME) {
+ console.log(`[Get Status] AI processing appears stuck for video ${videoId} (${Math.round((currentTime - updatedAtTime) / 60000)} minutes), resetting flag`);
+
+ await db()
+ .update(videos)
+ .set({
+ metadata: {
+ ...metadata,
+ aiProcessing: false,
+ generationError: "AI processing timed out and was reset"
+ }
+ })
+ .where(eq(videos.id, videoId));
+
+ const updatedResult = await db().select().from(videos).where(eq(videos.id, videoId));
+ if (updatedResult.length > 0 && updatedResult[0]) {
+ const updatedVideo = updatedResult[0];
+ const updatedMetadata = updatedVideo.metadata as VideoMetadata || {};
+
+ return {
+ transcriptionStatus: (updatedVideo.transcriptionStatus as "PROCESSING" | "COMPLETE" | "ERROR") || null,
+ aiProcessing: false,
+ aiTitle: updatedMetadata.aiTitle || null,
+ summary: updatedMetadata.summary || null,
+ chapters: updatedMetadata.chapters || null,
+ generationError: updatedMetadata.generationError || null,
+ error: "AI processing timed out and was reset"
+ };
+ }
+ }
+ }
+
+ if (
+ video.transcriptionStatus === "COMPLETE" &&
+ !metadata.aiProcessing &&
+ !metadata.summary &&
+ !metadata.chapters &&
+ !metadata.generationError
+ ) {
+ console.log(`[Get Status] Transcription complete but no AI data, checking feature flag for video owner ${video.ownerId}`);
+
+ 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] && (await isAiGenerationEnabled(videoOwnerQuery[0]))) {
+ console.log(`[Get Status] Feature flag enabled, triggering AI generation for video ${videoId}`);
+
+ (async () => {
+ try {
+ console.log(`[Get Status] Starting AI metadata generation for video ${videoId}`);
+ await generateAiMetadata(videoId, video.ownerId);
+ console.log(`[Get Status] AI metadata generation completed for video ${videoId}`);
+ } catch (error) {
+ console.error(`[Get Status] Error generating AI metadata for video ${videoId}:`, error);
+
+ try {
+ const currentVideo = await db().select().from(videos).where(eq(videos.id, videoId));
+ if (currentVideo.length > 0 && currentVideo[0]) {
+ const currentMetadata = (currentVideo[0].metadata as VideoMetadata) || {};
+ await db()
+ .update(videos)
+ .set({
+ metadata: {
+ ...currentMetadata,
+ aiProcessing: false,
+ generationError: error instanceof Error ? error.message : String(error)
+ }
+ })
+ .where(eq(videos.id, videoId));
+ }
+ } catch (resetError) {
+ console.error(`[Get Status] Failed to reset AI processing flag for video ${videoId}:`, resetError);
+ }
+ }
+ })();
+
+ return {
+ transcriptionStatus: (video.transcriptionStatus as "PROCESSING" | "COMPLETE" | "ERROR") || null,
+ aiProcessing: true,
+ aiTitle: metadata.aiTitle || null,
+ summary: metadata.summary || null,
+ chapters: metadata.chapters || null,
+ generationError: metadata.generationError || null,
+ };
+ } else {
+ const videoOwner = videoOwnerQuery[0];
+ console.log(`[Get Status] AI generation feature disabled for video owner ${video.ownerId} (email: ${videoOwner?.email}, pro: ${videoOwner?.stripeSubscriptionStatus})`);
+ }
+ }
+
+ return {
+ transcriptionStatus: (video.transcriptionStatus as "PROCESSING" | "COMPLETE" | "ERROR") || null,
+ aiProcessing: metadata.aiProcessing || false,
+ aiTitle: metadata.aiTitle || null,
+ summary: metadata.summary || null,
+ chapters: metadata.chapters || null,
+ generationError: metadata.generationError || null,
+ };
+}
\ No newline at end of file
diff --git a/apps/web/actions/videos/get-transcript.ts b/apps/web/actions/videos/get-transcript.ts
new file mode 100644
index 000000000..0a6eb7c3a
--- /dev/null
+++ b/apps/web/actions/videos/get-transcript.ts
@@ -0,0 +1,100 @@
+"use server";
+
+import { GetObjectCommand } from "@aws-sdk/client-s3";
+import { getCurrentUser } from "@cap/database/auth/session";
+import { videos, s3Buckets } from "@cap/database/schema";
+import { db } from "@cap/database";
+import { eq } from "drizzle-orm";
+import { createS3Client } from "@/utils/s3";
+
+export async function getTranscript(
+ videoId: string
+): Promise<{ success: boolean; content?: string; message: string }> {
+
+ const user = await getCurrentUser();
+
+ if (!user || !videoId) {
+ return {
+ success: false,
+ message: "Missing required data for fetching transcript",
+ };
+ }
+
+ const userId = user.id;
+ const query = await db()
+ .select({
+ video: videos,
+ bucket: s3Buckets,
+ })
+ .from(videos)
+ .leftJoin(s3Buckets, eq(videos.bucket, s3Buckets.id))
+ .where(eq(videos.id, videoId));
+
+ if (query.length === 0) {
+ return { success: false, message: "Video not found" };
+ }
+
+ const result = query[0];
+ if (!result?.video) {
+ return { success: false, message: "Video information is missing" };
+ }
+
+ const { video, bucket } = result;
+
+ if (video.ownerId !== userId) {
+ return {
+ success: false,
+ message: "You don't have permission to access this transcript",
+ };
+ }
+
+ if (video.transcriptionStatus !== "COMPLETE") {
+ return {
+ success: false,
+ message: "Transcript is not ready yet",
+ };
+ }
+
+ const awsRegion = video.awsRegion;
+ const awsBucket = video.awsBucket;
+
+ if (!awsRegion || !awsBucket) {
+ return {
+ success: false,
+ message: "AWS region or bucket information is missing",
+ };
+ }
+ const [s3Client] = await createS3Client(bucket);
+
+ try {
+ const transcriptKey = `${video.ownerId}/${videoId}/transcription.vtt`;
+
+ const getCommand = new GetObjectCommand({
+ Bucket: awsBucket,
+ Key: transcriptKey,
+ });
+
+ const response = await s3Client.send(getCommand);
+ const vttContent = await response.Body?.transformToString();
+
+ if (!vttContent) {
+ return { success: false, message: "Transcript file not found" };
+ }
+
+ return {
+ success: true,
+ content: vttContent,
+ message: "Transcript retrieved successfully",
+ };
+ } catch (error) {
+ console.error("[getTranscript] Error fetching transcript:", {
+ error: error instanceof Error ? error.message : error,
+ videoId,
+ userId
+ });
+ return {
+ success: false,
+ message: "Failed to fetch transcript",
+ };
+ }
+}
\ No newline at end of file
diff --git a/apps/web/app/api/playlist/route.ts b/apps/web/app/api/playlist/route.ts
index e4641f315..9fb228912 100644
--- a/apps/web/app/api/playlist/route.ts
+++ b/apps/web/app/api/playlist/route.ts
@@ -95,7 +95,6 @@ const app = new Hono()
);
}
- // Handle transcription file request first
if (fileType === "transcription") {
try {
const transcriptionContent = await bucket.getObject(
@@ -120,7 +119,6 @@ const app = new Hono()
}
}
- // Handle video/audio files
const videoPrefix = `${video.ownerId}/${videoId}/video/`;
const audioPrefix = `${video.ownerId}/${videoId}/audio/`;
@@ -161,7 +159,6 @@ const app = new Hono()
return c.redirect(playlistUrl);
}
- // Handle screen, video, and now audio types
let prefix;
switch (videoType) {
case "video":
diff --git a/apps/web/app/api/video/status/route.ts b/apps/web/app/api/video/status/route.ts
deleted file mode 100644
index 5f9cf359c..000000000
--- a/apps/web/app/api/video/status/route.ts
+++ /dev/null
@@ -1,187 +0,0 @@
-import { NextRequest } from "next/server";
-import { getCurrentUser } from "@cap/database/auth/session";
-import { db } from "@cap/database";
-import { videos, users } from "@cap/database/schema";
-import { VideoMetadata } from "@cap/database/types";
-import { eq } from "drizzle-orm";
-import { generateAiMetadata } from "@/actions/videos/generate-ai-metadata";
-import { transcribeVideo } from "@/actions/videos/transcribe";
-import { isAiGenerationEnabled } from "@/utils/flags";
-
-export const dynamic = "force-dynamic";
-
-const MAX_AI_PROCESSING_TIME = 10 * 60 * 1000;
-
-export async function GET(request: NextRequest) {
- try {
- const user = await getCurrentUser();
- const url = new URL(request.url);
- const videoId = url.searchParams.get("videoId");
-
- if (!user) {
- return Response.json({ auth: false }, { status: 401 });
- }
-
- if (!videoId) {
- return Response.json({ error: true, message: "Video ID not provided" }, { status: 400 });
- }
-
- const result = await db().select().from(videos).where(eq(videos.id, videoId));
- if (result.length === 0 || !result[0]) {
- return Response.json({ error: true, message: "Video not found" }, { status: 404 });
- }
-
- const video = result[0];
- const metadata: VideoMetadata = (video.metadata as VideoMetadata) || {};
-
- if (!video.transcriptionStatus) {
- console.log(`[Status API] Transcription not started for video ${videoId}, triggering transcription`);
- try {
- transcribeVideo(videoId, video.ownerId).catch(error => {
- console.error(`[Status API] Error starting transcription for video ${videoId}:`, error);
- });
-
- return Response.json({
- transcriptionStatus: "PROCESSING",
- aiProcessing: false,
- aiTitle: metadata.aiTitle || null,
- summary: metadata.summary || null,
- chapters: metadata.chapters || null,
- }, { status: 200 });
- } catch (error) {
- console.error(`[Status API] Error triggering transcription for video ${videoId}:`, error);
- return Response.json({
- transcriptionStatus: "ERROR",
- aiProcessing: false,
- aiTitle: metadata.aiTitle || null,
- summary: metadata.summary || null,
- chapters: metadata.chapters || null,
- error: "Failed to start transcription"
- }, { status: 500 });
- }
- }
-
- if (video.transcriptionStatus === "ERROR") {
- return Response.json({
- transcriptionStatus: "ERROR",
- aiProcessing: false,
- aiTitle: metadata.aiTitle || null,
- summary: metadata.summary || null,
- chapters: metadata.chapters || null,
- error: "Transcription failed"
- }, { status: 200 });
- }
-
- if (metadata.aiProcessing) {
- const updatedAtTime = new Date(video.updatedAt).getTime();
- const currentTime = new Date().getTime();
-
- if (currentTime - updatedAtTime > MAX_AI_PROCESSING_TIME) {
- console.log(`[Status API] AI processing appears stuck for video ${videoId} (${Math.round((currentTime - updatedAtTime) / 60000)} minutes), resetting flag`);
-
- await db()
- .update(videos)
- .set({
- metadata: {
- ...metadata,
- aiProcessing: false,
- generationError: "AI processing timed out and was reset"
- }
- })
- .where(eq(videos.id, videoId));
-
- const updatedResult = await db().select().from(videos).where(eq(videos.id, videoId));
- if (updatedResult.length > 0 && updatedResult[0]) {
- const updatedVideo = updatedResult[0];
- const updatedMetadata = updatedVideo.metadata as VideoMetadata || {};
-
- return Response.json({
- transcriptionStatus: updatedVideo.transcriptionStatus || null,
- aiProcessing: false,
- aiTitle: updatedMetadata.aiTitle || null,
- summary: updatedMetadata.summary || null,
- chapters: updatedMetadata.chapters || null,
- error: "AI processing timed out and was reset"
- }, { status: 200 });
- }
- }
- }
-
- if (
- video.transcriptionStatus === "COMPLETE" &&
- !metadata.aiProcessing &&
- !metadata.summary &&
- !metadata.chapters &&
- !metadata.generationError
- ) {
- console.log(`[Status API] Transcription complete but no AI data, checking feature flag for video owner ${video.ownerId}`);
-
- 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] && (await isAiGenerationEnabled(videoOwnerQuery[0]))) {
- console.log(`[Status API] Feature flag enabled, triggering AI generation for video ${videoId}`);
-
- (async () => {
- try {
- console.log(`[Status API] Starting AI metadata generation for video ${videoId}`);
- await generateAiMetadata(videoId, video.ownerId);
- console.log(`[Status API] AI metadata generation completed for video ${videoId}`);
- } catch (error) {
- console.error(`[Status API] Error generating AI metadata for video ${videoId}:`, error);
-
- try {
- const currentVideo = await db().select().from(videos).where(eq(videos.id, videoId));
- if (currentVideo.length > 0 && currentVideo[0]) {
- const currentMetadata = (currentVideo[0].metadata as VideoMetadata) || {};
- await db()
- .update(videos)
- .set({
- metadata: {
- ...currentMetadata,
- aiProcessing: false,
- generationError: error instanceof Error ? error.message : String(error)
- }
- })
- .where(eq(videos.id, videoId));
- }
- } catch (resetError) {
- console.error(`[Status API] Failed to reset AI processing flag for video ${videoId}:`, resetError);
- }
- }
- })();
-
- return Response.json({
- transcriptionStatus: video.transcriptionStatus || null,
- aiProcessing: true,
- aiTitle: metadata.aiTitle || null,
- summary: metadata.summary || null,
- chapters: metadata.chapters || null,
- }, { status: 200 });
- } else {
- const videoOwner = videoOwnerQuery[0];
- console.log(`[Status API] AI generation feature disabled for video owner ${video.ownerId} (email: ${videoOwner?.email}, pro: ${videoOwner?.stripeSubscriptionStatus})`);
- }
- }
-
- return Response.json({
- transcriptionStatus: video.transcriptionStatus || null,
- aiProcessing: metadata.aiProcessing || false,
- aiTitle: metadata.aiTitle || null,
- summary: metadata.summary || null,
- chapters: metadata.chapters || null,
- }, { status: 200 });
- } catch (error) {
- console.error("Error in video status endpoint:", error);
- return Response.json({
- error: true,
- message: "An unexpected error occurred"
- }, { status: 500 });
- }
-}
\ No newline at end of file
diff --git a/apps/web/app/s/[videoId]/Share.tsx b/apps/web/app/s/[videoId]/Share.tsx
index fef184e5e..61f5871d1 100644
--- a/apps/web/app/s/[videoId]/Share.tsx
+++ b/apps/web/app/s/[videoId]/Share.tsx
@@ -1,6 +1,7 @@
"use client";
import { getVideoAnalytics } from "@/actions/videos/get-analytics";
+import { getVideoStatus, VideoStatusResult } from "@/actions/videos/get-status";
import { userSelectProps } from "@cap/database/auth/session";
import { comments as commentsSchema, videos } from "@cap/database/schema";
import { useQuery } from "@tanstack/react-query";
@@ -51,14 +52,6 @@ interface ShareProps {
aiUiEnabled: boolean;
}
-interface VideoStatusResponse {
- transcriptionStatus?: "PROCESSING" | "COMPLETE" | "ERROR" | null;
- aiProcessing?: boolean;
- aiTitle?: string | null;
- summary?: string | null;
- chapters?: { title: string; start: number }[] | null;
-}
-
const useVideoStatus = (
videoId: string,
aiGenerationEnabled: boolean,
@@ -74,12 +67,8 @@ const useVideoStatus = (
) => {
return useQuery({
queryKey: ["videoStatus", videoId],
- queryFn: async (): Promise<VideoStatusResponse> => {
- const res = await fetch(`/api/video/status?videoId=${videoId}`);
- if (!res.ok) {
- throw new Error(`HTTP ${res.status}: ${res.statusText}`);
- }
- return res.json();
+ queryFn: async (): Promise<VideoStatusResult> => {
+ return await getVideoStatus(videoId);
},
initialData: initialData
? {
@@ -92,6 +81,7 @@ const useVideoStatus = (
aiTitle: initialData.aiData?.title || null,
summary: initialData.aiData?.summary || null,
chapters: initialData.aiData?.chapters || null,
+ generationError: null,
}
: undefined,
refetchInterval: (query) => {
@@ -192,6 +182,7 @@ export const Share = ({
summary: videoStatus?.summary || null,
chapters: videoStatus?.chapters || null,
processing: videoStatus?.aiProcessing || false,
+ generationError: videoStatus?.generationError || null,
}),
[videoStatus]
);
@@ -210,6 +201,9 @@ export const Share = ({
}
if (transcriptionStatus === "COMPLETE") {
+ if (aiData.generationError) {
+ return false;
+ }
if (aiData.processing === true) {
return true;
}
@@ -279,8 +273,7 @@ export const Share = ({
<div className="mt-4 hidden lg:block">
{aiLoading &&
(transcriptionStatus === "PROCESSING" ||
- transcriptionStatus === "COMPLETE" ||
- transcriptionStatus === "ERROR") && (
+ transcriptionStatus === "COMPLETE") && (
<div className="p-4 new-card-style animate-pulse">
<div className="space-y-6">
<div>
diff --git a/apps/web/app/s/[videoId]/_components/MP4VideoPlayer.tsx b/apps/web/app/s/[videoId]/_components/MP4VideoPlayer.tsx
index bcc416b1a..d3d8ceee1 100644
--- a/apps/web/app/s/[videoId]/_components/MP4VideoPlayer.tsx
+++ b/apps/web/app/s/[videoId]/_components/MP4VideoPlayer.tsx
@@ -21,13 +21,13 @@ export const MP4VideoPlayer = memo(
const startTime = useRef<number>(Date.now());
const [isLoaded, setIsLoaded] = useState(false);
const [currentSrc, setCurrentSrc] = useState(videoSrc);
- const lastAttemptTime = useRef<number>(Date.now());
+ const [hasError, setHasError] = useState(false);
+ const maxRetries = 3;
useImperativeHandle(ref, () => videoRef.current as HTMLVideoElement);
const fetchNewUrl = useCallback(async () => {
try {
- // Add timestamp to prevent caching
const timestamp = new Date().getTime();
const urlWithTimestamp = videoSrc.includes("?")
? `${videoSrc}&_t=${timestamp}`
@@ -36,17 +36,13 @@ export const MP4VideoPlayer = memo(
const response = await fetch(urlWithTimestamp, { method: "HEAD" });
if (response.redirected) {
- console.log({ response });
- // If the API redirected us, use the redirected URL
setCurrentSrc(response.url);
return response.url;
} else {
- // If no redirect (which is unusual for desktopMP4), just use the original URL
return urlWithTimestamp;
}
} catch (error) {
console.error("Error fetching new video URL:", error);
- // Return the original URL with timestamp if fetch fails
const timestamp = new Date().getTime();
return videoSrc.includes("?")
? `${videoSrc}&_t=${timestamp}`
@@ -56,25 +52,24 @@ export const MP4VideoPlayer = memo(
const reloadVideo = useCallback(async () => {
const video = videoRef.current;
- if (!video) return;
+ if (!video || retryCount.current >= maxRetries) return;
+
+ console.log(
+ `Reloading video (attempt ${retryCount.current + 1}/${maxRetries})`
+ );
- // Store the current position before reloading
const currentPosition = video.currentTime;
const wasPlaying = !video.paused;
- // Get a fresh URL from the API
const newUrl = await fetchNewUrl();
- // Update the video source
const sourceElement = video.querySelector("source");
if (sourceElement) {
sourceElement.setAttribute("src", newUrl);
}
- // Reset video and reload with new source
video.load();
- // Restore position and play state after loading
if (currentPosition > 0) {
const restorePosition = () => {
video.currentTime = currentPosition;
@@ -88,65 +83,54 @@ export const MP4VideoPlayer = memo(
video.addEventListener("canplay", restorePosition);
}
- // Update the last attempt time
- lastAttemptTime.current = Date.now();
- }, [fetchNewUrl]);
+ retryCount.current += 1;
+ }, [fetchNewUrl, maxRetries]);
const setupRetry = useCallback(() => {
- // Clear any existing timeout
if (retryTimeout.current) {
clearTimeout(retryTimeout.current);
}
- // If we've been trying for more than 2 minutes, stop retrying
+ if (retryCount.current >= maxRetries) {
+ console.error(`Video failed to load after ${maxRetries} attempts`);
+ setHasError(true);
+ return;
+ }
+
const elapsedMs = Date.now() - startTime.current;
- if (elapsedMs > 120000) {
- console.error("Video failed to load after 2 minutes of retries");
+ if (elapsedMs > 60000) {
+ console.error("Video failed to load after 1 minute");
+ setHasError(true);
return;
}
- // Progressive retry strategy:
- // - First attempt: immediate retry (10ms delay)
- // - First 1 second: retry every 200ms
- // - First 5 seconds: retry every 300ms
- // - After 5 seconds: retry every 1000ms
let retryInterval: number;
-
if (retryCount.current === 0) {
- retryInterval = 10; // Almost immediate first retry
- } else if (elapsedMs < 1000) {
- retryInterval = 200; // Very aggressive for first second
- } else if (elapsedMs < 5000) {
- retryInterval = 300; // Aggressive for first 5 seconds
+ retryInterval = 2000;
+ } else if (retryCount.current === 1) {
+ retryInterval = 5000;
} else {
- retryInterval = 1000; // Every second after that
+ retryInterval = 10000;
}
- retryCount.current += 1;
retryTimeout.current = setTimeout(() => {
- console.log(
- `Retry attempt ${retryCount.current} for video (interval: ${retryInterval}ms)`
- );
reloadVideo();
}, retryInterval);
- }, [reloadVideo]);
+ }, [reloadVideo, maxRetries]);
- // Reset everything when video source changes
useEffect(() => {
setCurrentSrc(videoSrc);
setIsLoaded(false);
+ setHasError(false);
retryCount.current = 0;
startTime.current = Date.now();
- lastAttemptTime.current = Date.now();
- // Clear any existing timeout
if (retryTimeout.current) {
clearTimeout(retryTimeout.current);
retryTimeout.current = null;
}
}, [videoSrc]);
- // Main video loading and event handling
useEffect(() => {
const video = videoRef.current;
if (!video) return;
@@ -154,11 +138,10 @@ export const MP4VideoPlayer = memo(
const handleLoadedData = () => {
console.log("Video loaded successfully");
setIsLoaded(true);
- // Dispatch canplay event to notify parent component
+ setHasError(false);
if (videoRef.current) {
videoRef.current.dispatchEvent(new Event("canplay"));
}
- // Clear any retry timeouts if video is loaded
if (retryTimeout.current) {
clearTimeout(retryTimeout.current);
retryTimeout.current = null;
@@ -166,60 +149,72 @@ export const MP4VideoPlayer = memo(
};
const handleLoadedMetadata = () => {
- // We'll let the loadeddata event handle dispatching canplay
- // This ensures we don't trigger the event too early
+ if (videoRef.current) {
+ videoRef.current.dispatchEvent(new Event("loadedmetadata"));
+ }
};
const handleError = (e: ErrorEvent) => {
console.error("Video loading error:", e);
- if (!isLoaded) {
+ if (!isLoaded && !hasError) {
setupRetry();
}
};
- const handleStalled = () => {
- console.log("Video stalled, retrying...");
- if (!isLoaded) {
- setupRetry();
+ const handleCanPlay = () => {
+ setIsLoaded(true);
+ setHasError(false);
+ if (retryTimeout.current) {
+ clearTimeout(retryTimeout.current);
+ retryTimeout.current = null;
}
};
- // Add event listeners
video.addEventListener("loadeddata", handleLoadedData);
video.addEventListener("loadedmetadata", handleLoadedMetadata);
video.addEventListener("error", handleError as EventListener);
- video.addEventListener("stalled", handleStalled);
-
- // Initial load
- reloadVideo();
-
- // Setup a periodic check for videos that don't trigger error events
- // but aren't loading either - check more frequently
- const loadingCheckInterval = setInterval(() => {
- const now = Date.now();
- const timeSinceLastAttempt = now - lastAttemptTime.current;
-
- // If it's been more than 2 seconds since our last attempt and video isn't loaded
- if (!isLoaded && timeSinceLastAttempt > 2000) {
- console.log("Video loading timed out, retrying...");
- setupRetry();
- }
- }, 2000);
+ video.addEventListener("canplay", handleCanPlay);
+
+ if (!isLoaded && !hasError && retryCount.current === 0) {
+ const initialTimeout = setTimeout(() => {
+ if (!isLoaded && !hasError) {
+ console.log(
+ "Video taking longer than expected to load, attempting reload"
+ );
+ setupRetry();
+ }
+ }, 10000);
+
+ return () => {
+ clearTimeout(initialTimeout);
+ video.removeEventListener("loadeddata", handleLoadedData);
+ video.removeEventListener("loadedmetadata", handleLoadedMetadata);
+ video.removeEventListener("error", handleError as EventListener);
+ video.removeEventListener("canplay", handleCanPlay);
+ if (retryTimeout.current) {
+ clearTimeout(retryTimeout.current);
+ }
+ };
+ }
return () => {
- // Cleanup event listeners
video.removeEventListener("loadeddata", handleLoadedData);
video.removeEventListener("loadedmetadata", handleLoadedMetadata);
video.removeEventListener("error", handleError as EventListener);
- video.removeEventListener("stalled", handleStalled);
-
- // Clear intervals and timeouts
- clearInterval(loadingCheckInterval);
+ video.removeEventListener("canplay", handleCanPlay);
if (retryTimeout.current) {
clearTimeout(retryTimeout.current);
}
};
- }, [currentSrc, isLoaded, reloadVideo, setupRetry]);
+ }, [currentSrc, isLoaded, hasError, setupRetry]);
+
+ if (hasError) {
+ return (
+ <div className="flex items-center justify-center w-full h-full bg-black text-white">
+ <p>Unable to load video</p>
+ </div>
+ );
+ }
return (
<video
diff --git a/apps/web/app/s/[videoId]/_components/ShareVideo.tsx b/apps/web/app/s/[videoId]/_components/ShareVideo.tsx
index d8bbc4ba6..c14ef2fd4 100644
--- a/apps/web/app/s/[videoId]/_components/ShareVideo.tsx
+++ b/apps/web/app/s/[videoId]/_components/ShareVideo.tsx
@@ -1,6 +1,7 @@
import { UpgradeModal } from "@/components/UpgradeModal";
import { usePublicEnv } from "@/utils/public-env";
import { useApiClient } from "@/utils/web-api";
+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";
@@ -28,6 +29,7 @@ import { toast } from "sonner";
import { fromVtt, Subtitle } from "subtitles-parser-vtt";
import { MP4VideoPlayer } from "./MP4VideoPlayer";
import { VideoPlayer } from "./VideoPlayer";
+import { useQuery } from "@tanstack/react-query";
declare global {
interface Window {
@@ -78,11 +80,7 @@ export const ShareVideo = forwardRef<
const [videoMetadataLoaded, setVideoMetadataLoaded] = useState(false);
const [videoReadyToPlay, setVideoReadyToPlay] = useState(false);
const [overlayVisible, setOverlayVisible] = useState(true);
- const [subtitles, setSubtitles] = useState<Subtitle[]>([]);
const [subtitlesVisible, setSubtitlesVisible] = useState(true);
- const [isTranscriptionProcessing, setIsTranscriptionProcessing] = useState(
- data.transcriptionStatus === "PROCESSING"
- );
const [upgradeModalOpen, setUpgradeModalOpen] = useState(false);
const [tempOverlayVisible, setTempOverlayVisible] = useState(false);
@@ -109,7 +107,22 @@ export const ShareVideo = forwardRef<
const lastUpdateTimeRef = useRef<number>(0);
const lastMousePosRef = useRef<number>(0);
- const [isLargeScreen, setIsLargeScreen] = useState(false);
+ const isLargeScreen = useScreenSize();
+
+ // Use TanStack Query for video source validation
+ const { data: videoSourceData } = useVideoSourceValidation(
+ data,
+ videoMetadataLoaded
+ );
+
+ // Update isMP4Source based on query result
+ useEffect(() => {
+ if (videoSourceData) {
+ setIsMP4Source(videoSourceData.isMP4Source);
+ } else if (videoMetadataLoaded) {
+ setIsMP4Source(data.source.type === "desktopMP4");
+ }
+ }, [videoSourceData, videoMetadataLoaded, data.source.type]);
useEffect(() => {
if (videoRef.current) {
@@ -121,29 +134,6 @@ export const ShareVideo = forwardRef<
}
}, [ref]);
- useEffect(() => {
- if (!videoMetadataLoaded) return;
-
- setIsMP4Source(data.source.type === "desktopMP4");
-
- if (data.source.type === "desktopMP4") {
- const thumbUrl = `/api/playlist?userId=${data.ownerId}&videoId=${data.id}&thumbnailTime=0`;
-
- fetch(thumbUrl, { method: "HEAD" })
- .then((response) => {
- if (response.ok) {
- setIsMP4Source(true);
- } else {
- setIsMP4Source(false);
- }
- })
- .catch((error) => {
- console.error("Error checking thumbnails:", error);
- setIsMP4Source(false);
- });
- }
- }, [videoMetadataLoaded, data.ownerId, data.id, data.source.type]);
-
const showControls = () => {
setOverlayVisible(true);
if (hideControlsTimeoutRef.current) {
@@ -217,11 +207,6 @@ export const ShareVideo = forwardRef<
}
}, [isHoveringControls, isPlaying, isHoveringVideo]);
- useEffect(() => {
- if (videoMetadataLoaded) {
- }
- }, [videoMetadataLoaded]);
-
useEffect(() => {
const handleShortcuts = (e: KeyboardEvent) => {
const target = e.target as HTMLElement;
@@ -872,44 +857,17 @@ export const ShareVideo = forwardRef<
const publicEnv = usePublicEnv();
const apiClient = useApiClient();
- useEffect(() => {
- const fetchSubtitles = async () => {
- let transcriptionUrl;
-
- if (data.bucket && data.awsBucket !== publicEnv.awsBucket) {
- transcriptionUrl = `/api/playlist?userId=${data.ownerId}&videoId=${data.id}&fileType=transcription`;
- } else {
- transcriptionUrl = `${publicEnv.s3BucketUrl}/${data.ownerId}/${data.id}/transcription.vtt`;
- }
-
- try {
- const response = await fetch(transcriptionUrl);
- const text = await response.text();
- const parsedSubtitles = fromVtt(text);
- setSubtitles(parsedSubtitles);
- setIsTranscriptionProcessing(false);
- } catch (error) {
- console.error("Error fetching subtitles:", error);
- setIsTranscriptionProcessing(false);
- }
- };
-
- if (data.transcriptionStatus === "PROCESSING") {
- setIsTranscriptionProcessing(true);
- } else if (data.transcriptionStatus === "COMPLETE") {
- fetchSubtitles();
- } else if (data.transcriptionStatus === "ERROR") {
- setIsTranscriptionProcessing(false);
- }
- }, [
- data.transcriptionStatus,
- data.bucket,
- data.awsBucket,
- data.ownerId,
+ const { data: transcriptContent, error: transcriptError } = useTranscript(
data.id,
- publicEnv.awsBucket,
- publicEnv.s3BucketUrl,
- ]);
+ data.transcriptionStatus
+ );
+
+ // Use custom hook for transcription processing
+ const { isTranscriptionProcessing, subtitles } = useTranscriptionProcessing(
+ data,
+ transcriptContent,
+ transcriptError
+ );
const currentSubtitle = subtitles.find(
(subtitle) =>
@@ -917,18 +875,6 @@ export const ShareVideo = forwardRef<
parseSubTime(subtitle.endTime) >= currentTime
);
- useEffect(() => {
- const checkScreenSize = () => {
- setIsLargeScreen(window.innerWidth >= 1024);
- };
-
- checkScreenSize();
-
- window.addEventListener("resize", checkScreenSize);
-
- return () => window.removeEventListener("resize", checkScreenSize);
- }, []);
-
useEffect(() => {
if (previewCanvasRef.current && isLargeScreen) {
const canvas = previewCanvasRef.current;
@@ -965,14 +911,6 @@ export const ShareVideo = forwardRef<
detectSafari();
}, []);
- useEffect(() => {
- if (data.transcriptionStatus === "PROCESSING") {
- setIsTranscriptionProcessing(true);
- } else if (data.transcriptionStatus === "ERROR") {
- setIsTranscriptionProcessing(false);
- }
- }, [data.transcriptionStatus]);
-
if (data.jobStatus === "ERROR") {
return (
<div className="flex overflow-hidden justify-center items-center w-full h-full rounded-lg">
@@ -1578,3 +1516,85 @@ export const ShareVideo = forwardRef<
</div>
);
});
+
+// Custom hook for video source validation using TanStack Query
+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, // 5 minutes
+ gcTime: 10 * 60 * 1000, // 10 minutes
+ });
+};
+
+// Custom hook for screen size detection
+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;
+};
+
+// Custom hook for transcription processing
+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(
+ "[ShareVideo] 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/s/[videoId]/_components/Sidebar.tsx b/apps/web/app/s/[videoId]/_components/Sidebar.tsx
index 7fc49003d..ee52f2375 100644
--- a/apps/web/app/s/[videoId]/_components/Sidebar.tsx
+++ b/apps/web/app/s/[videoId]/_components/Sidebar.tsx
@@ -133,7 +133,7 @@ export const Sidebar: React.FC<SidebarProps> = ({
/>
);
case "transcript":
- return <Transcript data={data} onSeek={onSeek} />;
+ return <Transcript data={data} onSeek={onSeek} user={user} />;
case "settings":
return <Settings />;
default:
diff --git a/apps/web/app/s/[videoId]/_components/tabs/Summary.tsx b/apps/web/app/s/[videoId]/_components/tabs/Summary.tsx
index a48d5ef9c..f8bae5787 100644
--- a/apps/web/app/s/[videoId]/_components/tabs/Summary.tsx
+++ b/apps/web/app/s/[videoId]/_components/tabs/Summary.tsx
@@ -79,7 +79,6 @@ export const Summary: React.FC<SummaryProps> = ({
);
useEffect(() => {
- console.log("[Summary] Received initialAiData update:", initialAiData);
if (initialAiData) {
setAiData(initialAiData);
setIsLoading(aiGenerationEnabled && initialAiData.processing === true);
@@ -100,15 +99,6 @@ export const Summary: React.FC<SummaryProps> = ({
})
: false;
- console.log("[Summary] Current state:", {
- isLoading,
- aiData,
- initialAiData,
- aiUiEnabled,
- aiGenerationEnabled,
- hasProAccess,
- });
-
const hasExistingAiData =
aiData?.summary || (aiData?.chapters && aiData.chapters.length > 0);
diff --git a/apps/web/app/s/[videoId]/_components/tabs/Transcript.tsx b/apps/web/app/s/[videoId]/_components/tabs/Transcript.tsx
index 0f2943d20..44b9f0825 100644
--- a/apps/web/app/s/[videoId]/_components/tabs/Transcript.tsx
+++ b/apps/web/app/s/[videoId]/_components/tabs/Transcript.tsx
@@ -2,12 +2,15 @@
import { videos } from "@cap/database/schema";
import { useState, useEffect } from "react";
-import { MessageSquare } from "lucide-react";
-import { usePublicEnv } from "@/utils/public-env";
+import { MessageSquare, Edit3, Check, X } from "lucide-react";
+import { editTranscriptEntry } from "@/actions/videos/edit-transcript";
+import { useTranscript, useInvalidateTranscript } from "hooks/use-transcript";
+import { Button } from "@cap/ui";
interface TranscriptProps {
data: typeof videos.$inferSelect;
onSeek?: (time: number) => void;
+ user?: { id: string } | null;
}
interface TranscriptEntry {
@@ -91,7 +94,12 @@ const parseVTT = (vttContent: string): TranscriptEntry[] => {
}
if (currentEntry.timestamp && !currentEntry.text) {
- currentEntry.text = trimmedLine;
+ const textContent =
+ trimmedLine.startsWith('"') && trimmedLine.endsWith('"')
+ ? trimmedLine.slice(1, -1)
+ : trimmedLine;
+
+ currentEntry.text = textContent;
if (
currentEntry.id !== undefined &&
currentEntry.timestamp &&
@@ -104,64 +112,75 @@ const parseVTT = (vttContent: string): TranscriptEntry[] => {
}
}
- return entries.sort((a, b) => a.startTime - b.startTime);
+ const sortedEntries = entries.sort((a, b) => a.startTime - b.startTime);
+ return sortedEntries;
};
-export const Transcript: React.FC<TranscriptProps> = ({ data, onSeek }) => {
+export const Transcript: React.FC<TranscriptProps> = ({
+ data,
+ onSeek,
+ user,
+}) => {
const [transcriptData, setTranscriptData] = useState<TranscriptEntry[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [selectedEntry, setSelectedEntry] = useState<number | null>(null);
const [isTranscriptionProcessing, setIsTranscriptionProcessing] =
useState(false);
const [hasTimedOut, setHasTimedOut] = useState(false);
+ const [editingEntry, setEditingEntry] = useState<number | null>(null);
+ const [editText, setEditText] = useState<string>("");
+ const [isSaving, setIsSaving] = useState(false);
- const publicEnv = usePublicEnv();
+ const {
+ data: transcriptContent,
+ isLoading: isTranscriptLoading,
+ error: transcriptError,
+ } = useTranscript(data.id, data.transcriptionStatus);
- useEffect(() => {
- const fetchTranscript = async () => {
- let transcriptionUrl;
+ const invalidateTranscript = useInvalidateTranscript();
- if (data.bucket && data.awsBucket !== publicEnv.awsBucket) {
- transcriptionUrl = `/api/playlist?userId=${data.ownerId}&videoId=${data.id}&fileType=transcription`;
+ useEffect(() => {
+ if (transcriptContent) {
+ const parsed = parseVTT(transcriptContent);
+ setTranscriptData(parsed);
+ setIsTranscriptionProcessing(false);
+ setIsLoading(false);
+ } else if (transcriptError) {
+ console.error(
+ "[Transcript] Transcript error from React Query:",
+ transcriptError.message
+ );
+ if (transcriptError.message === "TRANSCRIPT_NOT_READY") {
+ setIsTranscriptionProcessing(true);
} else {
- transcriptionUrl = `${publicEnv.s3BucketUrl}/${data.ownerId}/${data.id}/transcription.vtt`;
- }
-
- try {
- const response = await fetch(transcriptionUrl);
- const vttContent = await response.text();
- const parsed = parseVTT(vttContent);
- setTranscriptData(parsed);
setIsTranscriptionProcessing(false);
- } catch (error) {
- console.error("Error loading transcript:", error);
}
setIsLoading(false);
- };
+ }
+ }, [transcriptContent, transcriptError]);
- console.log("[Transcript] Transcription status:", data.transcriptionStatus);
+ useEffect(() => {
+ if (isTranscriptLoading) {
+ setIsLoading(true);
+ }
+ }, [isTranscriptLoading]);
+ useEffect(() => {
const videoCreationTime = new Date(data.createdAt).getTime();
const fiveMinutesInMs = 5 * 60 * 1000;
const isVideoOlderThanFiveMinutes =
Date.now() - videoCreationTime > fiveMinutesInMs;
- if (data.transcriptionStatus === "COMPLETE") {
- console.log("[Transcript] Transcription complete, fetching transcript");
- fetchTranscript();
- } else if (data.transcriptionStatus === "PROCESSING") {
- console.log("[Transcript] Transcription in progress");
+ if (data.transcriptionStatus === "PROCESSING") {
setIsTranscriptionProcessing(true);
setIsLoading(true);
} else if (data.transcriptionStatus === "ERROR") {
- console.log("[Transcript] Transcription error");
setIsTranscriptionProcessing(false);
setIsLoading(false);
} else if (isVideoOlderThanFiveMinutes && !data.transcriptionStatus) {
setIsLoading(false);
setHasTimedOut(true);
- } else {
- // Transcription hasn't started or status unknown, start our own polling
+ } else if (!data.transcriptionStatus) {
const startTime = Date.now();
const maxDuration = 2 * 60 * 1000;
@@ -178,7 +197,6 @@ export const Transcript: React.FC<TranscriptProps> = ({ data, onSeek }) => {
if (transcriptionStatus === "PROCESSING") {
setIsTranscriptionProcessing(true);
} else if (transcriptionStatus === "COMPLETE") {
- fetchTranscript();
clearInterval(intervalId);
} else if (transcriptionStatus === "ERROR") {
clearInterval(intervalId);
@@ -189,40 +207,18 @@ export const Transcript: React.FC<TranscriptProps> = ({ data, onSeek }) => {
return () => clearInterval(intervalId);
}
- }, [
- data.id,
- data.ownerId,
- data.bucket,
- data.awsBucket,
- data.transcriptionStatus,
- data.createdAt,
- publicEnv.awsBucket,
- publicEnv.s3BucketUrl,
- ]);
+ }, [data.id, data.transcriptionStatus, data.createdAt]);
const handleReset = () => {
setIsLoading(true);
- const fetchTranscript = async () => {
- const transcriptionUrl =
- data.bucket && data.awsBucket !== publicEnv.awsBucket
- ? `/api/playlist?userId=${data.ownerId}&videoId=${data.id}&fileType=transcription`
- : `${publicEnv.s3BucketUrl}/${data.ownerId}/${data.id}/transcription.vtt`;
-
- try {
- const response = await fetch(transcriptionUrl);
- const vttContent = await response.text();
- const parsed = parseVTT(vttContent);
- setTranscriptData(parsed);
- } catch (error) {
- console.error("Error resetting transcript:", error);
- }
- setIsLoading(false);
- };
-
- fetchTranscript();
+ invalidateTranscript(data.id);
};
const handleTranscriptClick = (entry: TranscriptEntry) => {
+ if (editingEntry === entry.id) {
+ return;
+ }
+
setSelectedEntry(entry.id);
if (onSeek) {
@@ -230,6 +226,62 @@ export const Transcript: React.FC<TranscriptProps> = ({ data, onSeek }) => {
}
};
+ const startEditing = (entry: TranscriptEntry) => {
+ setEditingEntry(entry.id);
+ setEditText(entry.text);
+ };
+
+ const cancelEditing = () => {
+ setEditingEntry(null);
+ setEditText("");
+ };
+
+ const saveEdit = async () => {
+ if (!editingEntry || !editText.trim()) {
+ return;
+ }
+
+ const originalEntry = transcriptData.find(
+ (entry) => entry.id === editingEntry
+ );
+
+ setIsSaving(true);
+ try {
+ const result = await editTranscriptEntry(data.id, editingEntry, editText);
+
+ if (result.success) {
+ setTranscriptData((prev) =>
+ prev.map((entry) =>
+ entry.id === editingEntry
+ ? { ...entry, text: editText.trim() }
+ : entry
+ )
+ );
+ setEditingEntry(null);
+ setEditText("");
+ invalidateTranscript(data.id);
+ } else {
+ console.error("[Transcript] Failed to save transcript edit:", {
+ entryId: editingEntry,
+ videoId: data.id,
+ errorMessage: result.message,
+ result,
+ });
+ }
+ } catch (error) {
+ console.error("[Transcript] Error saving transcript edit:", {
+ entryId: editingEntry,
+ videoId: data.id,
+ error: error instanceof Error ? error.message : error,
+ stack: error instanceof Error ? error.stack : undefined,
+ });
+ } finally {
+ setIsSaving(false);
+ }
+ };
+
+ const canEdit = user?.id === data.ownerId;
+
if (isLoading) {
return (
<div className="flex justify-center items-center h-full">
@@ -313,15 +365,81 @@ export const Transcript: React.FC<TranscriptProps> = ({ data, onSeek }) => {
{transcriptData.map((entry) => (
<div
key={entry.id}
- className={`group rounded-lg p-2 transition-colors cursor-pointer ${
- selectedEntry === entry.id ? "bg-gray-2" : "hover:bg-gray-2"
- }`}
+ className={`group rounded-lg transition-colors ${
+ editingEntry === entry.id
+ ? "bg-gray-1 border border-gray-4 p-3"
+ : selectedEntry === entry.id
+ ? "bg-gray-2 p-3"
+ : "hover:bg-gray-2 p-3"
+ } ${editingEntry === entry.id ? "" : "cursor-pointer"}`}
onClick={() => handleTranscriptClick(entry)}
>
- <div className="mb-1 text-sm text-gray-8 font-semibold">
- {entry.timestamp}
+ <div className="flex justify-between items-start mb-2">
+ <div className="text-xs text-gray-8 font-medium">
+ {entry.timestamp}
+ </div>
+ {canEdit && editingEntry !== entry.id && (
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ startEditing(entry);
+ }}
+ className="opacity-0 group-hover:opacity-100 p-1.5 hover:bg-gray-3 rounded-md transition-all duration-200"
+ title="Edit transcript"
+ >
+ <Edit3 className="w-3.5 h-3.5 text-gray-9" />
+ </button>
+ )}
</div>
- <div className="text-sm text-gray-12">{entry.text}</div>
+
+ {editingEntry === entry.id ? (
+ <div className="space-y-3">
+ <div className="rounded-lg bg-gray-1 border border-gray-4 p-3">
+ <textarea
+ value={editText}
+ onChange={(e) => setEditText(e.target.value)}
+ className="w-full text-sm leading-relaxed text-gray-12 bg-transparent placeholder:text-gray-8 resize-none focus:outline-none"
+ rows={Math.max(2, Math.ceil(editText.length / 60))}
+ autoFocus
+ onClick={(e) => e.stopPropagation()}
+ placeholder="Edit transcript text..."
+ />
+ </div>
+ <div className="flex gap-2 justify-end">
+ <Button
+ onClick={(e) => {
+ e.stopPropagation();
+ cancelEditing();
+ }}
+ disabled={isSaving}
+ variant="white"
+ size="xs"
+ className="min-w-[70px]"
+ >
+ <X className="w-3 h-3 mr-1" />
+ Cancel
+ </Button>
+ <Button
+ onClick={(e) => {
+ e.stopPropagation();
+ saveEdit();
+ }}
+ disabled={isSaving || !editText.trim()}
+ variant="primary"
+ size="xs"
+ className="min-w-[70px]"
+ spinner={isSaving}
+ >
+ <Check className="w-3 h-3 mr-1" />
+ Save
+ </Button>
+ </div>
+ </div>
+ ) : (
+ <div className="text-sm leading-relaxed text-gray-12">
+ {entry.text}
+ </div>
+ )}
</div>
))}
</div>
diff --git a/apps/web/hooks/use-transcript.ts b/apps/web/hooks/use-transcript.ts
new file mode 100644
index 000000000..84242c36c
--- /dev/null
+++ b/apps/web/hooks/use-transcript.ts
@@ -0,0 +1,32 @@
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { getTranscript } from "@/actions/videos/get-transcript";
+
+export const useTranscript = (videoId: string, transcriptionStatus?: string | null) => {
+ return useQuery({
+ queryKey: ["transcript", videoId],
+ queryFn: async () => {
+ const result = await getTranscript(videoId);
+
+ if (result.success && result.content) {
+ return result.content;
+ } else {
+ console.error("[useTranscript] Failed to fetch transcript:", result.message);
+ if (result.message === "Transcript is not ready yet") {
+ throw new Error("TRANSCRIPT_NOT_READY");
+ }
+ throw new Error(result.message);
+ }
+ },
+ enabled: transcriptionStatus === "COMPLETE",
+ staleTime: 0,
+ refetchOnWindowFocus: false,
+ });
+};
+
+export const useInvalidateTranscript = () => {
+ const queryClient = useQueryClient();
+
+ return (videoId: string) => {
+ queryClient.invalidateQueries({ queryKey: ["transcript", videoId] });
+ };
+};
\ No newline at end of file