commit 6db1db70a0596dd8ce5830fd5e419cd766c2973e Author: Claude Date: Sat Sep 26 12:40:01 2026 +0000 Add local ADB web remote for Android TV Node/Express server shells out to adb (connect/pair/keyevent/text/app launch) and serves a mobile-first installable PWA remote: power, mute, input switch, volume/channel rockers, D-pad, media transport, text entry, and one-tap streaming app launch. Supports multiple saved TVs and the Android 11+ wireless-debugging pairing flow. Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01RSVyYcrjrbmrMKT85G4fyn diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6b34b5f --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +node_modules/ +data/devices.json +*.log +.DS_Store diff --git a/README.md b/README.md new file mode 100644 index 0000000..970cdf0 --- /dev/null +++ b/README.md @@ -0,0 +1,94 @@ +# TV ADB Remote + +A slick, installable web remote for Android TV, controlled over ADB. Run a +small Node server on any always-on machine on your home network (a Pi, NAS, +old laptop, home server); point your phone's browser at it and control the +TV from a mobile-optimized PWA. + +Why a local web app instead of a native Android app: Android TV only +exposes control over ADB once you enable network debugging, and the +official ADB tooling is a desktop program. Rather than reimplement the ADB +protocol inside a phone app, this runs `adb` on a machine that already has +it, and serves a touch-friendly remote UI to any phone/tablet browser on the +LAN. Add to the home screen and it behaves like an installed app. + +## Features + +- Power, mute, input switch, volume rocker, channel rocker +- D-pad navigation, OK, back, home, menu +- Media transport (rewind / play-pause / fast-forward) +- Text entry (e.g. search boxes) sent as real keystrokes +- One-tap launch for common streaming apps (Netflix, YouTube, Prime Video, + Disney+, Spotify, Plex) +- Manage multiple TVs, each remembered with a friendly name +- Built-in pairing flow for Android 11+ ("Wireless debugging") +- Installable PWA with offline app shell + +## Requirements + +- Node.js 18+ and `adb` (Android platform-tools) installed **on the machine + running the server** — not on the phone. + - macOS: `brew install android-platform-tools` + - Debian/Ubuntu: `sudo apt install android-tools-adb` (or + `android-sdk-platform-tools`) + - Windows: download "SDK Platform-Tools" from developer.android.com and + put `adb.exe` on PATH +- The TV and this server on the same local network. + +## Set up the TV + +1. On the Android TV: Settings → System (or Device Preferences) → About → + tap "Build" repeatedly to enable Developer options. +2. Settings → Developer options → turn on **Network debugging** (older + Android TV) or **Settings → System → Developer options → Wireless + debugging** (Android 11+ / Google TV). +3. Note the IP address shown (Settings → Network & Internet). + - Android TV ≤ 10: that's it — the debug port (5555) is open. + - Android 11+ / Google TV: it shows a separate pairing IP:port and a + 6-digit code. Use the app's "Pair a new Android 11+ TV" flow, then add + the TV using its regular IP (still port 5555 once paired). + +## Run the server + +```sh +cd server +npm install +npm start +``` + +This serves the app at `http://:8787`. Open that URL +on your phone, add your TV by IP in Settings (⚙), then optionally "Add to +Home Screen" for a full-screen, app-like remote. + +Override the port with `PORT=9000 npm start`, or point at a non-default +`adb` binary with `ADB_BIN=/path/to/adb npm start`. + +## Development + +```sh +cd server +npm test +``` + +Runs the server's unit tests (command construction, input validation, +device persistence) using Node's built-in test runner — no real TV +required. + +## Project layout + +``` +server/ Express app + ADB bridge (source of truth for control logic) + src/adb.js Thin wrapper around the `adb` CLI (connect/pair/keyevent/…) + src/keycodes.js Android KeyEvent constants used by the remote buttons + src/deviceStore.js Persists saved TVs to data/devices.json + src/index.js HTTP API + static file serving + test/ Node test runner specs +public/ The PWA served to phones (HTML/CSS/vanilla JS, no build step) +scripts/ One-off dev scripts (icon generation) +``` + +## Security note + +This server has no authentication and will happily run `adb` commands +against whatever IP you give it — it's designed to sit on your trusted home +LAN, not the public internet. Don't port-forward it. diff --git a/public/app.js b/public/app.js new file mode 100644 index 0000000..2da25dd --- /dev/null +++ b/public/app.js @@ -0,0 +1,263 @@ +const APPS = [ + { name: "Netflix", package: "com.netflix.ninja" }, + { name: "YouTube", package: "com.google.android.youtube.tv" }, + { name: "Prime Video", package: "com.amazon.amazonvideo.livingroom" }, + { name: "Disney+", package: "com.disney.disneyplus" }, + { name: "Spotify", package: "com.spotify.tv.android" }, + { name: "Plex", package: "com.plexapp.android" }, +]; + +const state = { + devices: [], + selectedId: localStorage.getItem("selectedDeviceId") || null, +}; + +const els = { + deviceSelect: document.getElementById("deviceSelect"), + statusDot: document.getElementById("statusDot"), + settingsBtn: document.getElementById("settingsBtn"), + settingsDialog: document.getElementById("settingsDialog"), + closeSettings: document.getElementById("closeSettings"), + deviceList: document.getElementById("deviceList"), + addDeviceForm: document.getElementById("addDeviceForm"), + newDeviceName: document.getElementById("newDeviceName"), + newDeviceHost: document.getElementById("newDeviceHost"), + pairForm: document.getElementById("pairForm"), + pairHost: document.getElementById("pairHost"), + pairCode: document.getElementById("pairCode"), + settingsMessage: document.getElementById("settingsMessage"), + searchForm: document.getElementById("searchForm"), + searchInput: document.getElementById("searchInput"), + appsRow: document.getElementById("appsRow"), + toast: document.getElementById("toast"), +}; + +function setSettingsMessage(text, isError = false) { + els.settingsMessage.textContent = text; + els.settingsMessage.classList.toggle("error", isError); +} + +function showToast(message) { + els.toast.textContent = message; + els.toast.classList.add("show"); + clearTimeout(showToast._t); + showToast._t = setTimeout(() => els.toast.classList.remove("show"), 1800); +} + +function vibrate() { + if (navigator.vibrate) navigator.vibrate(12); +} + +async function api(path, options) { + const res = await fetch(`/api${path}`, { + headers: { "Content-Type": "application/json" }, + ...options, + }); + const body = await res.json().catch(() => ({})); + if (!res.ok) { + throw new Error(body.error || `Request failed (${res.status})`); + } + return body; +} + +function currentDevice() { + return state.devices.find((d) => d.id === state.selectedId) || null; +} + +function renderDeviceSelect() { + els.deviceSelect.innerHTML = ""; + if (!state.devices.length) { + const opt = document.createElement("option"); + opt.textContent = "No TVs added — tap ⚙"; + els.deviceSelect.appendChild(opt); + els.statusDot.className = "status-dot"; + return; + } + for (const d of state.devices) { + const opt = document.createElement("option"); + opt.value = d.id; + opt.textContent = d.name; + els.deviceSelect.appendChild(opt); + } + if (!state.selectedId || !state.devices.some((d) => d.id === state.selectedId)) { + state.selectedId = state.devices[0].id; + } + els.deviceSelect.value = state.selectedId; + localStorage.setItem("selectedDeviceId", state.selectedId); + updateStatusDot(); +} + +function updateStatusDot() { + const device = currentDevice(); + els.statusDot.className = "status-dot"; + if (device?.status === "device") els.statusDot.classList.add("online"); + else if (device) els.statusDot.classList.add("offline"); +} + +function renderDeviceList() { + els.deviceList.innerHTML = ""; + for (const d of state.devices) { + const li = document.createElement("li"); + li.innerHTML = ` +
+
${escapeHtml(d.name)}
+
${escapeHtml(d.host)} · ${d.status || "unknown"}
+
+
+ + +
+ `; + els.deviceList.appendChild(li); + } +} + +function escapeHtml(str) { + return String(str).replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c])); +} + +async function refreshDevices() { + const { devices } = await api("/devices"); + state.devices = devices; + renderDeviceSelect(); + renderDeviceList(); +} + +async function sendKey(key) { + const device = currentDevice(); + if (!device) return showToast("Add a TV first (⚙)"); + vibrate(); + try { + await api(`/devices/${device.id}/key`, { method: "POST", body: JSON.stringify({ key }) }); + } catch (err) { + showToast(err.message); + } +} + +async function launchApp(packageName, label) { + const device = currentDevice(); + if (!device) return showToast("Add a TV first (⚙)"); + vibrate(); + try { + await api(`/devices/${device.id}/app`, { method: "POST", body: JSON.stringify({ package: packageName }) }); + showToast(`Opening ${label}…`); + } catch (err) { + showToast(err.message); + } +} + +function renderApps() { + els.appsRow.innerHTML = ""; + for (const app of APPS) { + const btn = document.createElement("button"); + btn.className = "btn"; + btn.textContent = app.name; + btn.addEventListener("click", () => launchApp(app.package, app.name)); + els.appsRow.appendChild(btn); + } +} + +document.querySelectorAll("[data-key]").forEach((btn) => { + btn.addEventListener("click", () => sendKey(btn.dataset.key)); +}); + +document.querySelector('[data-action="mute"]').addEventListener("click", () => sendKey("VOLUME_MUTE")); + +els.deviceSelect.addEventListener("change", () => { + state.selectedId = els.deviceSelect.value; + localStorage.setItem("selectedDeviceId", state.selectedId); + updateStatusDot(); +}); + +els.settingsBtn.addEventListener("click", async () => { + setSettingsMessage(""); + await refreshDevices().catch((err) => showToast(err.message)); + els.settingsDialog.showModal(); +}); + +els.closeSettings.addEventListener("click", () => els.settingsDialog.close()); + +els.addDeviceForm.addEventListener("submit", async (e) => { + e.preventDefault(); + setSettingsMessage(""); + try { + const { device } = await api("/devices", { + method: "POST", + body: JSON.stringify({ name: els.newDeviceName.value.trim(), host: els.newDeviceHost.value.trim() }), + }); + els.newDeviceName.value = ""; + els.newDeviceHost.value = ""; + state.selectedId = device.id; + await refreshDevices(); + setSettingsMessage(`Added ${device.name}. Connecting…`); + await api(`/devices/${device.id}/connect`, { method: "POST" }); + setSettingsMessage(`Connected to ${device.name}.`); + await refreshDevices(); + } catch (err) { + setSettingsMessage(err.message, true); + await refreshDevices(); + } +}); + +els.deviceList.addEventListener("click", async (e) => { + const target = e.target.closest("button"); + if (!target) return; + const { action, id } = target.dataset; + setSettingsMessage(""); + try { + if (action === "connect") { + setSettingsMessage("Connecting…"); + await api(`/devices/${id}/connect`, { method: "POST" }); + setSettingsMessage("Connected."); + } else if (action === "remove") { + await api(`/devices/${id}`, { method: "DELETE" }); + } + await refreshDevices(); + } catch (err) { + setSettingsMessage(err.message, true); + await refreshDevices(); + } +}); + +els.pairForm.addEventListener("submit", async (e) => { + e.preventDefault(); + setSettingsMessage("Pairing…"); + try { + const device = currentDevice(); + if (!device) throw new Error("Add the TV's IP first, then pair."); + await api(`/devices/${device.id}/pair`, { + method: "POST", + body: JSON.stringify({ pairHost: els.pairHost.value.trim(), code: els.pairCode.value.trim() }), + }); + setSettingsMessage("Paired! Reconnecting…"); + els.pairHost.value = ""; + els.pairCode.value = ""; + await refreshDevices(); + } catch (err) { + setSettingsMessage(err.message, true); + } +}); + +els.searchForm.addEventListener("submit", async (e) => { + e.preventDefault(); + const device = currentDevice(); + const text = els.searchInput.value.trim(); + if (!device || !text) return; + try { + await api(`/devices/${device.id}/text`, { method: "POST", body: JSON.stringify({ text }) }); + els.searchInput.value = ""; + showToast("Sent"); + } catch (err) { + showToast(err.message); + } +}); + +renderApps(); +refreshDevices().catch((err) => showToast(err.message)); +setInterval(() => refreshDevices().catch(() => {}), 8000); + +if ("serviceWorker" in navigator) { + window.addEventListener("load", () => { + navigator.serviceWorker.register("/sw.js").catch(() => {}); + }); +} diff --git a/public/icons/icon-192.png b/public/icons/icon-192.png new file mode 100644 index 0000000..eab9ec4 Binary files /dev/null and b/public/icons/icon-192.png differ diff --git a/public/icons/icon-512.png b/public/icons/icon-512.png new file mode 100644 index 0000000..78f38df Binary files /dev/null and b/public/icons/icon-512.png differ diff --git a/public/index.html b/public/index.html new file mode 100644 index 0000000..08134f1 --- /dev/null +++ b/public/index.html @@ -0,0 +1,101 @@ + + + + + + TV Remote + + + + + + + + + +
+
+ + +
+ +
+ +
+
+ + + +
+ +
+ + + + + +
+ +
+ + + +
+ +
+
+ VOL + + +
+
+ CH + + +
+
+ +
+ + + +
+ + + +
+
+ + +

TVs

+
    + +
    + + + +
    + +
    + Pair a new Android 11+ TV +
    +

    On the TV: Settings → System → Developer options → Wireless debugging → Pair device with pairing code.

    + + + +
    +
    + +

    + + +
    + +
    + + + + diff --git a/public/manifest.json b/public/manifest.json new file mode 100644 index 0000000..8ec0bd2 --- /dev/null +++ b/public/manifest.json @@ -0,0 +1,14 @@ +{ + "name": "TV Remote", + "short_name": "TV Remote", + "description": "ADB-powered remote control for Android TV", + "start_url": "/", + "display": "standalone", + "background_color": "#0b0d12", + "theme_color": "#0b0d12", + "orientation": "portrait", + "icons": [ + { "src": "/icons/icon-192.png", "sizes": "192x192", "type": "image/png", "purpose": "any maskable" }, + { "src": "/icons/icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "any maskable" } + ] +} diff --git a/public/styles.css b/public/styles.css new file mode 100644 index 0000000..bb8d397 --- /dev/null +++ b/public/styles.css @@ -0,0 +1,356 @@ +:root { + --bg: #0b0d12; + --surface: #161a23; + --surface-raised: #1e2430; + --accent: #58d68d; + --accent-dim: #2e3a4a; + --text: #eef1f6; + --text-dim: #8a93a3; + --danger: #e0605a; + --radius: 20px; + color-scheme: dark; +} + +* { + box-sizing: border-box; + -webkit-tap-highlight-color: transparent; +} + +html, body { + height: 100%; +} + +body { + margin: 0; + background: var(--bg); + color: var(--text); + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; + display: flex; + flex-direction: column; + min-height: 100dvh; + overscroll-behavior: none; + user-select: none; +} + +.topbar { + display: flex; + align-items: center; + justify-content: space-between; + padding: calc(env(safe-area-inset-top, 0px) + 12px) 16px 8px; + gap: 8px; +} + +.device-picker { + display: flex; + align-items: center; + gap: 8px; + flex: 1; + min-width: 0; +} + +#deviceSelect { + flex: 1; + min-width: 0; + background: var(--surface); + color: var(--text); + border: none; + border-radius: 12px; + padding: 10px 12px; + font-size: 15px; +} + +.status-dot { + width: 10px; + height: 10px; + border-radius: 50%; + background: var(--text-dim); + flex-shrink: 0; +} +.status-dot.online { background: var(--accent); } +.status-dot.offline { background: var(--danger); } + +.icon-btn { + background: var(--surface); + border: none; + color: var(--text); + font-size: 18px; + width: 42px; + height: 42px; + border-radius: 12px; +} + +.remote { + flex: 1; + display: flex; + flex-direction: column; + gap: 18px; + padding: 8px 20px calc(env(safe-area-inset-bottom, 0px) + 24px); + max-width: 420px; + width: 100%; + margin: 0 auto; +} + +.btn { + background: var(--surface); + color: var(--text); + border: none; + border-radius: 16px; + font-size: 16px; + padding: 14px 10px; + display: flex; + align-items: center; + justify-content: center; + gap: 6px; + transition: background 80ms ease, transform 80ms ease; +} + +.btn:active { + background: var(--surface-raised); + transform: scale(0.96); +} + +.row { + display: flex; + gap: 12px; +} + +.row-top .btn-round { + flex: 1; + aspect-ratio: 1; + border-radius: 50%; + font-size: 22px; +} + +.row-top .btn-round[data-key="POWER"] { + color: var(--danger); +} + +.dpad { + display: grid; + grid-template-columns: 1fr 1fr 1fr; + grid-template-rows: 1fr 1fr 1fr; + gap: 6px; + aspect-ratio: 1; + max-width: 280px; + margin: 0 auto; + width: 100%; +} + +.dpad-up { grid-area: 1 / 2 / 2 / 3; border-radius: 20px 20px 6px 6px; } +.dpad-left { grid-area: 2 / 1 / 3 / 2; border-radius: 20px 6px 6px 20px; } +.dpad-center { + grid-area: 2 / 2 / 3 / 3; + border-radius: 50%; + background: var(--accent-dim); + font-weight: 600; + letter-spacing: 0.05em; +} +.dpad-right { grid-area: 2 / 3 / 3 / 4; border-radius: 6px 20px 20px 6px; } +.dpad-down { grid-area: 3 / 2 / 4 / 3; border-radius: 6px 6px 20px 20px; } + +.row-nav .btn { + flex: 1; + font-size: 14px; +} + +.row-vol-ch { + gap: 16px; +} + +.rocker { + flex: 1; + background: var(--surface); + border-radius: 20px; + display: flex; + flex-direction: column; + align-items: center; + overflow: hidden; +} + +.rocker-label { + font-size: 11px; + letter-spacing: 0.1em; + color: var(--text-dim); + padding-top: 10px; +} + +.rocker-btn { + width: 100%; + background: transparent; + border-radius: 0; + font-size: 22px; + padding: 14px 0; +} + +.rocker-btn:active { + background: var(--surface-raised); +} + +.row-media .btn { + flex: 1; + font-size: 18px; +} + +.row-search { + gap: 10px; +} + +#searchInput { + flex: 1; + min-width: 0; + background: var(--surface); + color: var(--text); + border: none; + border-radius: 16px; + padding: 14px 16px; + font-size: 16px; +} + +.row-search .btn { + flex: 0 0 auto; + padding: 14px 18px; +} + +.apps { + display: flex; + flex-wrap: wrap; + gap: 10px; + justify-content: center; +} + +.apps .btn { + flex: 1 1 calc(33% - 10px); + font-size: 13px; + padding: 12px 6px; +} + +dialog { + border: none; + border-radius: var(--radius); + background: var(--surface); + color: var(--text); + width: min(420px, 92vw); + padding: 20px; +} + +dialog::backdrop { + background: rgba(0, 0, 0, 0.6); +} + +dialog h2 { + margin: 0 0 12px; + font-size: 18px; +} + +.device-list { + list-style: none; + margin: 0 0 16px; + padding: 0; + display: flex; + flex-direction: column; + gap: 8px; +} + +.device-list li { + display: flex; + align-items: center; + justify-content: space-between; + background: var(--surface-raised); + border-radius: 12px; + padding: 10px 12px; + gap: 8px; +} + +.device-list .device-name { + font-weight: 600; + font-size: 14px; +} + +.device-list .device-host { + font-size: 12px; + color: var(--text-dim); +} + +.device-list .device-actions { + display: flex; + gap: 6px; +} + +.device-list button { + background: var(--accent-dim); + color: var(--text); + border: none; + border-radius: 8px; + padding: 8px 10px; + font-size: 12px; +} + +.device-list button.danger { + background: transparent; + color: var(--danger); +} + +.add-device-form, .pair-form { + display: flex; + flex-direction: column; + gap: 8px; + margin-top: 8px; +} + +.add-device-form input, .pair-form input { + background: var(--surface-raised); + border: none; + border-radius: 10px; + padding: 10px 12px; + color: var(--text); + font-size: 14px; +} + +.pair-details { + margin-top: 14px; + font-size: 13px; + color: var(--text-dim); +} + +.pair-details p { + font-size: 12px; + line-height: 1.4; +} + +.settings-message { + min-height: 18px; + font-size: 13px; + color: var(--accent); +} + +.settings-message.error { + color: var(--danger); +} + +.btn-close { + width: 100%; + margin-top: 8px; + background: var(--accent-dim); +} + +.toast { + position: fixed; + left: 50%; + bottom: calc(env(safe-area-inset-bottom, 0px) + 20px); + transform: translateX(-50%) translateY(20px); + background: var(--surface-raised); + color: var(--text); + padding: 10px 16px; + border-radius: 12px; + font-size: 13px; + opacity: 0; + pointer-events: none; + transition: opacity 150ms ease, transform 150ms ease; + max-width: 85vw; + text-align: center; +} + +.toast.show { + opacity: 1; + transform: translateX(-50%) translateY(0); +} diff --git a/public/sw.js b/public/sw.js new file mode 100644 index 0000000..b7be691 --- /dev/null +++ b/public/sw.js @@ -0,0 +1,25 @@ +const CACHE = "tv-remote-shell-v1"; +const SHELL_FILES = ["/", "/styles.css", "/app.js", "/manifest.json"]; + +self.addEventListener("install", (event) => { + event.waitUntil(caches.open(CACHE).then((cache) => cache.addAll(SHELL_FILES))); + self.skipWaiting(); +}); + +self.addEventListener("activate", (event) => { + event.waitUntil( + caches.keys().then((keys) => Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k)))) + ); + self.clients.claim(); +}); + +// Network-first for API calls (never serve stale remote-control state), +// cache-first for the static shell so the app still opens offline. +self.addEventListener("fetch", (event) => { + const url = new URL(event.request.url); + if (url.pathname.startsWith("/api/")) return; + + event.respondWith( + caches.match(event.request).then((cached) => cached || fetch(event.request)) + ); +}); diff --git a/scripts/make-icons.mjs b/scripts/make-icons.mjs new file mode 100644 index 0000000..f4d6955 --- /dev/null +++ b/scripts/make-icons.mjs @@ -0,0 +1,95 @@ +// One-off generator for the PWA app icons: a rounded remote-control glyph +// on a dark background. Pure Node (zlib + zlib.crc32), no image deps. +import { deflateSync, crc32 } from "node:zlib"; +import { writeFileSync, mkdirSync } from "node:fs"; + +const BG = [11, 13, 18]; // #0b0d12 +const FG = [88, 214, 141]; // accent green +const FG_DIM = [46, 58, 74]; + +function chunk(type, data) { + const typeBuf = Buffer.from(type, "ascii"); + const len = Buffer.alloc(4); + len.writeUInt32BE(data.length, 0); + const crcInput = Buffer.concat([typeBuf, data]); + const crc = Buffer.alloc(4); + crc.writeUInt32BE(crc32(crcInput) >>> 0, 0); + return Buffer.concat([len, typeBuf, data, crc]); +} + +function inRoundedRect(x, y, w, h, left, top, right, bottom, radius) { + if (x < left || x > right || y < top || y > bottom) return false; + const cx = x < left + radius ? left + radius : x > right - radius ? right - radius : x; + const cy = y < top + radius ? top + radius : y > bottom - radius ? bottom - radius : y; + const dx = x - cx; + const dy = y - cy; + return dx * dx + dy * dy <= radius * radius || (x >= left + radius && x <= right - radius) || (y >= top + radius && y <= bottom - radius); +} + +function makeIcon(size) { + const margin = Math.round(size * 0.2); + const left = margin; + const right = size - margin; + const top = Math.round(size * 0.08); + const bottom = size - top; + const radius = Math.round(size * 0.14); + + const btnRadius = Math.max(2, Math.round(size * 0.035)); + const btnCenters = [ + [size * 0.5, size * 0.28], + [size * 0.5, size * 0.46], + [size * 0.32, size * 0.62], + [size * 0.68, size * 0.62], + [size * 0.5, size * 0.78], + ]; + + const raw = Buffer.alloc(size * (1 + size * 4)); + for (let y = 0; y < size; y++) { + let rowStart = y * (1 + size * 4); + raw[rowStart] = 0; // filter type: none + for (let x = 0; x < size; x++) { + let [r, g, b] = BG; + if (inRoundedRect(x, y, size, size, left, top, right, bottom, radius)) { + [r, g, b] = FG_DIM; + for (const [bx, by] of btnCenters) { + const dx = x - bx; + const dy = y - by; + if (dx * dx + dy * dy <= btnRadius * btnRadius) { + [r, g, b] = FG; + break; + } + } + } + const off = rowStart + 1 + x * 4; + raw[off] = r; + raw[off + 1] = g; + raw[off + 2] = b; + raw[off + 3] = 255; + } + } + + const ihdr = Buffer.alloc(13); + ihdr.writeUInt32BE(size, 0); + ihdr.writeUInt32BE(size, 4); + ihdr[8] = 8; // bit depth + ihdr[9] = 6; // color type RGBA + ihdr[10] = 0; + ihdr[11] = 0; + ihdr[12] = 0; + + const idat = deflateSync(raw); + const signature = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]); + return Buffer.concat([ + signature, + chunk("IHDR", ihdr), + chunk("IDAT", idat), + chunk("IEND", Buffer.alloc(0)), + ]); +} + +mkdirSync(new URL("../public/icons", import.meta.url), { recursive: true }); +for (const size of [192, 512]) { + const png = makeIcon(size); + writeFileSync(new URL(`../public/icons/icon-${size}.png`, import.meta.url), png); + console.log(`wrote icon-${size}.png (${png.length} bytes)`); +} diff --git a/server/package-lock.json b/server/package-lock.json new file mode 100644 index 0000000..a1595e3 --- /dev/null +++ b/server/package-lock.json @@ -0,0 +1,835 @@ +{ + "name": "tv-adb-remote-server", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "tv-adb-remote-server", + "version": "1.0.0", + "dependencies": { + "express": "^4.19.2" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/accepts": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", + "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", + "license": "MIT", + "dependencies": { + "mime-types": "~2.1.34", + "negotiator": "0.6.3" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/array-flatten": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", + "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==", + "license": "MIT" + }, + "node_modules/body-parser": { + "version": "1.20.8", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.8.tgz", + "integrity": "sha512-JNcyFQ64OiijEkPzUBTCe+hyPXUD/3LEldGQ6iF5LR1w00mx9o7xtDWHXBY2iItjdCFGoilOLNQbH943ut7pHA==", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "content-type": "~1.0.5", + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "~1.2.0", + "http-errors": "~2.0.1", + "iconv-lite": "~0.4.24", + "on-finished": "~2.4.1", + "qs": "~6.16.0", + "raw-body": "~2.5.3", + "type-is": "~1.6.18", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/content-disposition": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", + "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", + "license": "MIT", + "dependencies": { + "safe-buffer": "5.2.1" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.7.tgz", + "integrity": "sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA==", + "license": "MIT" + }, + "node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/destroy": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", + "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", + "license": "MIT", + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express": { + "version": "4.22.3", + "resolved": "https://registry.npmjs.org/express/-/express-4.22.3.tgz", + "integrity": "sha512-Bdcs4+3qlpVlx2NRn6fgX2Ue2/gGRaPeawebgclM0ERSCqDpA+owF1fdPwjJUTAJWMTuAaxjDf+hzb0/4eKvvw==", + "license": "MIT", + "dependencies": { + "accepts": "~1.3.8", + "array-flatten": "1.1.1", + "body-parser": "~1.20.5", + "content-disposition": "~0.5.4", + "content-type": "~1.0.4", + "cookie": "~0.7.1", + "cookie-signature": "~1.0.6", + "debug": "2.6.9", + "depd": "2.0.0", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "finalhandler": "~1.3.1", + "fresh": "~0.5.2", + "http-errors": "~2.0.0", + "merge-descriptors": "1.0.3", + "methods": "~1.1.2", + "on-finished": "~2.4.1", + "parseurl": "~1.3.3", + "path-to-regexp": "~0.1.13", + "proxy-addr": "~2.0.7", + "qs": "~6.16.0", + "range-parser": "~1.2.1", + "safe-buffer": "5.2.1", + "send": "~0.19.0", + "serve-static": "~1.16.2", + "setprototypeof": "1.2.0", + "statuses": "~2.0.1", + "type-is": "~1.6.18", + "utils-merge": "1.0.1", + "vary": "~1.1.2" + }, + "engines": { + "node": ">= 0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/finalhandler": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.2.tgz", + "integrity": "sha512-aA4RyPcd3badbdABGDuTXCMTtOneUCAYH/gxoYRTZlIJdF0YPWuGqiAsIrhNnnqdXGswYk6dGujem4w80UJFhg==", + "license": "MIT", + "dependencies": { + "debug": "2.6.9", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "on-finished": "~2.4.1", + "parseurl": "~1.3.3", + "statuses": "~2.0.2", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/merge-descriptors": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz", + "integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/methods": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", + "license": "MIT", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "license": "MIT" + }, + "node_modules/negotiator": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", + "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-to-regexp": { + "version": "0.1.13", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.13.tgz", + "integrity": "sha512-A/AGNMFN3c8bOlvV9RreMdrv7jsmF9XIfDeCd87+I8RNg6s78BhJxMu69NEMHBSJFxKidViTEdruRwEk/WIKqA==", + "license": "MIT" + }, + "node_modules/proxy-addr": { + "version": "2.0.8", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz", + "integrity": "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/qs": { + "version": "6.16.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.16.0.tgz", + "integrity": "sha512-h6fhOIaRrID2CbEY2fqs+7t+UXZo+MLAnU5gRIq85uFtdiUPCdsApMlHhXogKVM4HM2DVbIjGNTTYH2OcmP1vA==", + "license": "BSD-3-Clause", + "dependencies": { + "es-define-property": "^1.0.1", + "side-channel": "^1.1.1" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "2.5.3", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.3.tgz", + "integrity": "sha512-s4VSOf6yN0rvbRZGxs8Om5CWj6seneMwK3oDb4lWDH0UPhWcxwOWw5+qk24bxq87szX1ydrwylIOp2uG1ojUpA==", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.4.24", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/send": { + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/send/-/send-0.19.2.tgz", + "integrity": "sha512-VMbMxbDeehAxpOtWJXlcUS5E8iXh6QmN+BkRX1GARS3wRaXEEgzCcB10gTQazO42tpNIya8xIyNx8fll1OFPrg==", + "license": "MIT", + "dependencies": { + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "~0.5.2", + "http-errors": "~2.0.1", + "mime": "1.6.0", + "ms": "2.1.3", + "on-finished": "~2.4.1", + "range-parser": "~1.2.1", + "statuses": "~2.0.2" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/send/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/serve-static": { + "version": "1.16.3", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.3.tgz", + "integrity": "sha512-x0RTqQel6g5SY7Lg6ZreMmsOzncHFU7nhnRWkKgWuMTu5NN0DR5oruckMqRvacAN9d5w6ARnRBXl9xhDCgfMeA==", + "license": "MIT", + "dependencies": { + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "parseurl": "~1.3.3", + "send": "~0.19.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, + "node_modules/side-channel": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz", + "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4", + "side-channel-list": "^1.0.1", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", + "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "license": "MIT", + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/utils-merge": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", + "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==", + "license": "MIT", + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + } + } +} diff --git a/server/package.json b/server/package.json new file mode 100644 index 0000000..d72acc7 --- /dev/null +++ b/server/package.json @@ -0,0 +1,17 @@ +{ + "name": "tv-adb-remote-server", + "version": "1.0.0", + "description": "Local server that bridges a web/PWA remote control to Android TV over ADB", + "type": "module", + "main": "src/index.js", + "scripts": { + "start": "node src/index.js", + "test": "node --test test/*.test.js" + }, + "dependencies": { + "express": "^4.19.2" + }, + "engines": { + "node": ">=18" + } +} diff --git a/server/src/adb.js b/server/src/adb.js new file mode 100644 index 0000000..96d6456 --- /dev/null +++ b/server/src/adb.js @@ -0,0 +1,111 @@ +import { execFile } from "node:child_process"; +import { promisify } from "node:util"; + +const execFileAsync = promisify(execFile); + +const ADB_BIN = process.env.ADB_BIN || "adb"; +const EXEC_TIMEOUT_MS = 8000; + +class AdbError extends Error { + constructor(message, { code, stderr } = {}) { + super(message); + this.name = "AdbError"; + this.code = code; + this.stderr = stderr; + } +} + +function run(args) { + return execFileAsync(ADB_BIN, args, { timeout: EXEC_TIMEOUT_MS }).catch((err) => { + if (err.code === "ENOENT") { + throw new AdbError( + "adb binary not found on this machine. Install Android platform-tools and make sure `adb` is on PATH.", + { code: "ADB_NOT_FOUND" } + ); + } + throw new AdbError(err.stderr?.trim() || err.message, { + code: "ADB_COMMAND_FAILED", + stderr: err.stderr, + }); + }); +} + +// Accepts "host" or "host:port" and rejects anything that isn't a plausible +// address, since this value is passed straight to execFile as a single arg +// (no shell involved, but we still don't want to hand adb garbage). +const HOST_PORT_RE = /^[a-zA-Z0-9.\-]+(:\d{1,5})?$/; + +export function normalizeTarget(hostOrHostPort) { + const trimmed = String(hostOrHostPort || "").trim(); + if (!HOST_PORT_RE.test(trimmed)) { + throw new AdbError(`"${hostOrHostPort}" doesn't look like a valid host or host:port`, { + code: "INVALID_TARGET", + }); + } + return trimmed.includes(":") ? trimmed : `${trimmed}:5555`; +} + +export async function connect(hostOrHostPort) { + const target = normalizeTarget(hostOrHostPort); + const { stdout } = await run(["connect", target]); + const text = stdout.trim(); + // adb prints "failed to connect..." on stdout with exit code 0, so we + // have to sniff the message instead of relying on the exit status. + if (/failed|unable|cannot/i.test(text)) { + throw new AdbError(text, { code: "CONNECT_FAILED" }); + } + return { target, message: text }; +} + +export async function disconnect(hostOrHostPort) { + const target = normalizeTarget(hostOrHostPort); + const { stdout } = await run(["disconnect", target]); + return { target, message: stdout.trim() }; +} + +export async function pair(hostAndPort, code) { + if (!/^\d{6}$/.test(String(code))) { + throw new AdbError("Pairing code must be exactly 6 digits", { code: "INVALID_PAIR_CODE" }); + } + const target = normalizeTarget(hostAndPort); + const { stdout } = await run(["pair", target, String(code)]); + const text = stdout.trim(); + if (/failed|unable|cannot/i.test(text)) { + throw new AdbError(text, { code: "PAIR_FAILED" }); + } + return { target, message: text }; +} + +export async function listDevices() { + const { stdout } = await run(["devices", "-l"]); + return stdout + .split("\n") + .slice(1) + .map((line) => line.trim()) + .filter(Boolean) + .map((line) => { + const [serial, state, ...rest] = line.split(/\s+/); + return { serial, state, details: rest.join(" ") }; + }); +} + +export async function shell(serial, ...shellArgs) { + const target = normalizeTarget(serial); + return run(["-s", target, "shell", ...shellArgs]); +} + +export async function keyevent(serial, code) { + await shell(serial, "input", "keyevent", String(code)); +} + +export async function sendText(serial, text) { + // Android's `input text` treats spaces specially; %s is the documented escape. + const escaped = String(text).replace(/ /g, "%s"); + await shell(serial, "input", "text", escaped); +} + +export async function launchApp(serial, packageName) { + await shell(serial, "monkey", "-p", packageName, "-c", "android.intent.category.LAUNCHER", "1"); +} + +export { AdbError }; diff --git a/server/src/deviceStore.js b/server/src/deviceStore.js new file mode 100644 index 0000000..9aece5b --- /dev/null +++ b/server/src/deviceStore.js @@ -0,0 +1,49 @@ +import { readFile, writeFile, mkdir } from "node:fs/promises"; +import { dirname } from "node:path"; +import { randomUUID } from "node:crypto"; + +const DATA_FILE = process.env.DEVICES_FILE || new URL("../../data/devices.json", import.meta.url).pathname; + +async function load() { + try { + const raw = await readFile(DATA_FILE, "utf8"); + const parsed = JSON.parse(raw); + return Array.isArray(parsed.devices) ? parsed.devices : []; + } catch (err) { + if (err.code === "ENOENT") return []; + throw err; + } +} + +async function save(devices) { + await mkdir(dirname(DATA_FILE), { recursive: true }); + await writeFile(DATA_FILE, JSON.stringify({ devices }, null, 2), "utf8"); +} + +export async function listSavedDevices() { + return load(); +} + +export async function addSavedDevice({ name, host }) { + const devices = await load(); + const device = { id: randomUUID(), name: name || host, host }; + devices.push(device); + await save(devices); + return device; +} + +export async function removeSavedDevice(id) { + const devices = await load(); + const next = devices.filter((d) => d.id !== id); + await save(next); + return next.length !== devices.length; +} + +export async function updateSavedDevice(id, patch) { + const devices = await load(); + const idx = devices.findIndex((d) => d.id === id); + if (idx === -1) return null; + devices[idx] = { ...devices[idx], ...patch }; + await save(devices); + return devices[idx]; +} diff --git a/server/src/index.js b/server/src/index.js new file mode 100644 index 0000000..088b461 --- /dev/null +++ b/server/src/index.js @@ -0,0 +1,179 @@ +import express from "express"; +import { fileURLToPath } from "node:url"; +import { dirname, join } from "node:path"; + +import * as adb from "./adb.js"; +import { KEYCODES, isValidKeycodeName } from "./keycodes.js"; +import { + listSavedDevices, + addSavedDevice, + removeSavedDevice, + updateSavedDevice, +} from "./deviceStore.js"; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const PUBLIC_DIR = join(__dirname, "..", "..", "public"); +const PORT = process.env.PORT || 8787; + +const app = express(); +app.use(express.json()); +app.use(express.static(PUBLIC_DIR)); + +function handle(fn) { + return async (req, res) => { + try { + await fn(req, res); + } catch (err) { + const status = err.name === "AdbError" ? 502 : 400; + res.status(status).json({ error: err.message, code: err.code }); + } + }; +} + +async function requireDevice(req) { + const devices = await listSavedDevices(); + const device = devices.find((d) => d.id === req.params.id); + if (!device) { + const err = new Error("Unknown device id"); + err.code = "DEVICE_NOT_FOUND"; + throw err; + } + return device; +} + +app.get("/api/health", (req, res) => res.json({ ok: true })); + +app.get("/api/keycodes", (req, res) => res.json({ keycodes: Object.keys(KEYCODES) })); + +app.get( + "/api/devices", + handle(async (req, res) => { + const [saved, live] = await Promise.all([listSavedDevices(), adb.listDevices().catch(() => [])]); + const liveBySerial = new Map(live.map((d) => [d.serial, d])); + const merged = saved.map((d) => { + const port = d.host.includes(":") ? d.host : `${d.host}:5555`; + const liveMatch = liveBySerial.get(port); + return { ...d, status: liveMatch?.state || "disconnected" }; + }); + res.json({ devices: merged }); + }) +); + +app.post( + "/api/devices", + handle(async (req, res) => { + const { name, host } = req.body || {}; + if (!host) { + const err = new Error("host is required"); + err.code = "MISSING_HOST"; + throw err; + } + adb.normalizeTarget(host); // validate early with a clear error + const device = await addSavedDevice({ name, host }); + res.status(201).json({ device }); + }) +); + +app.delete( + "/api/devices/:id", + handle(async (req, res) => { + const removed = await removeSavedDevice(req.params.id); + if (!removed) return res.status(404).json({ error: "Unknown device id" }); + res.json({ ok: true }); + }) +); + +app.post( + "/api/devices/:id/connect", + handle(async (req, res) => { + const device = await requireDevice(req); + const result = await adb.connect(device.host); + res.json(result); + }) +); + +app.post( + "/api/devices/:id/disconnect", + handle(async (req, res) => { + const device = await requireDevice(req); + const result = await adb.disconnect(device.host); + res.json(result); + }) +); + +app.post( + "/api/devices/:id/pair", + handle(async (req, res) => { + const device = await requireDevice(req); + const { pairHost, code } = req.body || {}; + if (!pairHost || !code) { + const err = new Error("pairHost and code are required"); + err.code = "MISSING_PAIR_INFO"; + throw err; + } + const result = await adb.pair(pairHost, code); + // Once paired, Android TV also opens the normal debugging port, so try + // connecting on the device's saved host right after. + await adb.connect(device.host).catch(() => {}); + res.json(result); + }) +); + +app.post( + "/api/devices/:id/key", + handle(async (req, res) => { + const device = await requireDevice(req); + const { key } = req.body || {}; + if (!isValidKeycodeName(key)) { + const err = new Error(`Unknown key "${key}"`); + err.code = "UNKNOWN_KEY"; + throw err; + } + await adb.keyevent(device.host, KEYCODES[key]); + res.json({ ok: true, key }); + }) +); + +app.post( + "/api/devices/:id/text", + handle(async (req, res) => { + const device = await requireDevice(req); + const { text } = req.body || {}; + if (typeof text !== "string" || !text.length) { + const err = new Error("text is required"); + err.code = "MISSING_TEXT"; + throw err; + } + await adb.sendText(device.host, text); + res.json({ ok: true }); + }) +); + +app.post( + "/api/devices/:id/app", + handle(async (req, res) => { + const device = await requireDevice(req); + const { package: packageName } = req.body || {}; + if (!packageName) { + const err = new Error("package is required"); + err.code = "MISSING_PACKAGE"; + throw err; + } + await adb.launchApp(device.host, packageName); + res.json({ ok: true }); + }) +); + +app.patch( + "/api/devices/:id", + handle(async (req, res) => { + const { name } = req.body || {}; + const updated = await updateSavedDevice(req.params.id, { name }); + if (!updated) return res.status(404).json({ error: "Unknown device id" }); + res.json({ device: updated }); + }) +); + +app.listen(PORT, () => { + console.log(`TV ADB Remote server listening on http://0.0.0.0:${PORT}`); +}); diff --git a/server/src/keycodes.js b/server/src/keycodes.js new file mode 100644 index 0000000..56110c1 --- /dev/null +++ b/server/src/keycodes.js @@ -0,0 +1,33 @@ +// Android KeyEvent codes used by `adb shell input keyevent `. +// Reference: https://developer.android.com/reference/android/view/KeyEvent +export const KEYCODES = { + POWER: 26, + SLEEP: 223, + WAKEUP: 224, + HOME: 3, + BACK: 4, + MENU: 82, + DPAD_UP: 19, + DPAD_DOWN: 20, + DPAD_LEFT: 21, + DPAD_RIGHT: 22, + DPAD_CENTER: 23, + VOLUME_UP: 24, + VOLUME_DOWN: 25, + VOLUME_MUTE: 164, + CHANNEL_UP: 166, + CHANNEL_DOWN: 167, + TV_INPUT: 178, + TV_INPUT_HDMI_1: 243, + TV_INPUT_HDMI_2: 244, + TV_INPUT_HDMI_3: 245, + MEDIA_PLAY_PAUSE: 85, + MEDIA_REWIND: 89, + MEDIA_FAST_FORWARD: 90, + SETTINGS: 176, + INFO: 165, +}; + +export function isValidKeycodeName(name) { + return Object.prototype.hasOwnProperty.call(KEYCODES, name); +} diff --git a/server/test/adb.test.js b/server/test/adb.test.js new file mode 100644 index 0000000..54f063c --- /dev/null +++ b/server/test/adb.test.js @@ -0,0 +1,36 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import * as adb from "../src/adb.js"; + +test("normalizeTarget adds default port 5555", () => { + assert.equal(adb.normalizeTarget("192.168.1.50"), "192.168.1.50:5555"); +}); + +test("normalizeTarget keeps an explicit port", () => { + assert.equal(adb.normalizeTarget("192.168.1.50:5556"), "192.168.1.50:5556"); +}); + +test("normalizeTarget trims whitespace", () => { + assert.equal(adb.normalizeTarget(" 192.168.1.50 "), "192.168.1.50:5555"); +}); + +test("normalizeTarget rejects shell-hostile input", () => { + assert.throws(() => adb.normalizeTarget("1.2.3.4; rm -rf /"), /doesn't look like/); +}); + +test("normalizeTarget rejects empty input", () => { + assert.throws(() => adb.normalizeTarget(""), /doesn't look like/); +}); + +test("connect() rejects cleanly against a closed local port instead of hanging", async () => { + // Nothing listens on 5599 locally, so `adb connect` should fail fast with + // a normal error rather than the process throwing an unhandled exception. + await assert.rejects(adb.connect("127.0.0.1:5599"), (err) => { + assert.equal(err.name, "AdbError"); + return true; + }); +}); + +test("pair() rejects a non-6-digit code before touching adb", async () => { + await assert.rejects(adb.pair("127.0.0.1:5599", "12"), /6 digits/); +}); diff --git a/server/test/deviceStore.test.js b/server/test/deviceStore.test.js new file mode 100644 index 0000000..a43578e --- /dev/null +++ b/server/test/deviceStore.test.js @@ -0,0 +1,34 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +test("deviceStore add/list/update/remove roundtrip", async () => { + const dir = await mkdtemp(join(tmpdir(), "tv-remote-test-")); + process.env.DEVICES_FILE = join(dir, "devices.json"); + + // Import fresh so it picks up the env var above. + const store = await import(`../src/deviceStore.js?t=${Date.now()}`); + + assert.deepEqual(await store.listSavedDevices(), []); + + const device = await store.addSavedDevice({ name: "Living Room", host: "192.168.1.50" }); + assert.equal(device.name, "Living Room"); + assert.ok(device.id); + + let list = await store.listSavedDevices(); + assert.equal(list.length, 1); + + const updated = await store.updateSavedDevice(device.id, { name: "Lounge" }); + assert.equal(updated.name, "Lounge"); + + const removed = await store.removeSavedDevice(device.id); + assert.equal(removed, true); + + list = await store.listSavedDevices(); + assert.equal(list.length, 0); + + await rm(dir, { recursive: true, force: true }); + delete process.env.DEVICES_FILE; +});