import http from "http";
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
const DIR = path.join(process.cwd(), "screens");
if (!fs.existsSync(DIR)) fs.mkdirSync(DIR, { recursive: true });
const PORT = 8765;
const HTML = `
📸 Screens Upload
📸 Screens Upload
Screenshots direkt in den screens/ Ordner im aktuellen Verzeichnis hochladen.
Drag & Drop oder klicken zum Auswählen
`;
function parseMultipart(body, boundary) {
const files = [];
const sep = Buffer.from("--" + boundary);
const parts = [];
let start = body.indexOf(sep) + sep.length + 2;
while (start < body.length) {
const end = body.indexOf(sep, start);
if (end === -1) break;
parts.push(body.slice(start, end - 2));
start = end + sep.length + 2;
}
for (const part of parts) {
const headerEnd = part.indexOf("\r\n\r\n");
if (headerEnd === -1) continue;
const header = part.slice(0, headerEnd).toString();
const content = part.slice(headerEnd + 4);
const nameMatch = header.match(/name="([^"]+)"/);
const fileMatch = header.match(/filename="([^"]+)"/);
if (nameMatch && fileMatch) {
files.push({ name: fileMatch[1], data: content });
}
}
return files;
}
const server = http.createServer((req, res) => {
if (req.method === "GET" && req.url === "/") {
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
return res.end(HTML);
}
if (req.method === "POST" && req.url === "/upload") {
const ct = req.headers["content-type"] || "";
const match = ct.match(/boundary=(.+)/);
if (!match) {
res.writeHead(400); return res.end("Kein Boundary");
}
const boundary = match[1];
const chunks = [];
req.on("data", c => chunks.push(c));
req.on("end", () => {
const body = Buffer.concat(chunks);
const files = parseMultipart(body, boundary);
if (!files.length) { res.writeHead(400); return res.end("Keine Datei gefunden"); }
const saved = [];
for (const file of files) {
const safeName = path.basename(file.name).replace(/[^a-zA-Z0-9._\- ()äöüÄÖÜß]/g, "_");
const dest = path.join(DIR, safeName);
fs.writeFileSync(dest, file.data);
saved.push(safeName);
console.log(`✅ Gespeichert: ${safeName}`);
}
res.writeHead(200); res.end(saved.join(", ") + " gespeichert.");
});
return;
}
res.writeHead(404); res.end("Not found");
});
server.listen(PORT, "0.0.0.0", () => {
console.log(`📸 Screens Upload Server läuft auf http://0.0.0.0:${PORT}`);
console.log(`📁 Speicherort: ${DIR}`);
});