aboutsummaryrefslogtreecommitdiffstats
path: root/static/modules/xbox.js
diff options
context:
space:
mode:
Diffstat (limited to 'static/modules/xbox.js')
-rw-r--r--static/modules/xbox.js249
1 files changed, 248 insertions, 1 deletions
diff --git a/static/modules/xbox.js b/static/modules/xbox.js
index 3350f52..7e2f075 100644
--- a/static/modules/xbox.js
+++ b/static/modules/xbox.js
@@ -14,6 +14,9 @@
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+import { offline } from "../offline.js";
+import { hold } from "../hold.js";
+
const SESSION_KEY = "deckit-xbox-session";
// A game session on the Xbox brings this tab forward once and leaves it
@@ -25,4 +28,248 @@ export function sessionPeek(st, store = globalThis.localStorage) {
return Infinity;
}
-export default { title: "Xbox", tab: "Xbox", interval: 5, peek: (st) => sessionPeek(st) };
+// Nerd Font (Material Design) glyphs.
+const G = {
+ xbox: "\u{F05B9}", power: "\u{F0425}", play: "\u{F040A}", pause: "\u{F03E4}",
+ vol_down: "\u{F075E}", vol_up: "\u{F075D}", mute: "\u{F0581}", unmute: "\u{F057E}",
+};
+const MEDIA = ["play", "pause", "vol_down", "vol_up", "mute", "unmute"];
+const LABEL = { play: "Play", pause: "Pause", vol_down: "Volume down", vol_up: "Volume up",
+ mute: "Mute", unmute: "Unmute" };
+const POWER = { On: ["On", "good"], ConnectedStandby: ["Standby", ""], Off: ["Off", ""],
+ SystemUpdate: ["Updating", "warn"] };
+
+function h(tag, cls, text) {
+ const e = document.createElement(tag);
+ if (cls) e.className = cls;
+ if (text != null) e.textContent = text;
+ return e;
+}
+
+// Images come straight from Microsoft's CDN; a broken one hides.
+function img(src, cls) {
+ const i = h("img", cls);
+ i.alt = "";
+ i.loading = "lazy";
+ i.referrerPolicy = "no-referrer";
+ i.onerror = () => { i.hidden = true; };
+ if (src) i.src = src;
+ else i.hidden = true;
+ return i;
+}
+
+const hours = (m) => (m == null ? "" : m < 60 ? `${m} min` : `${Math.round(m / 60)} h`);
+const gb = (b) => `${Math.round(b / 1e9)} GB`;
+function ago(iso) {
+ if (!iso) return "";
+ const s = (Date.now() - Date.parse(iso)) / 1000;
+ if (s < 3600) return `${Math.max(1, Math.round(s / 60))} min ago`;
+ if (s < 86400) return `${Math.round(s / 3600)} h ago`;
+ return `${Math.round(s / 86400)} d ago`;
+}
+function clock(since) {
+ const s = Math.max(0, Math.floor(Date.now() / 1000 - since));
+ const m = Math.floor(s / 60);
+ return `${Math.floor(m / 60)}:${String(m % 60).padStart(2, "0")}`;
+}
+
+async function post(action, body) {
+ const r = await fetch(`/api/xbox/${action}`, {
+ method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body),
+ });
+ if (!r.ok) throw new Error((await r.text()) || `${action} failed`);
+}
+
+async function send(action, id, card) {
+ const err = card.querySelector(".xb-err");
+ err.textContent = "";
+ try {
+ await post(action, { console: id });
+ } catch (e) {
+ err.textContent = e.message;
+ }
+}
+
+function presenceLine(st) {
+ const p = st.presence ?? {};
+ if (p.title) return [p.title.name, p.title.rich].filter(Boolean).join(" · ");
+ if (p.state === "Online") return "Online";
+ return p.last_seen ? `Last seen ${ago(p.last_seen.when)} · ${p.last_seen.title ?? ""}` : (p.state ?? "");
+}
+
+function consoleCard(c) {
+ const on = c.power === "On";
+ const card = h("div", "xb-card xb-console");
+ const head = h("div", "xb-chead");
+ const [label, cls] = POWER[c.power] ?? [c.power ?? "?", ""];
+ head.append(h("i", "nf xb-glyph", G.xbox), h("span", "xb-cname", c.name), h("span", `xb-pill ${cls}`, label));
+ // Tap wakes, hold turns off: a stray touch must not switch a game off.
+ const power = h("button", `ib hold xb-power${on ? " on" : ""}`, G.power);
+ power.classList.add("nf");
+ power.setAttribute("aria-label", "Power: tap to wake, hold to turn off");
+ hold(power, () => send("off", c.id, card), { tap: () => send("wake", c.id, card) });
+ head.append(power);
+ card.append(head);
+ for (const d of c.storage ?? []) {
+ const row = h("div", "xb-disk");
+ const used = d.total ? (d.total - d.free) / d.total : 0;
+ row.append(h("span", "", `${d.name} · ${gb(d.free)} free of ${gb(d.total)}`));
+ const bar = h("div", "gbar");
+ bar.append(h("i"));
+ bar.firstChild.style.width = `${Math.round(used * 100)}%`;
+ row.append(bar);
+ card.append(row);
+ }
+ if (on) {
+ const media = h("div", "xb-media");
+ for (const a of MEDIA) {
+ const b = h("button", "ib nf", G[a]);
+ b.setAttribute("aria-label", LABEL[a]);
+ b.onclick = () => send(a, c.id, card);
+ media.append(b);
+ }
+ card.append(media);
+ }
+ card.append(h("div", "xb-err"));
+ return card;
+}
+
+function nowPlaying(st) {
+ const g = st.playing;
+ const t = (st.titles ?? []).find((x) => x.id === g.id);
+ const card = h("div", "xb-card xb-now");
+ card.append(img(t?.cover, "xb-cover"));
+ const info = h("div", "xb-ninfo");
+ info.append(h("div", "xb-nlabel", "Now playing"), h("div", "xb-ntitle", g.name ?? ""),
+ h("div", "xb-nrich", g.rich ?? ""), h("div", "xb-clock num", clock(st.session)));
+ if (t) {
+ const a = t.achievements;
+ info.append(h("div", "xb-nach", `${a.score} / ${a.max} G · ${Math.round(a.pct)}%`));
+ const bar = h("div", "gbar");
+ bar.append(h("i"));
+ bar.firstChild.style.width = `${a.pct}%`;
+ info.append(bar);
+ }
+ card.append(info);
+ return card;
+}
+
+function gameTile(t) {
+ const tile = h("div", "xb-game");
+ tile.append(img(t.cover, "xb-gcover"), h("div", "xb-gname", t.name ?? ""));
+ if (t.type === "Game") {
+ const a = t.achievements;
+ const bar = h("div", "gbar");
+ bar.append(h("i"));
+ bar.firstChild.style.width = `${a.pct}%`;
+ tile.append(bar, h("div", "xb-gmeta", [`${a.score}/${a.max} G`, hours(t.minutes)].filter(Boolean).join(" · ")));
+ } else {
+ tile.append(h("div", "xb-gmeta", ago(t.last)));
+ }
+ return tile;
+}
+
+function row(pic, title, sub, side, cls = "") {
+ const r = h("div", `xb-row ${cls}`);
+ const text = h("div", "xb-rtext");
+ text.append(h("div", "xb-rtitle", title ?? ""), h("div", "xb-rsub", sub ?? ""));
+ r.append(img(pic, "xb-rpic"), text, h("span", "xb-rside", side ?? ""));
+ return r;
+}
+
+function signIn(box, st) {
+ box.textContent = "";
+ const wrap = h("div", "xb-login");
+ wrap.append(h("i", "nf xb-logo", G.xbox), h("div", "xb-ltitle", "Sign in to Xbox"));
+ if (st.login) {
+ wrap.append(h("div", "xb-lhint", `On any device, open ${st.login.url} and enter`),
+ h("div", "xb-code num", st.login.code));
+ } else {
+ const b = h("button", "ib xb-lbtn", "Sign in");
+ const err = h("div", "xb-err");
+ b.onclick = async () => {
+ b.disabled = true;
+ try {
+ await post("login", {});
+ } catch (e) {
+ err.textContent = e.message;
+ b.disabled = false;
+ }
+ };
+ wrap.append(h("div", "xb-lhint", "Your profile, games, friends and console appear here."), b, err);
+ }
+ box.append(wrap);
+}
+
+function render(box, st) {
+ box.textContent = "";
+ const p = st.profile ?? {};
+ const head = h("div", "xb-head");
+ const who = h("div", "xb-who");
+ who.append(h("div", "xb-tag", p.gamertag ?? ""), h("div", "xb-pres", presenceLine(st)));
+ head.append(img(p.pic, "xb-pic"), who, h("div", "xb-score num", `${p.gamerscore ?? 0} G`));
+ box.append(head);
+ if (st.stale) box.append(h("div", "xb-stale", "Xbox Live is not answering; this is the last data."));
+ const top = h("div", "xb-top");
+ if (st.playing) top.append(nowPlaying(st));
+ for (const c of st.consoles ?? []) top.append(consoleCard(c));
+ box.append(top);
+
+ box.append(h("div", "xb-section", "Recent games"));
+ const games = h("div", "xb-games");
+ for (const t of st.titles ?? []) games.append(gameTile(t));
+ box.append(games);
+
+ const lists = h("div", "xb-lists");
+ const ach = h("div", "xb-card xb-list");
+ ach.append(h("div", "xb-section", "Achievements"));
+ for (const a of st.achievements ?? []) ach.append(row(a.icon, a.name, `${a.title ?? ""} · ${ago(a.unlocked)}`, `${a.score} G`));
+ const fr = h("div", "xb-card xb-list");
+ const online = (st.friends ?? []).filter((f) => f.state === "Online").length;
+ fr.append(h("div", "xb-section", `Friends · ${online} online`));
+ for (const f of st.friends ?? []) {
+ fr.append(row(f.pic, f.gamertag, f.text, f.favorite ? "★" : "", f.state === "Online" ? "on" : ""));
+ }
+ lists.append(ach, fr);
+ box.append(lists);
+}
+
+export default {
+ title: "Xbox",
+ tab: "Xbox",
+ interval: 5,
+ peek: (st) => sessionPeek(st),
+
+ mount(el) {
+ el.innerHTML = '<div class="xbox"><div class="xb-off"></div><div class="xb-on"></div></div>';
+ },
+
+ update(st, el) {
+ const off = el.querySelector(".xb-off");
+ const on = el.querySelector(".xb-on");
+ const down = st.unconfigured || (st.offline && st.signed_in !== false);
+ off.hidden = !down;
+ on.hidden = down;
+ if (down) {
+ offline(off, st.unconfigured
+ ? { icon: "/icons/xbox.svg", title: "Xbox is not configured",
+ detail: "Set your Azure app's client id as [xbox] client_id on keystone's deck-it page." }
+ : { icon: "/icons/xbox.svg", title: "Xbox Live is not answering",
+ detail: "The tab fills in by itself once Xbox Live answers.", reason: st.reason });
+ on._key = null;
+ return;
+ }
+ // Drawn again only when the data changed: a redraw restarts the images
+ // and would cut a held power button short.
+ // ponytail: a hold across a 30s data change still restarts; key per card if it bites.
+ const key = JSON.stringify(st);
+ if (on._key !== key) {
+ on._key = key;
+ if (st.signed_in === false) signIn(on, st);
+ else if (st.loading) on.replaceChildren(h("div", "xb-loading", "Loading Xbox Live…"));
+ else render(on, st);
+ }
+ const c = on.querySelector(".xb-clock");
+ if (c) c.textContent = clock(st.session);
+ },
+};