sofia-cloud / src /app /api /generate /video /route.ts
GoGma's picture
Update src/app/api/generate/video/route.ts
b059128 verified
raw
history blame
3.06 kB
import { NextRequest, NextResponse } from "next/server";
import ZAI from "z-ai-web-dev-sdk";
import { db } from "@/lib/db";
import fs from "fs/promises";
import path from "path";
const DOWNLOAD_DIR = path.join(process.cwd(), "download", "videos");
async function ensureDir() {
try {
await fs.mkdir(DOWNLOAD_DIR, { recursive: true });
} catch {}
}
export async function POST(request: NextRequest) {
try {
const body = await request.json();
const {
prompt,
optimizedPrompt,
platform = "general",
style = "cinematic",
duration = "short",
aspectRatio = "16:9",
saveToDb = true,
projectId,
} = body;
if (!prompt && !optimizedPrompt) {
return NextResponse.json(
{ success: false, error: "Se requiere un prompt" },
{ status: 400 }
);
}
await ensureDir();
const finalPrompt = optimizedPrompt || prompt;
// ✅ DB record
let contentRecord: any = null;
if (saveToDb) {
contentRecord = await db.content.create({
data: {
type: "video",
title: (prompt || "").substring(0, 50),
description: prompt,
prompt: prompt,
optimizedPrompt: finalPrompt,
platform,
status: "processing",
projectId: projectId || null,
metadata: JSON.stringify({ style, duration, aspectRatio }),
},
});
}
try {
const zai = await ZAI.create();
// ✅ SDK correcto (sin la S)
const response: any = await zai.video.generations.create({
prompt: finalPrompt,
});
// ✅ Extraer URL de forma tolerante
const videoUrl: string | null =
response?.video_url ||
response?.url ||
response?.data?.[0]?.url ||
null;
if (!videoUrl) {
throw new Error("No se recibió video del generador");
}
// ✅ actualizar DB
if (contentRecord) {
await db.content.update({
where: { id: contentRecord.id },
data: {
status: "completed",
filePath: videoUrl,
},
});
}
return NextResponse.json({
success: true,
video: {
id: contentRecord?.id,
url: videoUrl,
prompt: finalPrompt,
platform,
style,
duration,
aspectRatio,
},
});
} catch (genError) {
console.error("Error generando video:", genError);
if (contentRecord) {
await db.content.update({
where: { id: contentRecord.id },
data: {
status: "failed",
metadata: JSON.stringify({ error: String(genError) }),
},
});
}
return NextResponse.json(
{ success: false, error: "Error al generar video" },
{ status: 500 }
);
}
} catch (error) {
console.error("Error en generate video:", error);
return NextResponse.json(
{ success: false, error: "Error interno" },
{ status: 500 }
);
}
}