dika/src/index.js
peppa-bot cb9196521a
All checks were successful
peppa/lint lint: success за 0с
peppa/test test: success за 1с
peppa/build build: success за 0с
ci / checks (pull_request) Successful in 10s
deploy / deploy (pull_request) Successful in 20s
DIK-69: владелец загружает фото файлом, инструкция и понятные ошибки на странице правки
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 11:58:05 +00:00

115 lines
6.8 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.

import http from "node:http";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { buildList, findAddress, nearVenues } from "./lib.js";
import { createStore, checkPassword, PHOTO_MAX, PHOTO_NAME } from "./admin.js";
import { walkRoutes } from "./route.js";
import { renderPage } from "./page.js";
const root = path.join(path.dirname(fileURLToPath(import.meta.url)), "..");
const types = { ".jpg": "image/jpeg", ".png": "image/png", ".webp": "image/webp", ".html": "text/html; charset=utf-8", ".js": "text/javascript", ".css": "text/css", ".json": "application/json" };
// dataDir — где лежит живая база (по умолчанию data/ рядом с кодом), password — пароль владельца базы.
export function createHandler({ dataDir = path.join(root, "data"), seedDir = path.join(root, "data"), password = "", route = {} } = {}) {
const store = createStore(dataDir, seedDir);
return (req, res) => handle(req, res, store, password, route);
}
const defaultHandler = () => createHandler({
dataDir: process.env.DATA_DIR || path.join(root, "data"), password: process.env.ADMIN_PASSWORD || "",
});
function admin(req, res, url, store, password, json) {
if (!password) {
res.writeHead(503, { "content-type": "text/plain; charset=utf-8" });
return res.end("Правка отключена: не задан пароль владельца базы. Задайте пароль и откройте страницу снова.");
}
if (!checkPassword(req.headers.authorization, password)) {
res.writeHead(401, { "www-authenticate": 'Basic realm="admin", charset="UTF-8"', "content-type": "text/html; charset=utf-8", "x-robots-tag": "noindex" });
return res.end(loginPage(ru()));
}
if (url.pathname === "/admin" && req.method === "GET") {
res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store", "x-robots-tag": "noindex" });
return res.end(fs.readFileSync(path.join(root, "admin", "index.html")));
}
if (url.pathname === "/admin/api/venues" && req.method === "GET") return json(200, store.list());
const p = /^\/admin\/api\/venues\/([\w-]+)\/photo$/.exec(url.pathname);
if (p && req.method === "POST") {
const parts = []; let size = 0, big = false;
req.on("data", (c) => { size += c.length; if (size > PHOTO_MAX) big = true; else parts.push(c); });
req.on("end", () => {
if (big) return json(413, { error: "photo_too_big" });
const r = store.savePhoto(p[1], Buffer.concat(parts));
return json(r.ok ? 200 : r.error === "not_found" ? 404 : 400, r);
});
return;
}
const m = /^\/admin\/api\/venues\/([\w-]+)$/.exec(url.pathname);
if (m && req.method === "POST") {
let body = "";
req.on("data", (c) => { body += c; if (body.length > 20000) req.destroy(); });
req.on("end", () => {
let patch;
try { patch = JSON.parse(body); } catch { return json(400, { error: "bad_request" }); }
const r = store.update(m[1], patch || {});
return json(r.ok ? 200 : r.error === "not_found" ? 404 : 400, r);
});
return;
}
return json(404, { error: "not_found" });
}
const ru = () => JSON.parse(fs.readFileSync(path.join(root, "public", "i18n", "ru.json"), "utf8"));
const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]);
// Без пароля: короткая страница для человека, а не «401» (DIK-69)
const loginPage = (t) => `<!doctype html><html lang="ru"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex"><title>${esc(t.admLoginTitle)}</title></head>`
+ `<body style="font:16px/1.4 system-ui,sans-serif;max-width:560px;margin:40px auto;padding:0 16px"><h1>${esc(t.admLoginTitle)}</h1><p>${esc(t.admLoginText)}</p><p><a href="/">${esc(t.admBack)}</a></p></body></html>`;
function handle(req, res, store, password, route) {
const db = store.db;
const url = new URL(req.url, "http://x");
const json = (code, body) => { res.writeHead(code, { "content-type": "application/json" }); res.end(JSON.stringify(body)); };
if (url.pathname === "/admin" || url.pathname.startsWith("/admin/")) return admin(req, res, url, store, password, json);
const ph = /^\/photos\/([^/]+)$/.exec(url.pathname);
if (ph) {
const file = path.join(store.dataDir, "photos", ph[1]);
if (!PHOTO_NAME.test(ph[1]) || !fs.existsSync(file)) { res.writeHead(404); return res.end("Not found"); }
res.writeHead(200, { "content-type": types[path.extname(file)], "cache-control": "public, max-age=86400" });
return fs.createReadStream(file).pipe(res);
}
if (url.pathname === "/healthz") return json(200, { ok: true });
if (url.pathname === "/api/base") return json(200, store.all());
if (url.pathname === "/api/locate") {
const v = findAddress(db.venues, url.searchParams.get("q") || "");
return v ? json(200, { lat: v.lat, lng: v.lng }) : json(404, { error: "not_found" });
}
if (url.pathname === "/api/venues") {
const hasPlace = url.searchParams.has("lat") || url.searchParams.has("lng");
const lat = hasPlace ? Number(url.searchParams.get("lat")) : null, lng = hasPlace ? Number(url.searchParams.get("lng")) : null;
if (hasPlace && (!Number.isFinite(lat) || !Number.isFinite(lng))) return json(400, { error: "bad_coords" });
const num = (k, allowed) => { const n = Number(url.searchParams.get(k)); return allowed.includes(n) ? n : null; };
const opts = { only: url.searchParams.get("only") === "1", maxKm: num("maxKm", [1, 2, 5]), maxPrice: num("maxPrice", [2000, 3000, 4000]) };
if (!hasPlace) return json(200, buildList(db.venues, null, null, opts));
walkRoutes(lat, lng, nearVenues(db.venues, lat, lng), route).then(
(routes) => json(200, buildList(db.venues, lat, lng, { ...opts, routes })),
() => json(200, buildList(db.venues, lat, lng, opts)));
return;
}
const rel = url.pathname === "/" ? "index.html" : url.pathname === "/base" ? "base.html" : url.pathname.slice(1);
const file = path.normalize(path.join(root, "public", rel));
if (!file.startsWith(path.join(root, "public")) || !fs.existsSync(file) || fs.statSync(file).isDirectory()) {
res.writeHead(404); return res.end("Not found");
}
res.writeHead(200, { "content-type": types[path.extname(file)] || "application/octet-stream" });
if (path.extname(file) === ".html") {
// страница уходит сразу с русскими текстами — подписи есть и без скрипта
return res.end(renderPage(fs.readFileSync(file, "utf8"), ru()));
}
fs.createReadStream(file).pipe(res);
}
if (process.argv[1] === fileURLToPath(import.meta.url)) {
http.createServer(defaultHandler()).listen(Number(process.env.PORT) || 3000);
}