nuzhna-setevaya-papka-dlya-p/server.js

183 lines
6.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const http = require("http");
const fs = require("fs");
const path = require("path");
const formidable = require("formidable");
const PORT = process.env.PORT || 3000;
const ROOT = __dirname;
const DATA = path.join(ROOT, "data.json");
const FILES = path.join(ROOT, "files");
const MAX_FILE = 500 * 1024 * 1024; // 500 МБ на файл
const META_MAX = 200; // длина имени/полей из формы
fs.mkdirSync(FILES, { recursive: true });
/* ---------- Метаданные (data.json) ---------- */
const safe = s => String(s == null ? "" : s).slice(0, META_MAX);
function loadMeta() {
try { return JSON.parse(fs.readFileSync(DATA, "utf8")); } catch (_) { return { files: [] }; }
}
function saveMeta(m) {
const tmp = DATA + "." + process.pid + ".tmp";
fs.writeFileSync(tmp, JSON.stringify(m, null, 2));
fs.renameSync(tmp, DATA);
}
/* ---------- Статика ---------- */
const MIME = {
".html": "text/html; charset=utf-8",
".css": "text/css; charset=utf-8",
".js": "application/javascript; charset=utf-8",
".svg": "image/svg+xml",
".png": "image/png",
".webmanifest": "application/manifest+json; charset=utf-8",
".json": "application/json; charset=utf-8"
};
function sendJson(res, status, obj) {
const body = JSON.stringify(obj);
res.writeHead(status, {
"Content-Type": "application/json; charset=utf-8",
"Content-Length": Buffer.byteLength(body),
"Cache-Control": "no-store"
});
res.end(body);
}
function serveStatic(req, res, url) {
let file = url === "/" ? "/index.html" : url;
file = file.split("?")[0];
const full = path.normalize(path.join(ROOT, file));
if (!full.startsWith(ROOT)) return notFound(res);
let st;
try { st = fs.statSync(full); } catch (_) { return notFound(res); }
if (!st.isFile()) return notFound(res);
res.writeHead(200, {
"Content-Type": MIME[path.extname(full)] || "application/octet-stream",
"Content-Length": st.size,
"Cache-Control": "no-cache"
});
fs.createReadStream(full).pipe(res);
}
function notFound(res) {
res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" });
res.end("Not found");
}
/* ---------- Загрузка файлов (потоком, прямо в диск) ---------- */
function handleUpload(req, res) {
const form = formidable({
maxFileSize: MAX_FILE,
maxFiles: 10,
// без filename: formidable сам ищет свободный путь внутри dest
filter: (part, name, value) => {
const ext = path.extname(name);
const base = path.basename(name);
const ok = base.length <= 180 && /^[A-Za-z0-9А-Яа-яЁё_\-\.() ]+$/.test(base) &&
(ext === "" || /^[.][A-Za-z0-9]{1,10}$/.test(ext));
if (!ok) return false;
form._uploaded.push({ name, ext });
}
});
form._uploaded = [];
form.on("file", (field, file) => {
fs.rename(file.filepath, path.join(FILES, file.originalFilename))
.catch(() => { /* конфликт имён разрешится при перечтении */ });
});
let done = false;
const finish = err => {
if (done) return;
done = true;
if (err) return sendJson(res, 400, { ok: false, error: String(err.message || err) });
const by = form.fields.by ? safe(form.fields.by) : "—";
const city = form.fields.city ? safe(form.fields.city) : "—";
const meta = loadMeta();
const added = [];
for (const f of form._uploaded) {
const id = "f" + Date.now().toString(36) + Math.random().toString(36).slice(2, 7);
const dest = path.join(FILES, f.name);
let size = 0;
try { size = fs.statSync(dest).size; } catch (_) {}
const rec = { id, name: f.name, ext: f.ext, size, by, city, date: new Date().toISOString() };
added.push(rec);
meta.files.push(rec);
}
saveMeta(meta);
sendJson(res, 200, { ok: true, added: added.length });
};
form.parse(req, finish);
}
/* ---------- Скачивание ---------- */
function handleDownload(res, name) {
const safeName = path.basename(name);
const full = path.join(FILES, safeName);
if (!full.startsWith(FILES)) return notFound(res);
let st;
try { st = fs.statSync(full); } catch (_) { return notFound(res); }
res.writeHead(200, {
"Content-Type": "application/octet-stream",
"Content-Length": st.size,
"Content-Disposition": 'attachment; filename="' + safeName.replace(/"/g, "").slice(0, 180) + '"'
});
fs.createReadStream(full).pipe(res);
}
/* ---------- Сервер ---------- */
http.createServer((req, res) => {
const url = req.url || "/";
const u = url.split("?")[0];
const query = new URLSearchParams(url.includes("?") ? url.slice(url.indexOf("?") + 1) : "");
try {
if (req.method === "GET" && u === "/api/meta") return sendJson(res, 200, loadMeta());
if (req.method === "GET" && u === "/api/files") {
let list = loadMeta().files;
const q = (query.get("q") || "").toLowerCase().trim();
if (q) list = list.filter(f => f.name.toLowerCase().includes(q));
try {
for (const f of list) {
let st;
try { st = fs.statSync(path.join(FILES, f.name)); } catch (_) { continue; }
f.size = st.size;
}
} catch (_) {}
list.sort((a, b) => String(b.date).localeCompare(String(a.date)));
return sendJson(res, 200, list);
}
if (req.method === "POST" && u === "/api/upload") return handleUpload(req, res);
if (req.method === "DELETE" && u.startsWith("/api/files/")) {
const name = path.basename(decodeURIComponent(u.slice("/api/files/".length)));
const meta = loadMeta();
const idx = meta.files.findIndex(f => f.name === name);
if (idx >= 0) {
meta.files.splice(idx, 1);
saveMeta(meta);
fs.unlink(path.join(FILES, name)).catch(() => {});
}
return sendJson(res, 200, { ok: true });
}
if (req.method === "GET" && u.startsWith("/api/download/")) {
return handleDownload(res, decodeURIComponent(u.slice("/api/download/".length)));
}
if (req.method === "GET") return serveStatic(req, res, url);
return notFound(res);
} catch (e) {
return sendJson(res, 500, { ok: false, error: "Сервер: внутренняя ошибка" });
}
}).listen(PORT, () => console.log("Общая папка: сервер на порту " + PORT));