193 lines
6.3 KiB
JavaScript
193 lines
6.3 KiB
JavaScript
const http = require("http");
|
||
const fs = require("fs");
|
||
const path = require("path");
|
||
|
||
const PORT = process.env.PORT || 3000;
|
||
const DATA_FILE = path.join(__dirname, "data.json");
|
||
const ROOT = __dirname;
|
||
|
||
const BOARD_KEYS = new Set(["gdplan", "myplan", "notes"]);
|
||
const MIME = {
|
||
".css": "text/css", ".js": "application/javascript",
|
||
".html": "text/html", ".json": "application/json",
|
||
".svg": "image/svg+xml", ".png": "image/png", ".ico": "image/x-icon",
|
||
".woff2": "font/woff2", ".woff": "font/woff", ".txt": "text/plain"
|
||
};
|
||
|
||
function readData() {
|
||
try { return JSON.parse(fs.readFileSync(DATA_FILE, "utf8")); }
|
||
catch (_) { return { gdplan: [], myplan: [], notes: [] }; }
|
||
}
|
||
function saveData(d) { fs.writeFileSync(DATA_FILE, JSON.stringify(d, null, 2)); }
|
||
|
||
function sendJson(res, code, obj) {
|
||
const body = JSON.stringify(obj);
|
||
res.writeHead(code, {
|
||
"Content-Type": "application/json; charset=utf-8",
|
||
"Access-Control-Allow-Origin": "*",
|
||
"Cache-Control": "no-store"
|
||
});
|
||
res.end(body);
|
||
}
|
||
|
||
function readBody(req) {
|
||
return new Promise(resolve => {
|
||
let s = "";
|
||
req.on("data", c => (s += c));
|
||
req.on("end", () => {
|
||
try { resolve(JSON.parse(s || "{}")); } catch (_) { resolve({}); }
|
||
});
|
||
});
|
||
}
|
||
|
||
// Parse news items from the JSON‑LD script on the TengriNews main page.
|
||
function parseNewsFromJsonLd(html) {
|
||
// Try JSON‑LD first (original source)
|
||
const jsonLdMatch = html.match(/<script[^>]*type="application\/ld\+json"[^>]*>([\s\S]*?)<\/script>/i);
|
||
if (jsonLdMatch) {
|
||
try {
|
||
const data = JSON.parse(jsonLdMatch[1]);
|
||
let list = [];
|
||
if (Array.isArray(data["@graph"])) {
|
||
const itemObj = data["@graph"].find(o => Array.isArray(o["itemListElement"]));
|
||
if (itemObj) list = itemObj["itemListElement"];
|
||
} else if (Array.isArray(data["itemListElement"])) {
|
||
list = data["itemListElement"];
|
||
}
|
||
return list.map(it => ({
|
||
title: it.name || "",
|
||
sourceUrl: it.url || "",
|
||
date: "",
|
||
image: it.image || ""
|
||
}));
|
||
} catch (_) { /* fall through */ }
|
||
}
|
||
// Fallback: Telegram embed page – extract first 5 message texts and links
|
||
const news = [];
|
||
const msgRegex = /<div class="tgme_widget_message_text[^>]*>([\s\S]*?)<\/div>/gi;
|
||
let m;
|
||
while ((m = msgRegex.exec(html)) !== null && news.length < 5) {
|
||
const raw = m[1];
|
||
// extract first href as sourceUrl
|
||
const hrefMatch = raw.match(/href="([^"]+)"/i);
|
||
const sourceUrl = hrefMatch ? hrefMatch[1] : "";
|
||
// strip HTML tags for a short title (first 120 chars)
|
||
const text = raw.replace(/<[^>]+>/g, "").replace(/\s+/g, " ").trim();
|
||
const title = text.length > 120 ? text.slice(0, 117) + "..." : text;
|
||
news.push({ title, sourceUrl, date: "", image: "" });
|
||
}
|
||
return news;
|
||
}
|
||
|
||
|
||
function sanitize(key, item) {
|
||
const base = { id: Number(item.id) || Date.now() };
|
||
if (key === "notes") {
|
||
base.text = String(item.text || "").slice(0, 2000);
|
||
return base;
|
||
}
|
||
base.text = String(item.text || "").slice(0, 500);
|
||
base.status = ["todo", "doing", "done"].includes(item.status) ? item.status : "todo";
|
||
base.due = String(item.due || "").slice(0, 10);
|
||
if (key === "gdplan") base.time = String(item.time || "").slice(0, 5);
|
||
return base;
|
||
}
|
||
|
||
const server = http.createServer(async (req, res) => {
|
||
const url0 = req.url.split("?")[0];
|
||
|
||
// CORS preflight
|
||
if (req.method === "OPTIONS") {
|
||
res.writeHead(204, {
|
||
"Access-Control-Allow-Origin": "*",
|
||
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
|
||
"Access-Control-Allow-Headers": "Content-Type"
|
||
});
|
||
return res.end();
|
||
}
|
||
|
||
// ---- API ----
|
||
if (url0.startsWith("/api/board/")) {
|
||
const key = url0.split("/")[3];
|
||
if (!BOARD_KEYS.has(key)) return sendJson(res, 400, { ok: false, error: "unknown board" });
|
||
|
||
if (req.method === "GET") {
|
||
const d = readData();
|
||
return sendJson(res, 200, d[key] || []);
|
||
}
|
||
|
||
const body = await readBody(req);
|
||
|
||
if (req.method === "POST") {
|
||
const d = readData();
|
||
const arr = d[key] || [];
|
||
const newId = arr.length ? Math.max(...arr.map(x => x.id)) + 1 : 1;
|
||
const item = sanitize(key, { ...body, id: newId });
|
||
arr.push(item);
|
||
d[key] = arr;
|
||
saveData(d);
|
||
return sendJson(res, 200, { ok: true, item });
|
||
}
|
||
|
||
// PUT / DELETE требуют id
|
||
const m = url0.match(/^\/api\/board\/(\w+)\/(\d+)$/);
|
||
if (m) {
|
||
const id = Number(m[2]);
|
||
const d = readData();
|
||
const arr = d[key] || [];
|
||
|
||
if (req.method === "PUT") {
|
||
const idx = arr.findIndex(x => x.id === id);
|
||
if (idx < 0) return sendJson(res, 404, { ok: false, error: "not found" });
|
||
arr[idx] = { ...arr[idx], ...sanitize(key, { ...arr[idx], ...body }) };
|
||
saveData(d);
|
||
return sendJson(res, 200, { ok: true, item: arr[idx] });
|
||
}
|
||
|
||
if (req.method === "DELETE") {
|
||
const next = arr.filter(x => x.id !== id);
|
||
d[key] = next;
|
||
saveData(d);
|
||
return sendJson(res, 200, { ok: true });
|
||
}
|
||
}
|
||
|
||
return sendJson(res, 405, { ok: false, error: "method not allowed" });
|
||
}
|
||
|
||
if (url0 === "/api/news") {
|
||
// Пакет новостей: берём список с главной страницы tengrinews.kz (JSON-LD).
|
||
try {
|
||
const resp = await fetch("https://t.me/s/bluescreenkz?embed=1", {
|
||
headers: { "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36" },
|
||
redirect: "follow"
|
||
});
|
||
if (!resp.ok) {
|
||
return sendJson(res, 502, []);
|
||
}
|
||
const html = await resp.text();
|
||
const items = parseNewsFromJsonLd(html);
|
||
return sendJson(res, 200, items);
|
||
} catch (e) {
|
||
return sendJson(res, 502, []);
|
||
}
|
||
}
|
||
|
||
// ---- Статика ----
|
||
let file = url0 === "/" ? "/index.html" : url0;
|
||
const full = path.join(ROOT, file);
|
||
if (full.startsWith(ROOT) && fs.existsSync(full)) {
|
||
const st = fs.statSync(full);
|
||
if (st.isFile()) {
|
||
const ext = path.extname(full).toLowerCase();
|
||
const type = MIME[ext] || "application/octet-stream";
|
||
res.writeHead(200, { "Content-Type": type + "; charset=utf-8" });
|
||
return res.end(fs.readFileSync(full));
|
||
}
|
||
}
|
||
res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" });
|
||
res.end("Not found");
|
||
});
|
||
|
||
server.listen(PORT, () => console.log("Сервер запущен на порту " + PORT));
|