import { NextRequest, NextResponse } from "next/server"; import { auth } from "@/app/(auth)/auth"; import { executeExtendJob, ExtendServiceError, } from "@/lib/ai/extend/service"; export const maxDuration = 180; export async function POST(request: NextRequest) { try { const session = await auth(); if (!session?.user?.id) { return NextResponse.json({ error: "未授权,请先登录" }, { status: 401 }); } const contentType = request.headers.get("content-type") || ""; let imageUrl: string | null = null; let imageBase64: string | null = null; let prompt = "图像拓展处理"; let chatId: string | null = null; let messageId: string | null = null; if (contentType.includes("application/json")) { const body = await request.json(); imageUrl = body.image_url ? String(body.image_url).trim() : null; imageBase64 = body.image_base64 ? String(body.image_base64).trim() : null; prompt = body.prompt || prompt; chatId = body.chatId || null; messageId = body.messageId || null; if (!imageUrl && !imageBase64) { return NextResponse.json( { error: "缺少image_base64或image_url参数" }, { status: 400 }, ); } const result = await executeExtendJob({ userId: session.user.id, imageUrl, imageBase64, prompt, chatId, messageId, xScale: body.xScale ? Number(body.xScale) : undefined, yScale: body.yScale ? Number(body.yScale) : undefined, }); return NextResponse.json({ success: true, original_url: result.original_url, thumbnail_url: result.thumbnail_url, base64: result.image_base64, processing_time: result.processing_time, }); } if (contentType.includes("multipart/form-data")) { const formData = await request.formData(); const file = formData.get("file") as File | null; if (!file) { return NextResponse.json({ error: "缺少file参数" }, { status: 400 }); } const arrayBuffer = await file.arrayBuffer(); const buffer = Buffer.from(arrayBuffer); const result = await executeExtendJob({ userId: session.user.id, imageBase64: buffer.toString("base64"), prompt: String(formData.get("prompt") || prompt), chatId: String(formData.get("chatId") || "") || null, messageId: String(formData.get("messageId") || "") || null, }); return NextResponse.json({ success: true, original_url: result.original_url, thumbnail_url: result.thumbnail_url, base64: result.image_base64, processing_time: result.processing_time, }); } return NextResponse.json( { error: "不支持的Content-Type,请使用application/json或multipart/form-data" }, { status: 400 }, ); } catch (error) { if (error instanceof ExtendServiceError) { return NextResponse.json( { error: error.message, detail: error.detail || error.message, }, { status: error.status }, ); } console.error("[Extend API] 错误:", error); return NextResponse.json( { error: "图像拓展失败", detail: error instanceof Error ? error.message : String(error), }, { status: 500 }, ); } }