File size: 2,335 Bytes
ceb943f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
"use server";

import { auth } from "@/lib/auth";
import { headers } from "next/headers";
import { db } from "@/lib/db";
import { youtubeVideos, youtubeChannels } from "@/lib/db/schema";
import { eq, and } from "drizzle-orm";
import { inngest } from "@/inngest/client";

export interface TriggerObjectDetectionResult {
    success: boolean;
    error?: string;
}

/**
 * Server action to manually trigger object detection for a specific video.
 * 
 * @param videoId - Internal database video ID
 * @returns Result object with success status or error message
 */
export async function triggerObjectDetectionAction(
    videoId: string
): Promise<TriggerObjectDetectionResult> {
    // 1. Authenticate user
    const session = await auth.api.getSession({
        headers: await headers(),
    });

    if (!session || !session.user) {
        return {
            success: false,
            error: "Unauthorized",
        };
    }

    try {
        // 2. Verify video exists and user owns the channel
        const [videoWithChannel] = await db
            .select({
                id: youtubeVideos.id,
                ytVideoId: youtubeVideos.videoId,
                creatorId: youtubeChannels.creatorId,
            })
            .from(youtubeVideos)
            .innerJoin(youtubeChannels, eq(youtubeVideos.channelId, youtubeChannels.id))
            .where(
                and(
                    eq(youtubeVideos.id, videoId),
                    eq(youtubeChannels.creatorId, session.user.id)
                )
            )
            .limit(1);

        if (!videoWithChannel) {
            return {
                success: false,
                error: "Video not found or permission denied",
            };
        }

        // 3. Trigger Inngest workflow
        await inngest.send({
            name: 'youtube/video.detect-objects',
            data: {
                videoId: videoWithChannel.id,
                videoUrl: `https://www.youtube.com/watch?v=${videoWithChannel.ytVideoId}`,
            },
        });

        return {
            success: true,
        };
    } catch (error) {
        console.error("Failed to trigger object detection:", error);
        return {
            success: false,
            error: "An unexpected error occurred while triggering object detection.",
        };
    }
}