add api for video download

This commit is contained in:
Sempre 2025-09-22 21:31:33 +08:00 committed by GitHub
parent a346bdf497
commit c1bc078a1f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 285 additions and 0 deletions

View File

@ -0,0 +1,285 @@
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { spawn } from "child_process";
import path from "path";
const searchRequestSchema = z.object({
keyword: z.string().min(1, "Keyword is required"),
page: z.number().optional().default(1),
pageSize: z.number().optional().default(20),
});
const infoRequestSchema = z.object({
url: z.string().url("Invalid URL provided"),
});
export async function POST(request: NextRequest) {
try {
const { searchParams } = new URL(request.url);
const action = searchParams.get("action");
switch (action) {
case "search":
return await handleSearch(request);
case "info":
return await handleVideoInfo(request);
case "download":
return await handleDownload(request);
default:
return NextResponse.json(
{ error: "Invalid action. Use 'search', 'info' or 'download'." },
{ status: 400 }
);
}
} catch (error) {
console.error("Video API error:", error);
return NextResponse.json(
{
error: "Internal server error",
message: "An unexpected error occurred",
},
{ status: 500 }
);
}
}
async function handleSearch(request: NextRequest) {
try {
const rawBody = await request.json().catch(() => null);
if (!rawBody) {
return NextResponse.json(
{ error: "Invalid JSON in request body" },
{ status: 400 }
);
}
const validationResult = searchRequestSchema.safeParse(rawBody);
if (!validationResult.success) {
return NextResponse.json(
{
error: "Invalid request parameters",
details: validationResult.error.flatten().fieldErrors,
},
{ status: 400 }
);
}
const { keyword, page, pageSize } = validationResult.data;
// Use yt-dlp to search for videos
return new Promise((resolve) => {
const startIndex = (page - 1) * pageSize + 1;
const endIndex = page * pageSize;
const ytDlp = spawn("yt-dlp", [
"--dump-single-json",
"--flat-playlist",
"--no-warnings",
"--playlist-start", startIndex.toString(),
"--playlist-end", endIndex.toString(),
`ytsearch${pageSize}:${keyword}`
]);
let stdoutData = "";
let stderrData = "";
ytDlp.stdout.on("data", (data) => {
stdoutData += data.toString();
});
ytDlp.stderr.on("data", (data) => {
stderrData += data.toString();
});
ytDlp.on("close", (code) => {
try {
if (code !== 0) {
resolve(
NextResponse.json(
{
success: false,
error: `yt-dlp process exited with code ${code}`,
details: stderrData,
},
{ status: 500 }
)
);
return;
}
if (!stdoutData.trim()) {
resolve(
NextResponse.json(
{
success: false,
error: "No output from yt-dlp",
details: stderrData || "Process completed with no output",
},
{ status: 500 }
)
);
return;
}
const result = JSON.parse(stdoutData);
resolve(NextResponse.json({
success: true,
data: result
}));
} catch (parseError) {
resolve(
NextResponse.json(
{
success: false,
error: `Error parsing yt-dlp output`,
details: parseError instanceof Error ? parseError.message : "Unknown error",
rawOutput: stdoutData,
},
{ status: 500 }
)
);
}
});
ytDlp.on("error", (error) => {
resolve(
NextResponse.json(
{
success: false,
error: `Failed to start yt-dlp process`,
details: error.message,
},
{ status: 500 }
)
);
});
});
} catch (error) {
return NextResponse.json(
{
success: false,
error: error instanceof Error ? error.message : "Unknown error occurred",
},
{ status: 500 }
);
}
}
async function handleVideoInfo(request: NextRequest) {
try {
const rawBody = await request.json().catch(() => null);
if (!rawBody) {
return NextResponse.json(
{ error: "Invalid JSON in request body" },
{ status: 400 }
);
}
const validationResult = infoRequestSchema.safeParse(rawBody);
if (!validationResult.success) {
return NextResponse.json(
{
error: "Invalid request parameters",
details: validationResult.error.flatten().fieldErrors,
},
{ status: 400 }
);
}
const { url } = validationResult.data;
// Use yt-dlp to get video info
return new Promise((resolve) => {
const ytDlp = spawn("yt-dlp", [
"--dump-single-json",
"--no-warnings",
"--compat-options", "no-youtube-channel-redirect",
url
]);
let stdoutData = "";
let stderrData = "";
ytDlp.stdout.on("data", (data) => {
stdoutData += data.toString();
});
ytDlp.stderr.on("data", (data) => {
stderrData += data.toString();
});
ytDlp.on("close", (code) => {
try {
if (code !== 0) {
resolve(
NextResponse.json(
{
success: false,
error: `yt-dlp process exited with code ${code}`,
details: stderrData,
},
{ status: 500 }
)
);
return;
}
if (!stdoutData.trim()) {
resolve(
NextResponse.json(
{
success: false,
error: "No output from yt-dlp",
details: stderrData || "Process completed with no output",
},
{ status: 500 }
)
);
return;
}
const result = JSON.parse(stdoutData);
resolve(NextResponse.json({
success: true,
data: result
}));
} catch (parseError) {
resolve(
NextResponse.json(
{
success: false,
error: `Error parsing yt-dlp output`,
details: parseError instanceof Error ? parseError.message : "Unknown error",
rawOutput: stdoutData,
},
{ status: 500 }
)
);
}
});
ytDlp.on("error", (error) => {
resolve(
NextResponse.json(
{
success: false,
error: `Failed to start yt-dlp process`,
details: error.message,
},
{ status: 500 }
)
);
});
});
} catch (error) {
return NextResponse.json(
{
success: false,
error: error instanceof Error ? error.message : "Unknown error occurred",
},
{ status: 500 }
);
}
}