const express = require("express"); const fs = require("fs"); const path = require("path"); const { execFile } = require("child_process"); const app = express(); app.use(express.json({ limit: "256kb" })); const HOST = process.env.IOMATEX_WEB_HOST || "0.0.0.0"; const PORT = parseInt(process.env.IOMATEX_WEB_PORT || "8081", 10); const DIST_DIR = process.env.IOMATEX_WEB_DIST || "/opt/iomatex-web/dist"; const ENV_FILE = "/etc/default/itscreen"; const ENV_KEY = "ITSCREEN_SERVER_URL"; function safeRead(p) { try { return fs.readFileSync(p, "utf8"); } catch { return ""; } } function parseEnvValue(text, key) { const m = text.match(new RegExp(`^${key}=(.*)$`, "m")); return m ? m[1].trim() : null; } function atomicWrite(p, content) { const tmp = `${p}.tmp`; fs.writeFileSync(tmp, content, { mode: 0o644 }); fs.renameSync(tmp, p); } function upsertEnvKey(filePath, key, value) { const text = safeRead(filePath); const lines = text ? text.split(/\r?\n/) : []; const out = lines.filter(l => l && l.trim().length && !l.startsWith(`${key}=`)).map(l => l.trim()); out.push(`${key}=${value}`); atomicWrite(filePath, out.join("\n") + "\n"); } function run(cmd, args) { return new Promise((resolve, reject) => { execFile(cmd, args, { timeout: 20000 }, (err, stdout, stderr) => { if (err) return reject(new Error(String(stderr || err))); resolve(String(stdout || "").trim()); }); }); } function validateServerUrl(url) { if (typeof url !== "string") return "serverUrl must be string"; const u = url.trim(); if (!u.startsWith("https://")) return "Only https:// is allowed"; if (/\s/.test(u)) return "serverUrl contains spaces"; if (u.length < 12) return "serverUrl is too short"; return null; } app.get("/api/v1/edge/state", async (req, res) => { try { const env = safeRead(ENV_FILE); const serverUrl = parseEnvValue(env, ENV_KEY); let svc = "unknown"; try { svc = await run("systemctl", ["is-active", "itscreen.service"]); } catch {} res.json({ registered: false, status: serverUrl ? "server-set" : "not-configured", serverUrl: serverUrl || null, device: { id: null, username: null }, itscreenService: svc, lastError: null }); } catch (e) { res.status(500).json({ error: "state_failed", details: String(e) }); } }); app.post("/api/v1/edge/set-server", async (req, res) => { const serverUrl = req?.body?.serverUrl; const err = validateServerUrl(serverUrl); if (err) return res.status(400).json({ error: "bad_request", details: err }); try { upsertEnvKey(ENV_FILE, ENV_KEY, serverUrl.trim()); await run("systemctl", ["restart", "itscreen.service"]); res.json({ ok: true, serverUrl: serverUrl.trim() }); } catch (e) { res.status(500).json({ error: "set_server_failed", details: String(e) }); } }); app.use("/", express.static(DIST_DIR, { maxAge: "1h", index: false })); app.get("*", (req, res) => { const indexPath = path.join(DIST_DIR, "index.html"); if (fs.existsSync(indexPath)) return res.sendFile(indexPath); res.status(404).send("UI not installed (missing dist/index.html)"); }); app.listen(PORT, HOST, () => console.log(`IOMATEX Web+API on http://${HOST}:${PORT}`));