Dough Git

commit

Move endpoint and add new features

commit
21488493225db28a4b9d2a49ed2642545f4798de
author
Clove Twilight <[email protected]>
date
2026-07-14 10:50

diff --git a/src/docs.ts b/src/docs.ts
index 46d1b82..96beacd 100644
--- a/src/docs.ts
+++ b/src/docs.ts
@@ -201,7 +201,7 @@ export const DOCS_HTML = `<!doctype html>
 <div class="wrap">
   <nav id="nav"></nav>
   <div>
-    <input id="filter" placeholder="Filter endpoints… (e.g. fronters, battery, ws)" autocomplete="off" />
+    <input id="filter" placeholder="Filter endpoints… (e.g. fronters, devices, ws)" autocomplete="off" />
     <div id="content"></div>
   </div>
 </div>
@@ -215,7 +215,7 @@ var GROUPS = [
       { m: "GET", path: "Bearer JWT", auth: "jwt",
         desc: "Most /plural write endpoints need a login token. Get one from POST /plural/login, then send it as 'Authorization: Bearer <token>'. Tokens last 24 hours. Some routes additionally require an admin, owner, or pet role." },
       { m: "GET", path: "X-Battery-Key", auth: "key",
-        desc: "Reporting a battery level (POST /battery) needs your device key, sent as the 'X-Battery-Key' header." },
+        desc: "Reporting device state (POST /devices) needs your device key, sent as the 'X-Battery-Key' header." },
       { m: "GET", path: "Bot token", auth: "bot",
         desc: "The /plural/bot/* endpoints are for the companion Discord bot: they need both a 'User-Agent: CloveShortcuts/<version>' header and the bot's token as 'Authorization: Bearer <token>'." }
     ]
@@ -384,13 +384,13 @@ var GROUPS = [
     ]
   },
   {
-    id: "battery", name: "Battery", blurb: "Latest known battery level per device.",
+    id: "devices", name: "Devices", blurb: "Latest known device state (battery, charging, low power mode, wifi).",
     endpoints: [
-      { m: "GET", path: "/battery", auth: "public", desc: "All devices → { device, level, updated_at }." },
-      { m: "GET", path: "/battery/:device", auth: "public", desc: "One device, or 404." },
-      { m: "POST", path: "/battery?device=iphone&level=25", auth: "key",
-        desc: "Report a level (0–100) for a device. Send the X-Battery-Key header.",
-        params: [["device", "1–64 chars."], ["level", "Integer 0–100."]] }
+      { m: "GET", path: "/devices", auth: "public", desc: "All devices → { device, level, charging, lowPowerMode, wifi, updated_at }." },
+      { m: "GET", path: "/devices/:device", auth: "public", desc: "One device, or 404." },
+      { m: "POST", path: "/devices?device=iphone&level=25&charging=1&lpm=0&wifi=Home", auth: "key",
+        desc: "Report device state. Only 'device' is required; supplied fields are updated, the rest untouched. Send the X-Battery-Key header.",
+        params: [["device", "1–64 chars (required)."], ["level", "Optional. Integer 0–100."], ["charging", "Optional. 1 (true) or 0 (false)."], ["lpm", "Optional. 1 (true) or 0 (false) → lowPowerMode."], ["wifi", "Optional. Any string (network name), ≤128 chars."]] }
     ]
   },
   {
diff --git a/src/index.ts b/src/index.ts
index 57e8b86..69b70f4 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -5,7 +5,7 @@
  *   /v2/lanyard/*     — live presence (Lanyard) + realtime socket
  *   /v2/discord/*     — general Discord info: profile, badges, guilds, girls
  *   /v2/plural/*      — Doughmination system API   (SystemState DO)
- *   /v2/battery/*     — device battery levels      (SystemState DO)
+ *   /v2/devices/*     — device state (battery, etc.) (SystemState DO)
  *   /v2/system-data/* — visitor logs + viewer      (SystemState DO)
  *
  * Two Durable Objects:
@@ -104,8 +104,8 @@ function isSystemPath(path: string): boolean {
   return (
     path === "/v2/plural" ||
     path.startsWith("/v2/plural/") ||
-    path === "/v2/battery" ||
-    path.startsWith("/v2/battery/") ||
+    path === "/v2/devices" ||
+    path.startsWith("/v2/devices/") ||
     path === "/v2/system-data" ||
     path.startsWith("/v2/system-data/")
   );
@@ -144,7 +144,7 @@ export default {
 
     const path = url.pathname.replace(/\/+$/, "") || "/";
 
-    // ---- SystemState DO (plural / battery / system-data) -----------------
+    // ---- SystemState DO (plural / devices / system-data) -----------------
     // Forwarded first, and untouched, so its Hono CORS + WebSocket upgrade
     // (/v2/plural/ws) work end-to-end.
     if (isSystemPath(path)) {
diff --git a/src/system/app.ts b/src/system/app.ts
index cdc5779..22482ae 100644
--- a/src/system/app.ts
+++ b/src/system/app.ts
@@ -10,7 +10,7 @@
  *
  *   /v2/plural/*        — auth, system, members, fronting, users, metrics,
  *                         admin, member status, bot, SEO (robots/sitemap)
- *   /v2/battery/*       — device battery levels        (misc)
+ *   /v2/devices/*       — device state (battery, etc.)  (misc)
  *   /v2/system-data/*   — visitor logging + log viewer (misc)
  *
  * The realtime socket /v2/plural/ws is handled by the DO before the request
@@ -35,7 +35,7 @@ import { adminRoutes } from "./routes/admin";
 import { memberStatusRoutes } from "./routes/member_status";
 import { botRoutes } from "./routes/bot";
 import { staticRoutes } from "./routes/static";
-import { batteryRoutes } from "./routes/battery";
+import { deviceRoutes } from "./routes/devices";
 import { systemDataRoutes } from "./routes/system_data";
 
 // One-time owner seed per DO lifetime (there is no startup phase on a Worker).
@@ -95,7 +95,7 @@ systemApp.onError((err, c) => {
 });
 
 systemApp.route("/v2/plural", pluralApp);
-systemApp.route("/v2/battery", batteryRoutes);
+systemApp.route("/v2/devices", deviceRoutes);
 systemApp.route("/v2/system-data", systemDataRoutes);
 
 systemApp.notFound((c) => c.json({ detail: "Unknown route." }, 404));
diff --git a/src/system/routes/battery.ts b/src/system/routes/battery.ts
deleted file mode 100644
index 501135f..0000000
--- a/src/system/routes/battery.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-/**
- * Copyright (c) 2026 Clove Twilight
- * Licensed under the ESAL-2.0 Licence.
- * See LICENCE.md in the project root for full licence information.
- */
-
-/**
- * Device battery levels. Mounted at /v2/battery.
- *   POST /v2/battery?device=iphone&level=25   (X-Battery-Key required)
- *   GET  /v2/battery                          (public, all devices)
- *   GET  /v2/battery/:device                  (public, one device)
- */
-
-import { Hono } from "hono";
-
-import type { Env } from "../hono";
-import { getAllLevels, getDeviceLevel, setDeviceLevel } from "../services/battery";
-import { verifyBatteryAccess } from "../middleware/auth";
-
-export const batteryRoutes = new Hono<Env>();
-
-batteryRoutes.post("/", verifyBatteryAccess, async (c) => {
-  const device = c.req.query("device");
-  const levelRaw = c.req.query("level");
-
-  if (typeof device !== "string" || device.length < 1 || device.length > 64) {
-    return c.json({ detail: "Query param 'device' must be a string between 1 and 64 characters" }, 422);
-  }
-
-  const level = Number(levelRaw);
-  if (typeof levelRaw !== "string" || Number.isNaN(level) || level < 0 || level > 100) {
-    return c.json({ detail: "Query param 'level' must be an integer between 0 and 100" }, 422);
-  }
-
-  const record = await setDeviceLevel(device, level);
-  return c.json({ success: true, ...record });
-});
-
-batteryRoutes.get("/", async (c) => {
-  const levels = await getAllLevels();
-  const result: Record<string, unknown> = {};
-  for (const [device, record] of Object.entries(levels)) {
-    result[device] = { device, ...record };
-  }
-  return c.json(result);
-});
-
-batteryRoutes.get("/:device", async (c) => {
-  const device = c.req.param("device");
-  const record = await getDeviceLevel(device);
-  if (record === null) {
-    return c.json({ detail: `No battery level recorded for device '${device}'` }, 404);
-  }
-  return c.json({ device, ...record });
-});
diff --git a/src/system/routes/devices.ts b/src/system/routes/devices.ts
new file mode 100644
index 0000000..6dcf0b4
--- /dev/null
+++ b/src/system/routes/devices.ts
@@ -0,0 +1,94 @@
+/**
+ * Copyright (c) 2026 Clove Twilight
+ * Licensed under the ESAL-2.0 Licence.
+ * See LICENCE.md in the project root for full licence information.
+ */
+
+/**
+ * Device state. Mounted at /v2/devices.
+ *   POST /v2/devices?device=iphone&level=25&charging=1&lpm=0   (X-Battery-Key required)
+ *   GET  /v2/devices                                           (public, all devices)
+ *   GET  /v2/devices/:device                                   (public, one device)
+ *
+ * Only `device` is required on POST. `level`, `charging` and `lpm` are each
+ * optional — any supplied field is updated, the rest are left untouched.
+ *   level    — integer 0–100
+ *   charging — 1 (true) or 0 (false)
+ *   lpm      — 1 (true) or 0 (false), stored as `lowPowerMode`
+ *   wifi     — any string (the network name), 0–128 chars
+ */
+
+import { Hono } from "hono";
+
+import type { Env } from "../hono";
+import { getAllLevels, getDeviceLevel, setDeviceLevel } from "../services/devices";
+import { verifyBatteryAccess } from "../middleware/auth";
+
+export const deviceRoutes = new Hono<Env>();
+
+/** Parse a "1"/"0" flag query param. Returns undefined if absent, null if invalid. */
+function parseFlag(raw: string | undefined): boolean | null | undefined {
+  if (raw === undefined) return undefined;
+  if (raw === "1") return true;
+  if (raw === "0") return false;
+  return null;
+}
+
+deviceRoutes.post("/", verifyBatteryAccess, async (c) => {
+  const device = c.req.query("device");
+  if (typeof device !== "string" || device.length < 1 || device.length > 64) {
+    return c.json({ detail: "Query param 'device' must be a string between 1 and 64 characters" }, 422);
+  }
+
+  const patch: { level?: number; charging?: boolean; lowPowerMode?: boolean; wifi?: string } = {};
+
+  const levelRaw = c.req.query("level");
+  if (levelRaw !== undefined) {
+    const level = Number(levelRaw);
+    if (levelRaw === "" || !Number.isInteger(level) || level < 0 || level > 100) {
+      return c.json({ detail: "Query param 'level' must be an integer between 0 and 100" }, 422);
+    }
+    patch.level = level;
+  }
+
+  const charging = parseFlag(c.req.query("charging"));
+  if (charging === null) {
+    return c.json({ detail: "Query param 'charging' must be 1 (true) or 0 (false)" }, 422);
+  }
+  if (charging !== undefined) patch.charging = charging;
+
+  const lpm = parseFlag(c.req.query("lpm"));
+  if (lpm === null) {
+    return c.json({ detail: "Query param 'lpm' must be 1 (true) or 0 (false)" }, 422);
+  }
+  if (lpm !== undefined) patch.lowPowerMode = lpm;
+
+  const wifi = c.req.query("wifi");
+  if (wifi !== undefined) {
+    if (wifi.length > 128) {
+      return c.json({ detail: "Query param 'wifi' must be 128 characters or fewer" }, 422);
+    }
+    patch.wifi = wifi;
+  }
+
+  const record = await setDeviceLevel(device, patch);
+  return c.json({ success: true, ...record });
+});
+
+deviceRoutes.get("/", async (c) => {
+  const levels = await getAllLevels();
+  const result: Record<string, unknown> = {};
+  for (const [device, record] of Object.entries(levels)) {
+    result[device] = { device, ...record };
+  }
+  return c.json(result);
+});
+
+deviceRoutes.get("/:device", async (c) => {
+  const device = c.req.param("device");
+  const record = await getDeviceLevel(device);
+  if (record === null) {
+    return c.json({ detail: `No state recorded for device '${device}'` }, 404);
+  }
+  return c.json({ device, ...record });
+});
diff --git a/src/system/services/battery.ts b/src/system/services/battery.ts
deleted file mode 100644
index 0cb134f..0000000
--- a/src/system/services/battery.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-/**
- * Copyright (c) 2026 Clove Twilight
- * Licensed under the ESAL-2.0 Licence.
- * See LICENCE.md in the project root for full licence information.
- */
-
-/** Latest-known battery level per device (no history). DO blob store. */
-
-import { rt } from "../runtime";
-
-interface BatteryRecord {
-  level: number;
-  updated_at: string;
-}
-
-type LevelsMap = Record<string, BatteryRecord>;
-
-const KEY = "battery_levels";
-
-export async function getAllLevels(): Promise<LevelsMap> {
-  return rt().store.get<LevelsMap>(KEY, {});
-}
-
-export async function saveAllLevels(levels: LevelsMap): Promise<void> {
-  await rt().store.put(KEY, levels);
-}
-
-export async function getDeviceLevel(device: string): Promise<BatteryRecord | null> {
-  const levels = await getAllLevels();
-  return levels[device] ?? null;
-}
-
-export async function setDeviceLevel(
-  device: string,
-  level: number,
-): Promise<{ device: string } & BatteryRecord> {
-  const levels = await getAllLevels();
-  const record: BatteryRecord = { level, updated_at: new Date().toISOString() };
-  levels[device] = record;
-  await saveAllLevels(levels);
-  return { device, ...record };
-}
diff --git a/src/system/services/devices.ts b/src/system/services/devices.ts
new file mode 100644
index 0000000..1520e2a
--- /dev/null
+++ b/src/system/services/devices.ts
@@ -0,0 +1,59 @@
+/**
+ * Copyright (c) 2026 Clove Twilight
+ * Licensed under the ESAL-2.0 Licence.
+ * See LICENCE.md in the project root for full licence information.
+ */
+
+/** Latest-known device state (no history). DO blob store. */
+
+import { rt } from "../runtime";
+
+interface DeviceRecord {
+  level?: number;
+  charging?: boolean;
+  lowPowerMode?: boolean;
+  wifi?: string;
+  updated_at: string;
+}
+
+/** Fields a caller may set. All optional — only provided fields are updated. */
+type DevicePatch = Pick<DeviceRecord, "level" | "charging" | "lowPowerMode" | "wifi">;
+
+type DevicesMap = Record<string, DeviceRecord>;
+
+const KEY = "battery_levels";
+
+export async function getAllLevels(): Promise<DevicesMap> {
+  return rt().store.get<DevicesMap>(KEY, {});
+}
+
+export async function saveAllLevels(levels: DevicesMap): Promise<void> {
+  await rt().store.put(KEY, levels);
+}
+
+export async function getDeviceLevel(device: string): Promise<DeviceRecord | null> {
+  const levels = await getAllLevels();
+  return levels[device] ?? null;
+}
+
+/** Merge `patch` into the device's record, preserving any fields not supplied. */
+export async function setDeviceLevel(
+  device: string,
+  patch: DevicePatch,
+): Promise<{ device: string } & DeviceRecord> {
+  const levels = await getAllLevels();
+  const existing = levels[device] ?? {};
+
+  const record: DeviceRecord = {
+    ...existing,
+    ...(patch.level !== undefined ? { level: patch.level } : {}),
+    ...(patch.charging !== undefined ? { charging: patch.charging } : {}),
+    ...(patch.lowPowerMode !== undefined ? { lowPowerMode: patch.lowPowerMode } : {}),
+    ...(patch.wifi !== undefined ? { wifi: patch.wifi } : {}),
+    updated_at: new Date().toISOString(),
+  };
+
+  levels[device] = record;
+  await saveAllLevels(levels);
+  return { device, ...record };
+}