1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
|
// deck-it - the Xbox tab: Xbox Live profile, games, friends and the console
// Copyright (C) 2026 Danilo M. <danix@danix.xyz>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// 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
// there (app.js reads Infinity as "stay"). The session is remembered, so a
// reload, or leaving the tab, does not bring it back until the next one.
export function sessionPeek(st, store = globalThis.localStorage) {
if (!st.session || store.getItem(SESSION_KEY) === String(st.session)) return 0;
store.setItem(SESSION_KEY, st.session);
return Infinity;
}
// 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`);
}
// Xbox Live reports a power change some seconds late: until it does (30s at
// most), the pill says what was asked. console id -> {label, from, until}
const pending = {};
const PENDING = { wake: "Waking…", off: "Turning off…" };
async function send(action, id, card) {
const err = card.querySelector(".xb-err");
err.textContent = "";
try {
await post(action, { console: id });
if (PENDING[action]) {
const pill = card.querySelector(".xb-pill");
pending[id] = { label: PENDING[action], from: pill.dataset.power, until: Date.now() + 30000 };
pill.textContent = PENDING[action];
pill.className = "xb-pill warn";
}
} 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 ?? "");
}
// "XboxSeriesX" -> "Xbox Series X"
const model = (t) => (t ?? "").replace(/([a-z])([A-Z])/g, "$1 $2");
function consoleCard(c, apps) {
const on = c.power === "On";
const card = h("div", "xb-card xb-console");
const head = h("div", "xb-chead");
const p = pending[c.id];
const waiting = p && p.from === c.power && Date.now() < p.until;
if (!waiting) delete pending[c.id];
const [label, cls] = waiting ? [p.label, "warn"] : POWER[c.power] ?? [c.power ?? "?", ""];
const names = h("div", "xb-cnames");
const line = h("div", "xb-cline");
const pill = h("span", `xb-pill ${cls}`, label);
pill.dataset.power = c.power ?? "";
line.append(h("span", "xb-cname", c.name), pill);
names.append(line, h("div", "xb-cmodel", [model(c.type), c.region].filter(Boolean).join(" · ")));
head.append(h("i", "nf xb-glyph", G.xbox), names);
// 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);
}
const flags = h("div", "xb-flags");
for (const [on_, text] of [[c.remote, "Remote"], [c.streaming, "Streaming"]]) {
if (on_ != null) flags.append(h("span", `xb-flag${on_ ? " on" : ""}`, `${text} ${on_ ? "on" : "off"}`));
}
card.append(flags);
if (apps?.length) {
card.append(h("div", "xb-cmodel", `${apps.length} installed · ${gb(apps.reduce((n, a) => n + a.size, 0))}`));
}
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 ?? 0)}%`));
const bar = h("div", "gbar");
bar.append(h("i"));
bar.firstChild.style.width = `${a.pct ?? 0}%`;
info.append(bar);
}
card.append(info);
return card;
}
function gameTile(t) {
const tile = h("div", "xb-game");
const art = h("div", "xb-gart");
art.append(img(t.cover, "xb-gcover"));
if (t.installed) {
const badge = h("span", "xb-badge", `Installed · ${gb(t.installed.size)}`);
badge.title = [t.installed.version != null ? `v${t.installed.version}` : null,
t.installed.updated ? `updated ${ago(t.installed.updated)}` : null].filter(Boolean).join(" · ");
art.append(badge);
}
tile.append(art, 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 ?? 0}%`;
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;
}
// The viewer lives outside the redrawn part, so a data change leaves it open.
// The links are signed CDN URIs; the CDN answers octet-stream, so the link downloads.
function view(c, dlg) {
const media = c.kind === "clip" ? h("video", "xb-vmedia") : img(c.url, "xb-vmedia");
if (c.kind === "clip") Object.assign(media, { src: c.url, controls: true, autoplay: true, playsInline: true });
const a = h("a", "ib xb-vdl", "Tablet");
a.href = c.url;
a.download = `${c.id}.${c.kind === "clip" ? "mp4" : "png"}`;
a.referrerPolicy = "no-referrer";
const meta = [c.title, new Date(c.date).toLocaleString(),
c.expires ? `kept until ${new Date(c.expires).toLocaleDateString()}` : null].filter(Boolean).join(" · ");
const info = h("div", "xb-gmeta", meta);
// The PC downloads it into Pictures/Xbox or Videos/Xbox; the answer names the file.
const pc = h("button", "ib xb-vdl", "Save to PC");
pc.onclick = async () => {
pc.disabled = true;
info.textContent = "Saving…";
try {
const r = await fetch("/api/xbox/save", {
method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ id: c.id }),
});
if (!r.ok) throw new Error((await r.text()) || "save failed");
info.textContent = `Saved: ${(await r.json()).path}`;
} catch (e) {
info.textContent = e.message;
}
pc.disabled = false;
};
const foot = h("div", "xb-vfoot");
const btns = h("div", "xb-vbtns");
btns.append(pc, a);
foot.append(info, btns);
const close = h("button", "ib nf xb-vclose", "\u{F0156}");
close.setAttribute("aria-label", "Close");
close.onclick = () => dlg.close();
dlg.replaceChildren(media, foot, close);
dlg.onclose = () => dlg.replaceChildren(); // stops a clip still playing
dlg.showModal();
}
function captureTile(c, dlg) {
const tile = h("button", "xb-game xb-cap");
const art = h("div", "xb-gart");
art.append(img(c.thumb, "xb-gcover xb-ccover"));
if (c.kind === "clip") art.append(h("span", "xb-badge", `Clip · ${c.seconds ?? "?"} s`));
tile.append(art, h("div", "xb-gname", c.title ?? ""), h("div", "xb-gmeta", ago(c.date)));
tile.onclick = () => view(c, dlg);
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, dlg) {
box.textContent = "";
const p = st.profile ?? {};
const head = h("div", "xb-head");
// Xbox's profile background is the gamerpic blurred; here only its light and shade, tinted by UDT,
// behind the profile and the consoles.
const hero = h("div", "xb-hero");
if (p.pic) hero.style.setProperty("--xb-bg", `url(${JSON.stringify(p.pic)})`);
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`));
hero.append(head);
if (st.stale) hero.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, st.apps?.[c.id]));
if (!st.consoles?.length && st.reason?.startsWith("consoles")) {
top.append(h("div", "xb-stale", "Console control is unavailable: Xbox Live refused the console list."));
}
hero.append(top);
box.append(hero);
box.append(h("div", "xb-section", "Games"));
const games = h("div", "xb-games");
for (const t of st.titles ?? []) games.append(gameTile(t));
box.append(games);
if (st.captures?.length) {
box.append(h("div", "xb-section", "Captures"));
const caps = h("div", "xb-games");
for (const c of st.captures) caps.append(captureTile(c, dlg));
box.append(caps);
}
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>' +
'<dialog class="xb-view" closedby="any"></dialog></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 data change is dropped (hold.js); key per card if it bites.
// The minute is in the key so the "ago" texts move on with idle data.
const key = JSON.stringify(st) + Math.floor(Date.now() / 60000);
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, el.querySelector(".xb-view"));
}
const c = on.querySelector(".xb-clock");
if (c) c.textContent = clock(st.session);
},
};
|