ffpeg / index.js
ImjerryCo's picture
Update index.js
4713649 verified
const express = require("express");
const { spawn } = require("child_process");
const fs = require("fs");
const path = require("path");
const crypto = require("crypto");
const app = express();
const PORT = 7860;
// TEMP folder
const TMP = "/tmp";
// simple cleanup helper
const cleanup = (file) => {
try {
if (fs.existsSync(file)) fs.unlinkSync(file);
} catch {}
};
app.get("/", async (req, res) => {
const url = req.query.url;
if (!url) {
return res.json({
status: false,
message: "Use ?url=video_link"
});
}
const id = crypto.randomBytes(6).toString("hex");
const outputFile = path.join(TMP, `${id}.mp4`);
// 🔥 IMPORTANT: NO ENCODING (LOW CPU)
const ffmpegArgs = [
"-y",
"-user_agent", "Mozilla/5.0",
"-i", url,
"-c", "copy",
"-bsf:a", "aac_adtstoasc",
"-movflags", "+faststart",
outputFile
];
const ffmpeg = spawn("ffmpeg", ffmpegArgs);
let timeout = setTimeout(() => {
ffmpeg.kill("SIGKILL");
cleanup(outputFile);
}, 1000 * 60 * 8); // 8 min safety timeout
ffmpeg.stderr.on("data", () => {});
ffmpeg.on("close", (code) => {
clearTimeout(timeout);
if (code !== 0 || !fs.existsSync(outputFile)) {
cleanup(outputFile);
return res.json({
status: false,
error: "Download failed or blocked stream"
});
}
// pretend HF space file hosting
const fileUrl = `https://${req.headers.host}/file/${id}`;
return res.json({
status: true,
download: fileUrl
});
});
});
// serve temp files
app.get("/file/:id", (req, res) => {
const file = path.join(TMP, `${req.params.id}.mp4`);
if (!fs.existsSync(file)) {
return res.json({
status: false,
error: "File expired or not found"
});
}
res.download(file, "video.mp4", () => {
cleanup(file);
});
});
app.listen(PORT, () => {
console.log("Running on", PORT);
});