feat!: new targets.json structure, add target status endpoint, move frontend to HTML file with table
BREAKING CHANGE: convert older targets.json file to new structure
This commit is contained in:
47
api.js
47
api.js
@@ -1,34 +1,20 @@
|
||||
import express from 'express';
|
||||
import cors from 'cors';
|
||||
import { sendWolPacket } from './wol.js';
|
||||
import { ping, sendWolPacket } from './wol.js';
|
||||
import targets from "./targets.json" with { type: "json" };
|
||||
import { fileURLToPath } from "node:url";
|
||||
import path from 'node:path';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
|
||||
const app = express();
|
||||
const port = 9999;
|
||||
|
||||
app.use(cors()).use(express.json());
|
||||
|
||||
app.get("/", (req, res) => {
|
||||
let html = `<!DOCTYPE html><head>
|
||||
<style>
|
||||
body { background: #fff; color: #000; }
|
||||
@media (prefers-color-scheme: dark) {
|
||||
body { background: #111; color: #eee; }
|
||||
a { color: #7295f6; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h2 style="margin-bottom: 5px">Targets:</h2>
|
||||
<ul style="margin: 0; padding-left: 0; list-style-position: inside">
|
||||
${Object.keys(targets).map(key => `<li><a href="/wake/${key}">${key}</a></li>`).join("")}
|
||||
</ul>
|
||||
</body>`;
|
||||
res.send(html);
|
||||
});
|
||||
|
||||
app.get("/targets", (req, res) => {
|
||||
res.json(Object.keys(targets));
|
||||
res.json(targets);
|
||||
});
|
||||
|
||||
app.post("/wake", (req, res) => {
|
||||
@@ -62,14 +48,12 @@ app.get("/wake", (req, res) => {
|
||||
});
|
||||
|
||||
app.get("/wake/:name", (req, res) => {
|
||||
const name = req.params.name;
|
||||
const mac = targets[name];
|
||||
|
||||
if (!mac) {
|
||||
const target = targets[req.params.name];
|
||||
if (!target?.mac) {
|
||||
return res.status(404).json({ status: "error", message: "Unknown target" });
|
||||
}
|
||||
|
||||
sendWolPacket(mac)
|
||||
sendWolPacket(target.mac)
|
||||
.then(() => res.json({ status: "ok" }))
|
||||
.catch(err => {
|
||||
console.error(err);
|
||||
@@ -77,6 +61,17 @@ app.get("/wake/:name", (req, res) => {
|
||||
});
|
||||
});
|
||||
|
||||
app.get("/status/:name", (req, res) => {
|
||||
const target = targets[req.params.name];
|
||||
if (!target?.ip) {
|
||||
return res.json({ isUp: null });
|
||||
}
|
||||
|
||||
ping(target.ip).then(isUp => res.json({ isUp }));
|
||||
});
|
||||
|
||||
app.use(express.static(path.join(__dirname, 'public')));
|
||||
|
||||
app.listen(port, () => {
|
||||
console.log('WOL server running on port ' + port);
|
||||
});
|
||||
Reference in New Issue
Block a user