AnyBot/mobile/screen.html

402 lines
20 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<!doctype html>
<html lang="zh-Hant">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover, user-scalable=no">
<meta name="theme-color" content="#1e1d1b">
<title>Bot 的電腦</title>
<link rel="icon" href="icon.svg">
<style>
:root {
/* The app's dark 「紙」 (src/theme.rs shell, dark): the screen sits on the same warm night. */
--bg: #151412;
--bar: #1e1d1b;
--elev: #262422;
--hover: rgba(242, 240, 235, 0.08);
--line: rgba(242, 240, 235, 0.12);
--text: #f2f0eb;
--dim: rgba(242, 240, 235, 0.58);
--accent: #d88366;
--warn: #d9a441;
--ok: #6fb97d;
--font: -apple-system, BlinkMacSystemFont, "SF Pro Text", "PingFang TC", "Noto Sans TC", "Segoe UI", system-ui, sans-serif;
}
* { box-sizing: border-box; }
html, body { margin: 0; height: 100%; background: var(--bg); color: var(--text); font: 13.5px/1.4 var(--font); overflow: hidden; -webkit-font-smoothing: antialiased; }
body { display: flex; flex-direction: column; height: 100dvh; }
header {
display: flex; align-items: center; gap: 8px;
padding: 8px 12px; padding-top: max(8px, env(safe-area-inset-top));
min-height: 48px; background: var(--bar); border-bottom: 1px solid var(--line); flex: none;
}
body.embed header { min-height: 44px; padding: 6px 10px; }
header .name { font-weight: 600; font-size: 14px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
header .state { color: var(--dim); font-size: 12px; white-space: nowrap; display: flex; align-items: center; gap: 6px; }
.dot { width: 7px; height: 7px; border-radius: 50%; background: var(--dim); flex: none; }
.dot.live { background: var(--ok); box-shadow: 0 0 0 3px rgba(16, 171, 97, 0.18); }
.dot.hold { background: var(--warn); box-shadow: 0 0 0 3px rgba(217, 164, 65, 0.2); }
.grow { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 1px; }
button {
font: inherit; font-size: 13px; font-weight: 500; color: var(--text);
background: var(--elev); border: 1px solid var(--line); border-radius: 999px;
height: 30px; padding: 0 12px; cursor: pointer; white-space: nowrap;
display: inline-flex; align-items: center; justify-content: center; gap: 5px;
transition: background 0.12s, border-color 0.12s;
}
button:hover { background: var(--hover); }
button.main { background: var(--accent); border-color: var(--accent); color: #fff; font-weight: 600; }
button.main:hover { filter: brightness(1.08); }
button.hold-on { background: rgba(217, 164, 65, 0.18); border-color: var(--warn); color: var(--warn); font-weight: 600; }
button.icon { width: 30px; padding: 0; border-radius: 9px; background: transparent; border-color: transparent; color: var(--dim); }
button.icon:hover { background: var(--hover); color: var(--text); }
#screen { flex: 1; min-height: 0; position: relative; background: #000; }
#screen > div { background: #000 !important; }
#msg {
position: absolute; inset: 0; display: flex; align-items: center; justify-content: center;
text-align: center; padding: 24px; color: var(--dim); font-size: 13.5px; line-height: 1.6; pointer-events: none;
}
#type {
display: none; gap: 6px; padding: 8px 10px;
padding-bottom: max(8px, env(safe-area-inset-bottom));
background: var(--bar); border-top: 1px solid var(--line); flex-wrap: wrap; align-items: center;
}
#type.on { display: flex; }
#type input {
flex: 1 1 180px; min-width: 0; height: 32px; font: inherit; font-size: 14px; color: var(--text);
background: #0e0e0e; border: 1px solid var(--line); border-radius: 10px; padding: 0 10px; outline: none;
}
#type input:focus { border-color: var(--accent); }
/* 虛擬觸控板: a layer over the picture that takes the fingers; the pointer drawn on it. */
#pad { position: absolute; inset: 0; z-index: 5; display: none; touch-action: none; -webkit-user-select: none; user-select: none; -webkit-touch-callout: none; }
#pad.on { display: block; }
#ptr { position: absolute; z-index: 6; width: 20px; height: 20px; margin: -2px 0 0 -3px; pointer-events: none; display: none; filter: drop-shadow(0 1px 2px rgba(0,0,0,0.6)); }
#ptr.on { display: block; }
#tip {
position: absolute; z-index: 7; left: 50%; bottom: 12px; transform: translateX(-50%); max-width: calc(100% - 24px);
background: rgba(30, 29, 27, 0.92); border: 1px solid var(--line); border-radius: 14px; padding: 9px 12px;
font-size: 12.5px; line-height: 1.6; color: var(--text); pointer-events: none; opacity: 0; transition: opacity 0.3s;
}
#tip.on { opacity: 1; }
#tip b { font-weight: 600; color: var(--accent); }
/* The key bar: modifiers you tap (once: the next key; twice: locked), and the keys a phone lacks. */
#bar {
display: none; gap: 6px; padding: 8px 10px; padding-bottom: max(8px, env(safe-area-inset-bottom));
background: var(--bar); border-top: 1px solid var(--line); overflow-x: auto; scrollbar-width: none; flex: none;
}
#bar::-webkit-scrollbar { display: none; }
#bar.on { display: flex; }
#bar button { height: 36px; min-width: 40px; padding: 0 10px; border-radius: 10px; flex: none; font-size: 13px; }
#bar .sep { width: 1px; background: var(--line); margin: 4px 2px; flex: none; }
#bar button.once { background: rgba(216, 131, 102, 0.22); border-color: var(--accent); color: var(--accent); }
#bar button.lock { background: var(--accent); border-color: var(--accent); color: #fff; }
#bar button.on { background: var(--text); border-color: var(--text); color: var(--bar); }
#combos {
display: none; grid-template-columns: repeat(3, 1fr); gap: 6px; padding: 10px; background: var(--bar);
border-top: 1px solid var(--line); max-height: 40vh; overflow-y: auto; flex: none;
}
#combos.on { display: grid; }
#combos button { height: auto; min-height: 48px; flex-direction: column; gap: 2px; border-radius: 12px; padding: 6px 4px; }
#combos button small { color: var(--dim); font-size: 11px; font-weight: 400; letter-spacing: 0.5px; }
body.has-bar #type { padding-bottom: 8px; }
</style>
</head>
<body>
<header>
<button class="icon" id="back" title="關閉">✕</button>
<div class="grow">
<div class="name" id="name">Bot 的電腦</div>
<div class="state"><span class="dot" id="dot"></span><span id="state">連線中…</span></div>
</div>
<button class="main" id="take">接管</button>
<button class="icon" id="popout" title="在新分頁打開" style="display:none">↗</button>
</header>
<div id="screen"><div id="msg">正在連接畫面…</div><div id="pad"></div><svg id="ptr" viewBox="0 0 20 20"><path d="M3 2 L3 16 L7 12.5 L9.6 18 L12 17 L9.5 11.6 L14.5 11.6 Z" fill="#fff" stroke="#111" stroke-width="1.2" stroke-linejoin="round"/></svg><div id="tip"></div></div>
<div id="combos"></div>
<div id="type">
<input id="text" placeholder="輸入文字(支援中文輸入法),按 Enter 送出到電腦" autocomplete="off" enterkeyhint="send">
<button class="main" id="send">送出</button>
</div>
<div id="bar"></div>
<script type="module">
import RFB from "./novnc.js";
import { trackpad, MODS, KEYS, COMBOS, comboLabel, modState } from "./trackpad.js";
const q = new URLSearchParams(location.hash.slice(1));
const sq = new URLSearchParams(location.search);
const embed = q.get("embed") === "1" || sq.get("embed") === "1" || window.parent !== window;
if (embed) document.body.classList.add("embed");
const name = q.get("name") || "Bot 的電腦";
const token = localStorage.getItem("anybot.token") || "";
const wsBase = (location.protocol === "https:" ? "wss://" : "ws://") + location.host;
// The lasting login never rides in the connection's address (addresses end up in logs): a
// ticket good for this one screen, for a few minutes, is asked for first. (An older server
// that has none still gets the login, as before.)
async function ticketFor(path, body) {
try {
const r = await fetch(path, {method: "POST", headers: {"Authorization": "Bearer " + token, "Content-Type": "application/json"}, body: JSON.stringify(body)});
return r.ok ? ((await r.json()).ticket || "") : "";
} catch (_) { return ""; }
}
const lan = q.get("lan") === "1";
const host = q.get("host") || "";
// 每個 Bot 一個螢幕: the bot whose screen this is (the AnyBot shows its own screen, or the shared one).
const botq = /^\d+$/.test(q.get("bot") || "") ? "&bot=" + q.get("bot") : "";
// The ticket this page holds. Every connection — the first and each reconnect — gets a fresh
// one: on 區網 a new one-use ticket with this phone's login; through the account, the held one
// swapped for a new one (the account server drops the old at once, so the ticket in this page's
// link — and the browser's history — is dead as soon as the page is up). A ticket can be swapped
// up to ten minutes after its last use; after that it is the login that asks again, or — a page
// the app opened, with no login here — the person opens the screen again from AnyBot.
let ticket = q.get("ticket") || "";
let firstTry = true;
async function swap(old) {
try {
const r = await fetch("relay/screen-ticket/renew", {method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify({ticket: old})});
if (r.ok) return { ticket: (await r.json()).ticket || "" };
if (r.status === 410) return { gone: true };
if (r.status === 404) return { old: true }; // an older server: it has no swapping
return {}; // try again in a moment
} catch (_) { return {}; }
}
// → the connection's address; "" to wait and try again (the server wasn't reached); null when
// there is nothing left to sign in with (the link's ticket is used up, and no login here).
async function address() {
const first = firstTry;
firstTry = false;
let auth;
if (lan) {
const t = token ? await ticketFor("api/vnc/ticket", {}) : (first ? ticket : "");
if (!t && !token) return null;
auth = t ? "ticket=" + encodeURIComponent(t) : "t=" + encodeURIComponent(token);
} else {
if (ticket) {
const r = await swap(ticket);
if (r.ticket) ticket = r.ticket;
else if (r.gone) ticket = "";
else if (!r.old) return "";
}
if (!ticket && token) ticket = await ticketFor("relay/screen-ticket", {host});
if (!ticket && !token) return null;
// (An older server with no tickets at all still gets the login, as before.)
auth = ticket ? "ticket=" + encodeURIComponent(ticket) : "t=" + encodeURIComponent(token);
}
return lan ? `${wsBase}/api/vnc?${auth}${botq}` : `${wsBase}/relay/vnc/${encodeURIComponent(host)}?${auth}${botq}`;
}
const $ = (id) => document.getElementById(id);
document.title = name;
$("name").textContent = name;
if (!embed) $("back").textContent = "←";
if (embed) {
$("popout").style.display = "";
$("popout").onclick = () => {
const clean = new URLSearchParams(q);
clean.delete("embed");
window.open("screen#" + clean.toString(), "_blank", "noopener");
};
}
let rfb = null, ws = null, control = q.get("control") === "1", tries = 0, connected = false, closed = false;
// X11 keysyms (the bots' computer is Linux) and the browser key codes noVNC sends beside them.
const SYM = { Return: 0xff0d, Escape: 0xff1b, Tab: 0xff09, BackSpace: 0xff08, Delete: 0xffff, Up: 0xff52, Down: 0xff54, Left: 0xff51, Right: 0xff53, Home: 0xff50, End: 0xff57, PageUp: 0xff55, PageDown: 0xff56, F11: 0xffc8, space: 0x20, ctrl: 0xffe3, alt: 0xffe9, shift: 0xffe1, super: 0xffeb };
const CODE = { Return: "Enter", Escape: "Escape", Tab: "Tab", BackSpace: "Backspace", Delete: "Delete", Up: "ArrowUp", Down: "ArrowDown", Left: "ArrowLeft", Right: "ArrowRight", Home: "Home", End: "End", PageUp: "PageUp", PageDown: "PageDown", F11: "F11", space: "Space", ctrl: "ControlLeft", alt: "AltLeft", shift: "ShiftLeft", super: "MetaLeft" };
const symOf = (k) => SYM[k] !== undefined ? SYM[k] : k.length === 1 ? k.toLowerCase().charCodeAt(0) : 0;
const codeOf = (k) => CODE[k] || (/^[a-z]$/i.test(k) ? "Key" + k.toUpperCase() : /^[0-9]$/.test(k) ? "Digit" + k : "");
const mods = modState(() => renderBar());
// Hold the modifiers down around `fn` (a key or a click), then let the once-held ones go.
function withMods(list, fn) {
if (!rfb) return;
for (const m of list) rfb.sendKey(SYM[m], CODE[m], true);
fn();
for (const m of [...list].reverse()) rfb.sendKey(SYM[m], CODE[m], false);
}
function press(key, extra = []) {
const list = [...new Set([...mods.list(), ...extra])];
withMods(list, () => rfb.sendKey(symOf(key), codeOf(key)));
mods.used();
}
// 虛擬觸控板 over noVNC: the pointer lives in the canvas's own (shown) pixels; noVNC turns them
// into the remote screen's. (Its _handleMouse* are the same calls its own mouse handling makes.)
let mask = 0, padOn = localStorage.getItem("anybot.pad") !== "0";
const BIT = { left: 1, right: 4 };
const canvas = () => rfb && rfb._canvas;
function placePtr(x, y) {
const c = canvas();
if (!c) return;
const cr = c.getBoundingClientRect(), sr = $("screen").getBoundingClientRect();
$("ptr").style.left = (cr.left - sr.left + x) + "px";
$("ptr").style.top = (cr.top - sr.top + y) + "px";
}
const pad = trackpad($("pad"), {
bounds() { const c = canvas(); return c ? { w: c.clientWidth || 1, h: c.clientHeight || 1 } : { w: 1, h: 1 }; },
move(x, y) { rfb?._handleMouseMove(x, y); },
down(x, y, b) { if (!rfb) return; mask |= BIT[b]; rfb._handleMouseButton(x, y, mask); },
up(x, y, b) { if (!rfb) return; mask &= ~BIT[b]; rfb._handleMouseButton(x, y, mask); },
click(x, y, b, n) {
if (!rfb) return;
withMods(mods.list(), () => { for (let i = 0; i < n; i++) { rfb._handleMouseButton(x, y, mask | BIT[b]); rfb._handleMouseButton(x, y, mask); } });
mods.used();
},
scroll(x, y, dx, dy) {
if (!rfb) return;
const notch = (bit, n) => { for (let i = 0; i < Math.abs(n); i++) { rfb._handleMouseButton(x, y, mask | bit); rfb._handleMouseButton(x, y, mask); } };
if (dy) notch(dy > 0 ? 16 : 8, dy);
if (dx) notch(dx > 0 ? 64 : 32, dx);
},
show: placePtr,
});
function tip() {
const n = Number(localStorage.getItem("anybot.padTip") || 0);
if (n >= 3) return;
localStorage.setItem("anybot.padTip", String(n + 1));
$("tip").innerHTML = "<b>一指</b>移動游標・<b>點一下</b>按・<b>點兩下按住</b>拖曳・<b>兩指</b>捲動・<b>兩指點</b>右鍵";
$("tip").classList.add("on");
setTimeout(() => $("tip").classList.remove("on"), 5000);
}
function showPad() {
const on = control && padOn && connected;
$("pad").classList.toggle("on", on);
$("ptr").classList.toggle("on", on);
pad.enabled = on;
if (on) { pad.center(); tip(); }
}
// The bar: 觸控板 | Ctrl Alt Shift ❖ | Esc Tab ← ↑ ↓ → ⌫ Del ⏎ Home End PgUp PgDn | 快捷鍵 ⌨
function renderBar() {
const b = $("bar");
const btn = (attrs, label, cls = "") => `<button ${attrs} class="${cls}">${label}</button>`;
b.innerHTML = btn('data-pad="1" title="觸控板:手指移動游標;關掉改成點哪裡按哪裡"', "觸控板", padOn ? "on" : "")
+ '<span class="sep"></span>'
+ MODS.linux.map(([m, l]) => btn(`data-mod="${m}"`, l, mods.get(m))).join("")
+ '<span class="sep"></span>'
+ KEYS.map(([k, l]) => btn(`data-key="${k}"`, l)).join("")
+ '<span class="sep"></span>'
+ btn('data-combos="1"', "快捷鍵", $("combos").classList.contains("on") ? "on" : "")
+ btn('data-kb="1" title="輸入文字(支援中文與貼上)"', "⌨ 打字", $("type").classList.contains("on") ? "on" : "");
}
$("combos").innerHTML = COMBOS.linux.map(([name, ms, k], i) => `<button data-combo="${i}">${name}<small>${comboLabel(ms, k, "linux")}</small></button>`).join("");
$("combos").onclick = (e) => {
const c = e.target.closest("[data-combo]");
if (!c) return;
const [, ms, k] = COMBOS.linux[Number(c.dataset.combo)];
press(k, ms);
navigator.vibrate?.(8);
};
$("bar").onclick = (e) => {
const t = e.target.closest("button");
if (!t) return;
if (t.dataset.pad) { padOn = !padOn; localStorage.setItem("anybot.pad", padOn ? "1" : "0"); showPad(); }
else if (t.dataset.mod) mods.tap(t.dataset.mod);
else if (t.dataset.key) press(t.dataset.key);
else if (t.dataset.combos) $("combos").classList.toggle("on");
else if (t.dataset.kb) { $("type").classList.toggle("on"); if ($("type").classList.contains("on")) $("text").focus(); }
renderBar();
};
function state(text, kind) { $("state").textContent = text; $("dot").className = "dot" + (kind ? " " + kind : ""); }
function message(text) { $("msg").textContent = text; $("msg").style.display = text ? "" : "none"; }
// 接管 holds the bot's screen: its steps there wait while you drive (交還給 Bot lets them go on).
const apiBase = lan ? "" : "h/" + encodeURIComponent(host) + "/";
let holding = false;
function hold(on) {
if (on === holding || !token) return;
holding = on;
const bot = /^\d+$/.test(q.get("bot") || "") ? Number(q.get("bot")) : null;
fetch(apiBase + "api/box/hold", { method: "POST", keepalive: true, headers: { Authorization: "Bearer " + token, "Content-Type": "application/json" }, body: JSON.stringify({ bot, on }) }).catch(() => {});
}
function showControl() {
$("take").textContent = control ? "交還給 Bot" : "接管";
$("take").className = control ? "hold-on" : "main";
$("bar").classList.toggle("on", control);
document.body.classList.toggle("has-bar", control);
if (!control) { $("type").classList.remove("on"); $("combos").classList.remove("on"); }
renderBar();
hold(control && connected);
showPad();
if (rfb) { rfb.viewOnly = !control; if (control && !padOn) rfb.focus(); }
if (connected) state(control ? "你在操作(Bot 會等你完成)" : "即時觀看", control ? "hold" : "live");
if (embed && window.parent !== window) {
try { window.parent.postMessage({ anybotScreen: "control", control }, location.origin); } catch (_) {}
}
}
function retry() {
tries += 1;
state("連線中斷,重新連線中…");
message(tries > 3 ? "暫時連不上這台電腦(可能正在休眠或尚未啟動)。你可以在旁邊請它喚醒,或稍後自動重試。" : "連線中斷,正在重新連線…");
setTimeout(connect, Math.min(1000 * tries, 6000));
}
async function connect() {
if (closed) return;
message("正在連接畫面…"); state("連線中…");
const url = await address();
if (closed) return;
if (url === null) {
// Nothing would ever let it in again: say so instead of knocking every few seconds.
state("連結已過期");
message("這個畫面連結已過期(斷線超過十分鐘)。請回到 AnyBot 再開一次 Bot 的電腦。");
return;
}
if (!url) { retry(); return; }
ws = new WebSocket(url);
rfb = new RFB($("screen"), ws, { shared: true });
rfb.scaleViewport = true;
rfb.resizeSession = false;
rfb.qualityLevel = 6;
rfb.compressionLevel = 2;
rfb.showDotCursor = true;
rfb.viewOnly = !control;
rfb.addEventListener("connect", () => { tries = 0; connected = true; message(""); showControl(); });
rfb.addEventListener("disconnect", () => {
rfb = null; connected = false; showPad();
if (closed) return;
retry();
});
}
$("take").onclick = () => { control = !control; showControl(); };
function send() {
const t = $("text").value;
if (!t || !ws || ws.readyState !== 1) return;
// A modifier held and one letter typed: that shortcut (Ctrl, then c → Ctrl+C), not the letter.
if (mods.list().length && [...t].length === 1) press(t);
else ws.send(t);
$("text").value = "";
}
$("send").onclick = send;
$("text").addEventListener("keydown", (e) => { if (e.key === "Enter" && !e.isComposing) { e.preventDefault(); send(); } });
$("back").onclick = () => {
closed = true;
hold(false);
if (rfb) { try { rfb.disconnect(); } catch (_) {} }
if (embed && window.parent !== window) {
window.parent.postMessage({ anybotScreen: "close" }, location.origin);
} else if (history.length > 1) {
history.back();
} else {
location.href = "./";
}
};
window.addEventListener("message", (e) => {
if (e.origin !== location.origin || !e.data) return;
if (e.data.anybotSetControl !== undefined) {
control = !!e.data.anybotSetControl;
showControl();
}
});
// Away from the page (the phone locked, another app): let the bot go on; back again, hold again.
document.addEventListener("visibilitychange", () => hold(control && connected && !document.hidden));
window.addEventListener("pagehide", () => hold(false));
window.addEventListener("resize", () => { if ($("pad").classList.contains("on")) { const p = pad.pos; placePtr(p.x, p.y); } });
showControl();
connect();
</script>
</body>
</html>