Spaces:
Runtime error
Runtime error
File size: 9,941 Bytes
304bdf5 5480d48 304bdf5 5480d48 304bdf5 5480d48 85f636b 5480d48 85f636b 5480d48 85f636b 5480d48 85f636b 5480d48 85f636b 5480d48 304bdf5 5480d48 304bdf5 5480d48 304bdf5 5480d48 304bdf5 85f636b 304bdf5 85f636b 304bdf5 5480d48 | 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 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 | "use server";
import { db } from "@/lib/db";
import { youtubeVideos, detectedObjects, marketplaceMatches, adminModeration } from "@/lib/db/schema";
import { eq, and, inArray, desc } from "drizzle-orm";
import { auth } from "@/lib/auth";
import { headers } from "next/headers";
import { inngest } from "@/inngest/client";
import { revalidatePath } from "next/cache";
async function ensureAdmin() {
const session = await auth.api.getSession({
headers: await headers()
});
const adminEmails = process.env.ADMIN_EMAILS?.split(",") || [];
if (!session?.user?.email || !adminEmails.includes(session.user.email)) {
throw new Error("Unauthorized");
}
}
export async function getAnalysisQueue(status?: string) {
await ensureAdmin();
const statuses = status
? [status]
: ['pending_analysis', 'awaiting_approval', 'in_progress'];
const queue = await db.query.youtubeVideos.findMany({
where: inArray(youtubeVideos.scanStatus, statuses as any),
with: {
channel: true
},
orderBy: (youtubeVideos, { desc }) => [desc(youtubeVideos.createdAt)]
});
return queue;
}
/**
* Triggers AI analysis for a video that is currently in 'pending_analysis'.
*/
export async function triggerAIAnalysisAction(videoId: string) {
await ensureAdmin();
const video = await db.query.youtubeVideos.findFirst({
where: eq(youtubeVideos.id, videoId)
});
if (!video) throw new Error("Video not found");
// Send to Inngest
await inngest.send({
name: 'youtube/video.detect-objects',
data: {
videoId: video.id,
videoUrl: video.url || `https://www.youtube.com/watch?v=${video.videoId}`,
},
});
// Note: status is updated to 'in_progress' inside the Inngest function.
revalidatePath(`/admin/analysis/${videoId}`);
return { success: true };
}
/**
* Approves a single detected object (making it visible to the user).
*/
export async function approveDetectionAction(detectionId: string) {
const session = await auth.api.getSession({
headers: await headers()
});
await ensureAdmin();
const detection = await db.query.detectedObjects.findFirst({
where: eq(detectedObjects.id, detectionId),
with: {
video: {
with: {
channel: true
}
}
}
});
if (!detection) throw new Error("Detection not found");
const isDemoRecord = detection.video?.channel?.creatorId?.startsWith('demo');
await db.transaction(async (tx) => {
const updateData: any = { moderationStatus: 'APPROVED' };
// If it's a demo record, we auto-approve at the creator level too
// so it appears in the public vault immediately.
if (isDemoRecord) {
updateData.status = 'approved';
}
await tx.update(detectedObjects)
.set(updateData)
.where(eq(detectedObjects.id, detectionId));
await tx.insert(adminModeration).values({
detectionId,
adminId: session!.user.id,
action: 'approved',
originalValues: {
moderationStatus: detection.moderationStatus,
status: detection.status
},
correctedValues: updateData,
trainAiFlag: true
});
});
revalidatePath('/admin/analysis');
return { success: true };
}
/**
* Rejects a single detected object (hiding it from the user).
*/
export async function rejectDetectionAction(detectionId: string) {
const session = await auth.api.getSession({
headers: await headers()
});
await ensureAdmin();
const detection = await db.query.detectedObjects.findFirst({
where: eq(detectedObjects.id, detectionId)
});
if (!detection) throw new Error("Detection not found");
await db.transaction(async (tx) => {
await tx.update(detectedObjects)
.set({ moderationStatus: 'REJECTED' })
.where(eq(detectedObjects.id, detectionId));
await tx.insert(adminModeration).values({
detectionId,
adminId: session!.user.id,
action: 'rejected',
originalValues: { moderationStatus: detection.moderationStatus },
correctedValues: { moderationStatus: 'REJECTED' },
trainAiFlag: true
});
});
revalidatePath('/admin/analysis');
return { success: true };
}
/**
* Marks the entire video analysis as complete and removes it from the queue.
*/
export async function completeVideoReviewAction(videoId: string) {
await ensureAdmin();
await db.update(youtubeVideos)
.set({ scanStatus: 'completed' })
.where(eq(youtubeVideos.id, videoId));
// Optional: Trigger notifications here
// notifyUser(videoId, 'analysis_ready');
revalidatePath('/admin/analysis-queue');
revalidatePath(`/admin/analysis/${videoId}`);
return { success: true };
}
/**
* Manually adds a product to a video from the admin interface.
*/
export async function addManualProductAction(videoId: string, data: {
objectName: string;
category: any;
price?: number;
affiliateUrl?: string;
imageUrl?: string;
}) {
await ensureAdmin();
// Check if it's a demo record
const videoResult = await db.query.youtubeVideos.findFirst({
where: eq(youtubeVideos.id, videoId),
with: {
channel: true
}
});
const isDemoRecord = videoResult?.channel?.creatorId?.startsWith('demo');
// 1. Create Detection (AUTO-APPROVED if added by admin)
const [detection] = await db.insert(detectedObjects).values({
videoId,
objectName: data.objectName,
category: data.category,
confidenceScore: 1.0,
frameTimestamp: 0,
status: isDemoRecord ? 'approved' : 'pending_review',
moderationStatus: 'APPROVED',
thumbnailUrl: data.imageUrl || '/placeholder-product.png',
}).returning();
// 2. Create Marketplace Match if URL provided
if (data.affiliateUrl) {
// Simple productId extraction fallback
const productId = data.affiliateUrl.match(/\/dp\/([A-Z0-9]{10})/)
? data.affiliateUrl.match(/\/dp\/([A-Z0-9]{10})/)?.[1]
: `manual-${crypto.randomUUID().slice(0, 8)}`;
await db.insert(marketplaceMatches).values({
objectId: detection.id,
marketplace: 'amazon',
productId: productId || 'unknown',
productName: data.objectName,
price: data.price || 0,
availabilityStatus: 'IN_STOCK',
affiliateUrl: data.affiliateUrl,
imageUrl: data.imageUrl,
});
}
revalidatePath(`/admin/analysis/${videoId}`);
return { success: true };
}
/**
* Fetches products from other vaults for the same videoId.
*/
export async function getCrossVaultSuggestions(videoId: string, excludeCreatorId?: string) {
await ensureAdmin();
// Find other instances of this videoId
const otherVideos = await db.query.youtubeVideos.findMany({
where: eq(youtubeVideos.videoId, videoId),
});
const otherVideoIds = otherVideos.map(v => v.id);
if (otherVideoIds.length === 0) return [];
// Fetch unique products from these videos
const products = await db.query.detectedObjects.findMany({
where: and(
inArray(detectedObjects.videoId, otherVideoIds),
eq(detectedObjects.moderationStatus, 'APPROVED')
),
with: {
marketplaceMatches: true
}
});
// Deduplicate by product name/link
return products;
}
/**
* Clones a detection (and its first marketplace match) to the specified video.
*/
export async function cloneDetectionAction(videoId: string, sourceDetectionId: string) {
await ensureAdmin();
const source = await db.query.detectedObjects.findFirst({
where: eq(detectedObjects.id, sourceDetectionId),
with: {
marketplaceMatches: true
}
});
if (!source) throw new Error("Source detection not found");
// 1. Create new detection
const [newDetection] = await db.insert(detectedObjects).values({
videoId,
objectName: source.objectName,
category: source.category,
confidenceScore: 1.0,
frameTimestamp: source.frameTimestamp,
thumbnailUrl: source.thumbnailUrl,
status: 'pending_review',
moderationStatus: 'APPROVED',
}).returning();
// 2. Clone first marketplace match
const match = source.marketplaceMatches[0];
if (match) {
await db.insert(marketplaceMatches).values({
objectId: newDetection.id,
marketplace: match.marketplace,
productId: match.productId,
productName: match.productName,
price: match.price,
availabilityStatus: match.availabilityStatus,
affiliateUrl: match.affiliateUrl,
imageUrl: match.imageUrl,
});
}
revalidatePath(`/admin/analysis/${videoId}`);
return { success: true };
}
/**
* Fetches the moderation history for a specific video.
*/
export async function getAnalysisHistory(videoInternalId: string) {
await ensureAdmin();
// Get all detections for this video
const detections = await db.query.detectedObjects.findMany({
where: eq(detectedObjects.videoId, videoInternalId),
});
if (detections.length === 0) return [];
// Get audit logs for these detections
const logs = await db.query.adminModeration.findMany({
where: inArray(adminModeration.detectionId, detections.map(d => d.id)),
with: {
admin: true,
detection: true,
},
orderBy: [desc(adminModeration.createdAt)],
});
return logs;
}
|