feat: stats graphs, playtime, ip search against ban evasion, 150-char chat

- stats graphs for the admin and moderator panels (lib/stats.js, public/stats-view.html)
- playtime, private unless shown on the card's bio tab; set on the account page
- search accounts by ip address, only against ban evasion; mods see no addresses and each search is logged
- privacy policy for the above (terms version 2026-10-17)
- the per-second save looks only at accounts in play, with a slow sweep of the rest
- items in several dens at once; chat filter hides slurs and threats by default
- sexual usernames refused; moderators may enter full rooms; guide login allowed
- 150-character chat box (client build 55)
- fixes: gifts, trades, dens, pets in dens, den recycling, special animals' colours,
  jammer walls, settings switches; the buddy list sent at login
- the item giver, the rules screen and the art studio rework
This commit is contained in:
Burrowdev committed 2026-10-17 02:00:57 +03:00
1 parent 8400d2f928
commit 04f468af2c
56 files changed
+25667 -3894

No files matched your search

+37
View File
@@ -338,6 +338,16 @@
<p class="status" id="bio-status" role="status"></p>
</section>
<section>
<h2>Playtime</h2>
<p id="playtime-text"></p>
<div class="switch">
<div class="what"><b>Show on my card</b><span class="hint">At the top of the Bio tab, for anyone who opens your card in the game.</span></div>
<button id="playtime-public" type="button" aria-pressed="false">Private</button>
</div>
<p class="status" id="playtime-status" role="status"></p>
</section>
<section>
<h2>Discord</h2>
<p id="badges" hidden></p>
@@ -610,6 +620,7 @@
[account.online ? "Playing now" : account.lastSeen ? when(account.lastSeen) : "Not played yet", "Last seen"],
[when(account.createdAt), "Created"],
[account.logins.toLocaleString(), "Logins"],
[played(account.playtime), "Playtime"],
[`${account.animals}${ANIMALS[account.animalType] ? ` · ${ANIMALS[account.animalType]} in use` : ""}`, "Animals"],
[account.pets.toLocaleString(), "Pets"],
[account.items.toLocaleString(), "Clothing"],
@@ -638,6 +649,12 @@
return row;
}));
$("playtime-text").textContent = `You have played for ${played(account.playtime)}.`;
$("playtime-public").textContent = account.playtimePublic ? "Public" : "Private";
$("playtime-public").setAttribute("aria-pressed", String(account.playtimePublic));
$("playtime-public").setAttribute("aria-label", `Show playtime on my card: ${account.playtimePublic ? "public" : "private"}`);
$("playtime-public").disabled = false;
if (document.activeElement !== $("bio-text")) {
$("bio-text").value = account.bio;
}
@@ -1148,6 +1165,26 @@
});
$("forget-devices").addEventListener("click", () => act({action: "forgetDevices"}, "two-step-status"));
// time played, in the largest units that say it: "3 days 4 hours".
const played = seconds => {
const days = Math.floor(seconds / 86400);
const hours = Math.floor(seconds % 86400 / 3600);
const minutes = Math.floor(seconds % 3600 / 60);
const unit = (count, name) => `${count.toLocaleString()} ${name}${count === 1 ? "" : "s"}`;
if (days > 0) {
return hours > 0 ? `${unit(days, "day")} ${unit(hours, "hour")}` : unit(days, "day");
}
if (hours > 0) {
return minutes > 0 ? `${unit(hours, "hour")} ${unit(minutes, "minute")}` : unit(hours, "hour");
}
return unit(minutes, "minute");
};
$("playtime-public").addEventListener("click", async () => {
$("playtime-public").disabled = true;
await act({action: "playtimePublic", on: !account.playtimePublic}, "playtime-status");
$("playtime-public").disabled = false;
});
const bioCount = () => {
$("bio-count").textContent = `${[...$("bio-text").value.trim()].length} / ${account ? account.bioLimit : 200}`;
};
+99 -5
View File
@@ -245,6 +245,7 @@
<nav role="tablist">
<button role="tab" data-tab="overview" aria-selected="true">Overview</button>
<button role="tab" data-tab="accounts" aria-selected="false">Accounts</button>
<button role="tab" data-tab="stats" aria-selected="false">Stats</button>
<button role="tab" data-tab="reports" aria-selected="false">Reports<span id="report-count"></span></button>
<button role="tab" data-tab="support" aria-selected="false">Requests<span id="support-count"></span></button>
<button role="tab" data-tab="masterpieces" aria-selected="false">Masterpieces<span id="masterpiece-count"></span></button>
@@ -274,9 +275,17 @@
</div>
</div>
<div data-view="stats" hidden>
<!--stats-view-->
</div>
<div data-view="accounts" hidden>
<section>
<div class="toolbar">
<select id="account-search-by" aria-label="Search by">
<option value="name">By name</option>
<option value="address">By IP address</option>
</select>
<input id="account-search" type="search" placeholder="Search" aria-label="Search accounts">
<select id="account-filter" aria-label="Which accounts">
<option value="all">All</option>
@@ -284,7 +293,15 @@
<option value="banned">Banned</option>
</select>
</div>
<div class="table-wrap"><table>
<div id="address-view" hidden>
<p class="hint">Accounts that signed in from this address, or from addresses starting with it, in the last 90 days.</p>
<p class="status" id="address-status" role="status"></p>
<div class="table-wrap"><table>
<thead><tr><th>Name</th><th>State</th><th>Addresses</th><th>Last from there</th></tr></thead>
<tbody id="address-results"></tbody>
</table></div>
</div>
<div class="table-wrap" id="account-list"><table>
<thead><tr><th>Name</th><th>State</th><th>Created</th><th>Last login</th><th>Last seen</th><th class="num">Logins</th><th class="num">Animals</th><th class="num">Items</th></tr></thead>
<tbody id="accounts"></tbody>
</table></div>
@@ -744,8 +761,61 @@
return tags.length ? tags : [el("span", "Offline", "hint")];
};
// time played: "3d 4h", "2h 15m", "40m".
const played = seconds => {
const days = Math.floor(seconds / 86400);
const hours = Math.floor(seconds % 86400 / 3600);
const minutes = Math.floor(seconds % 3600 / 60);
return days > 0 ? `${days.toLocaleString()}d ${hours}h` : hours > 0 ? `${hours}h ${minutes}m` : `${minutes}m`;
};
// by IP address: the server looks through the sign-in histories.
let addressFound = null; // {query, players} or null
const searchByAddress = async () => {
const query = $("account-search").value.trim();
if (query === "") {
addressFound = null;
setStatus($("address-status"), "");
renderAccounts();
return;
}
const result = await api(`address-search?q=${encodeURIComponent(query)}`);
if (query !== $("account-search").value.trim()) {
return; // typed on meanwhile
}
addressFound = result.ok ? {query, players: result.data.players} : null;
setStatus($("address-status"), result.ok ? (result.data.players.length ? "" : "Nobody signed in from there.") : result.data.error || "That did not work.", !result.ok);
renderAccounts();
};
const renderAddressResults = () => {
const found = addressFound ? addressFound.players : [];
$("address-results").replaceChildren(...found.map(entry => {
const account = accounts.find(one => one.username === entry.username);
const row = el("tr", undefined, entry.username === selected ? "pick selected" : "pick");
const nameCell = el("td");
const pick = el("button", entry.username);
pick.type = "button";
nameCell.append(pick);
const stateCell = el("td");
if (account) {
stateCell.append(...accountState(account).flatMap(tag => [tag, " "]));
}
row.addEventListener("click", () => select(entry.username));
row.append(nameCell, stateCell, el("td", entry.addresses.map(one => one.address).join(", ")), el("td", when(entry.lastAt)));
return row;
}));
};
const renderAccounts = () => {
const query = $("account-search").value.trim().toLowerCase();
const byAddress = $("account-search-by").value === "address";
$("address-view").hidden = !byAddress;
$("account-list").hidden = byAddress;
if (byAddress) {
renderAddressResults();
$("no-accounts").hidden = true;
}
const query = byAddress ? "" : $("account-search").value.trim().toLowerCase();
const filter = $("account-filter").value;
const shown = accounts
.filter(account => account.username.toLowerCase().includes(query))
@@ -769,11 +839,13 @@
el("td", account.items.toLocaleString(), "num"));
return row;
}));
$("no-accounts").hidden = shown.length > 0;
if (!byAddress) {
$("no-accounts").hidden = shown.length > 0;
}
const current = accounts.find(account => account.username === selected);
$("detail").hidden = !current;
if (current) {
$("detail-name").textContent = `${current.username} · ${current.gems.toLocaleString()} gems`;
$("detail-name").textContent = `${current.username} · ${current.gems.toLocaleString()} gems · played ${played(current.playtime || 0)}${current.playtimePublic ? " (public)" : ""}`;
}
};
@@ -979,7 +1051,26 @@
}
});
$("account-search").addEventListener("input", renderAccounts);
let addressWait = null;
$("account-search").addEventListener("input", () => {
if ($("account-search-by").value === "address") {
clearTimeout(addressWait);
addressWait = setTimeout(searchByAddress, 400);
}
else {
renderAccounts();
}
});
$("account-search-by").addEventListener("change", () => {
const byAddress = $("account-search-by").value === "address";
$("account-search").placeholder = byAddress ? "203.0.113.7, or the start of one" : "Search";
if (byAddress) {
searchByAddress();
}
else {
renderAccounts();
}
});
$("account-filter").addEventListener("change", renderAccounts);
const act = async (username, action, extra, statusElement) => {
@@ -1378,6 +1469,9 @@
renderAccounts();
}
}
else if (tab === "stats") {
await window.statsView.load(api);
}
else if (tab === "reports") {
result = await api(`reports?handled=${$("report-filter").value}`);
if (result.ok) {
+8
View File
@@ -76,6 +76,14 @@
window.ipc.sendToHost("fps", count);
}
// an address the SWF wants open (AJClient.finderLink): the client opens
// it in the system browser, being a webview that may open no window.
function ajOpenPage(url) {
if (/^https:\/\//.test(String(url))) {
window.ipc.sendToHost("openPage", String(url));
}
}
function ajPrint(imageData) {
window.ipc.sendToHost("printImage", imageData);
}
+52 -7
View File
@@ -261,19 +261,25 @@
<button role="tab" data-tab="requests" aria-selected="false">Requests<span id="request-count"></span></button>
<button role="tab" data-tab="masterpieces" aria-selected="false">Masterpieces<span id="masterpiece-count"></span></button>
<button role="tab" data-tab="bans" aria-selected="false">Bans</button>
<button role="tab" data-tab="stats" aria-selected="false">Stats</button>
</nav>
<div data-view="players">
<section>
<div class="toolbar">
<select id="player-search-by" aria-label="Search by">
<option value="name">By name</option>
<option value="address">By IP address</option>
</select>
<input id="player-search" type="search" placeholder="Search" aria-label="Search players">
<span class="hint" id="online-count"></span>
</div>
<div class="table-wrap"><table>
<thead><tr><th>Name</th><th>State</th><th>Where</th><th>Last seen</th></tr></thead>
<thead><tr><th>Name</th><th>State</th><th>Where</th><th id="players-when">Last seen</th></tr></thead>
<tbody id="players"></tbody>
</table></div>
<div class="empty" id="no-players" hidden>No players match.</div>
<p class="hint" id="address-hint" hidden>Players who signed in from this address, or from addresses starting with it, in the last 90 days. Each search is written in the moderator log.</p>
</section>
<section id="detail" hidden>
<h2 id="detail-name"></h2>
@@ -316,6 +322,10 @@
</section>
</div>
<div data-view="stats" hidden>
<!--stats-view-->
</div>
<div data-view="chat" hidden>
<section>
<form id="chat-form" class="toolbar">
@@ -456,6 +466,13 @@
}
return "under a minute";
};
// time played: "3d 4h", "2h 15m", "40m".
const played = seconds => {
const days = Math.floor(seconds / 86400);
const hours = Math.floor(seconds % 86400 / 3600);
const minutes = Math.floor(seconds % 3600 / 60);
return days > 0 ? `${days.toLocaleString()}d ${hours}h` : hours > 0 ? `${hours}h ${minutes}m` : `${minutes}m`;
};
const left = seconds => (seconds === -1 ? "Until lifted" : seconds ? `${duration(seconds)} left` : "—");
let check = null; // the captcha (public/captcha.js), once the sign-in is shown
@@ -515,10 +532,12 @@
const row = el("tr", undefined, player.username === selected ? "pick selected" : "pick");
const stateCell = el("td");
stateCell.append(...stateTags(player).flatMap(tag => [tag, " "]));
row.append(el("td", player.username), stateCell, el("td", player.room || "—"), el("td", player.online ? "Now" : when(player.lastSeen)));
row.append(el("td", player.username), stateCell, el("td", player.room || "—"),
el("td", player.matchedAt ? when(player.matchedAt) : player.online ? "Now" : when(player.lastSeen)));
row.addEventListener("click", () => select(player.username === selected ? null : player.username));
return row;
}));
$("no-players").textContent = "No players match.";
$("no-players").hidden = players.length > 0;
};
@@ -546,6 +565,7 @@
["Where", player.online ? player.room : "Offline"],
["Last seen", player.online ? "Now" : when(player.lastSeen)],
["Joined", when(player.createdAt)],
["Playtime", played(player.playtime || 0)],
["Ban", player.banned === 0 ? "—" : `${left(player.banned)} · ${player.banReason}`],
["Chat", player.silenced === 0 ? "—" : `Silenced: ${left(player.silenced).toLowerCase()}`],
["Reports waiting", String(player.openReports)],
@@ -623,7 +643,16 @@
}
});
$("player-search").addEventListener("input", () => refresh());
// by address, asked once typing stops: each search is written down.
let searchWait = null;
$("player-search").addEventListener("input", () => {
clearTimeout(searchWait);
searchWait = setTimeout(refresh, $("player-search-by").value === "address" ? 700 : 0);
});
$("player-search-by").addEventListener("change", () => {
$("player-search").placeholder = $("player-search-by").value === "address" ? "203.0.113.7, or the start of one" : "Search";
refresh();
});
const chatUrl = before => `chat?username=${encodeURIComponent(chatQuery.username)}&room=${encodeURIComponent(chatQuery.room)}`
+ `&text=${encodeURIComponent(chatQuery.text)}&before=${before}`;
@@ -874,11 +903,24 @@
$("online-count").textContent = `${counts.data.online} playing`;
}
if (shown === "players") {
const result = await api(`players?q=${encodeURIComponent($("player-search").value.trim())}`);
if (result.ok) {
players = result.data.players;
const byAddress = $("player-search-by").value === "address";
const query = $("player-search").value.trim();
$("players-when").textContent = byAddress ? "Last from address" : "Last seen";
$("address-hint").hidden = !byAddress;
if (byAddress && query === "") {
players = [];
renderPlayers();
await loadDetail();
}
else {
const result = await api(`players?q=${encodeURIComponent(query)}${byAddress ? "&by=address" : ""}`);
players = result.ok ? result.data.players : [];
renderPlayers();
if (!result.ok && byAddress) {
$("no-players").textContent = said(result);
}
if (result.ok) {
await loadDetail();
}
}
}
else if (shown === "chat") {
@@ -905,6 +947,9 @@
renderMasterpieces(result.data);
}
}
else if (shown === "stats") {
await window.statsView.load(api);
}
else if (shown === "bans") {
const result = await api("bans");
if (result.ok) {
+11 -6
View File
@@ -161,7 +161,7 @@
<section>
<h2>1. Who is responsible</h2>
<p>The controller of your personal data is the operator of Burrow, {{operator}}. Contact for anything in this policy: {{legalEmail}}. General contact: {{adminEmail}}.</p>
<p>We do not sell data, show ads, track you across sites or send marketing. We do not collect your real name, email address or date of birth. The only statistics we see are the overall traffic figures described in section 4.</p>
<p>We do not sell data, show ads, track you across sites or send marketing. We do not collect your real name, email address or date of birth. The only statistics we keep are the game's own activity figures in section 2, which are used only to run and plan the server, and the overall traffic figures described in section 4.</p>
</section>
<section>
@@ -173,7 +173,9 @@
<tr><td>Your game data: animals, items, dens, pets, buddies, block list, trades, achievements, settings</td><td>To run the game for you</td></tr>
<tr><td>What you choose to write or make: bio, Discord username (optional), Jam-A-Grams, wall posts, paintings, feedback</td><td>To show or deliver it as you asked</td></tr>
<tr><td>Typed chat and whispers, with the room and time</td><td>Moderation: reviewing reports and deciding on bans</td></tr>
<tr><td>IP address at each sign-in, and sign-in times</td><td>Security: your sign-in history, limiting abuse, address bans</td></tr>
<tr><td>IP address at each sign-in, and sign-in times</td><td>Security: your sign-in history, limiting abuse, address bans, and finding accounts made to get around a ban</td></tr>
<tr><td>When you log in to the game, how long each visit lasts, and your total playtime</td><td>To show you your playtime, and for overall activity figures (how many people play and when) that staff use to run the server</td></tr>
<tr><td>The number of players online, counted every minute</td><td>Overall activity figures. This count is not linked to anyone</td></tr>
<tr><td>Reports, bans and their reasons, appeals, username rejections</td><td>Moderation and preventing ban evasion</td></tr>
<tr><td>2FA secret and trusted-device tokens, if you turn 2FA on</td><td>To protect your account</td></tr>
<tr><td>Technical error reports sent by the game client</td><td>Fixing bugs</td></tr>
@@ -185,9 +187,10 @@
<section>
<h2>3. Who can see it</h2>
<ul>
<li><b>Other players</b> see your username, animals, den, bio, Discord username if you add one, badges, when you joined and were last seen, your chat in the room you are in, and whether you are currently banned.</li>
<li><b>Moderators</b> can also read stored chat and whispers, reports, and ban history. They cannot see your IP address, sign-in history, password or inventory.</li>
<li><b>The administrator</b> can see everything listed in section 2.</li>
<li><b>Other players</b> see your username, animals, den, bio, Discord username if you add one, badges, when you joined and were last seen, your chat in the room you are in, whether you are currently banned, and your total playtime if you make it public on your account page (it is private unless you choose otherwise).</li>
<li><b>Moderators</b> can also read stored chat and whispers, reports, and ban history, and see your total playtime and the overall activity figures. They cannot see your IP address, sign-in history, password or inventory.</li>
<li><b>Moderators</b> can look up which accounts signed in from an IP address they already have, only to stop ban evasion: finding new accounts made by someone who is banned. The search shows only account names and when they signed in from that address, never the address itself or any other address. Every search is recorded under the moderator's name and reviewed by the administrator.</li>
<li><b>The administrator</b> can see everything listed in section 2, and can search accounts by IP address for the same purpose.</li>
<li><b>Our hosting provider</b> stores the data on our behalf, in {{hostedIn}}. If that is outside your country, your data is transferred there to provide the service.</li>
<li><b>Cloudflare</b> carries part of the traffic to this server. See section 4.</li>
</ul>
@@ -214,10 +217,12 @@
<tr><td>Handled reports, feedback and username requests</td><td>12 months</td></tr>
<tr><td>Ban records</td><td>While the account exists, then 12 months</td></tr>
<tr><td>Banned IP addresses</td><td>Until the ban is lifted</td></tr>
<tr><td>Record of game logins and visit lengths</td><td>12 months</td></tr>
<tr><td>Number of players online (not linked to anyone)</td><td>Kept indefinitely</td></tr>
<tr><td>Backups</td><td>14 days</td></tr>
</tbody>
</table></div>
<p style="margin-top:12px">When you delete your account we delete your game data, chat, appeal, feedback, username requests and paintings straight away. Your username is held for 30 days so nobody can pass as you, and ban records are kept as shown above. Copies in backups disappear within 14 days.</p>
<p style="margin-top:12px">When you delete your account we delete your game data, chat, appeal, feedback, username requests and paintings straight away, and your total playtime. Your past logins stay in the overall activity figures for up to 12 months and are not shown to anyone by name. Your username is held for 30 days so nobody can pass as you, and ban records are kept as shown above. Copies in backups disappear within 14 days.</p>
</section>
<section>
+2 -2
View File
@@ -3,7 +3,7 @@
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Item finder</title>
<title>Item giver</title>
<link rel="icon" type="image/png" href="/logo-square.png">
<style>
/* black and white throughout, in the game's own text font: the look of
@@ -147,7 +147,7 @@
<body>
<main>
<img class="logo" src="/logo.png" alt="">
<h1>Item finder</h1>
<h1>Item giver</h1>
<p class="lede">Search every clothing and den item by name or id and add it to an account for free. In-game shops only stock a slice of the catalogue each.</p>
<div class="controls">
+324
View File
@@ -0,0 +1,324 @@
<!-- the Stats tab of the admin panel (admin.html) and the moderator panel
(mod.html), put in each where it says so by lib/panel.js and
lib/modpanel.js. the numbers are lib/stats.js's; the graphs are drawn
here, in white on black like the rest. hovering a bar or a point
names its numbers. -->
<style>
.stats-tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); gap: 12px; margin-bottom: 16px; }
.stats-tile { padding: 12px 14px 11px; border: 1px solid var(--line); border-radius: 18px; min-width: 0; }
.stats-tile .value { font-size: 24px; font-weight: 700; line-height: 1.15; font-variant-numeric: tabular-nums; overflow-wrap: anywhere; }
.stats-tile .name { margin-top: 2px; font-size: 11px; letter-spacing: 0.1em; text-transform: uppercase; color: var(--muted); }
.stats-tile .sub { font-size: 12px; color: var(--muted); }
.stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 420px), 1fr)); gap: 16px; }
.stats-grid section { margin: 0; min-width: 0; }
.stats-chart { width: 100%; height: auto; display: block; }
.stats-chart text { fill: var(--muted); font: 11px "DigitalDelivery", system-ui, sans-serif; }
.stats-chart .axis { stroke: var(--line); stroke-width: 1; }
.stats-chart .bar { fill: var(--text); }
.stats-chart .bar.dim { fill: #555; }
.stats-chart .hit { fill: transparent; }
.stats-chart .hit:hover + .bar, .stats-chart .bar:hover { fill: #bbb; }
.stats-chart .line { fill: none; stroke: var(--text); stroke-width: 2; }
.stats-chart .line.dim { stroke: #666; stroke-width: 1.5; stroke-dasharray: 4 3; }
.stats-legend { display: flex; gap: 14px; flex-wrap: wrap; font-size: 12px; color: var(--muted); margin: 0 0 8px; }
.stats-legend span::before { content: ""; display: inline-block; width: 14px; height: 0; border-top: 2px solid var(--text); vertical-align: middle; margin-right: 6px; }
.stats-legend span.dim::before { border-top: 2px dashed #666; }
.stats-legend span.box::before { height: 10px; border: 0; background: var(--text); }
.stats-legend span.box.dim::before { background: #555; }
.stats-heat { display: grid; grid-template-columns: 34px repeat(24, 1fr); gap: 2px; font-size: 10px; color: var(--muted); }
.stats-heat div { aspect-ratio: 1; border-radius: 3px; min-width: 0; }
.stats-heat .label { aspect-ratio: auto; align-self: center; text-align: right; padding-right: 4px; }
.stats-heat .hour { aspect-ratio: auto; text-align: center; }
.stats-empty { color: var(--muted); padding: 24px 0; text-align: center; }
</style>
<section>
<div class="toolbar">
<select id="stats-range" aria-label="Time covered">
<option value="1">Last 24 hours</option>
<option value="7" selected>Last 7 days</option>
<option value="30">Last 30 days</option>
<option value="90">Last 90 days</option>
<option value="365">Last year</option>
</select>
<span class="hint" id="stats-note">Times are in your time zone.</span>
</div>
<div class="stats-tiles" id="stats-tiles"></div>
</section>
<div class="stats-grid">
<section>
<h2>Players online</h2>
<div class="stats-legend"><span>Average</span><span class="dim">Most at once</span></div>
<div id="stats-online"></div>
</section>
<section>
<h2>Logins</h2>
<div class="stats-legend"><span class="box">Logins</span><span class="box dim">Different players</span></div>
<div id="stats-logins"></div>
</section>
<section>
<h2>New accounts</h2>
<div id="stats-new"></div>
</section>
<section>
<h2>Busiest hours</h2>
<p class="hint">Average players online at each hour of the day.</p>
<div id="stats-hours"></div>
</section>
<section>
<h2>Week at a glance</h2>
<p class="hint">Average players online by day and hour: the lighter, the busier.</p>
<div id="stats-week"></div>
</section>
<section>
<h2>Most time played</h2>
<div class="table-wrap"><table>
<thead><tr><th>Player</th><th class="num">Playtime</th></tr></thead>
<tbody id="stats-top"></tbody>
</table></div>
<div class="stats-empty" id="stats-no-top" hidden>No playtime counted yet.</div>
</section>
</div>
<script>
(() => {
const SVG = "http://www.w3.org/2000/svg";
const W = 640;
const H = 220;
const PAD = {left: 40, right: 10, top: 10, bottom: 28};
const DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
const byId = id => document.getElementById(id);
const svgEl = (tag, attrs = {}, text) => {
const node = document.createElementNS(SVG, tag);
for (const [name, value] of Object.entries(attrs)) {
node.setAttribute(name, value);
}
if (text !== undefined) {
node.textContent = text;
}
return node;
};
const htmlEl = (tag, text, className) => {
const node = document.createElement(tag);
if (text !== undefined) {
node.textContent = text;
}
if (className) {
node.className = className;
}
return node;
};
const played = seconds => {
const days = Math.floor(seconds / 86400);
const hours = Math.floor(seconds % 86400 / 3600);
const minutes = Math.floor(seconds % 3600 / 60);
if (days > 0) {
return `${days.toLocaleString()}d ${hours}h`;
}
if (hours > 0) {
return `${hours}h ${minutes}m`;
}
return `${minutes}m`;
};
const when = (seconds, withTime = true) => (seconds
? new Date(seconds * 1000).toLocaleString([], withTime ? {dateStyle: "medium", timeStyle: "short"} : {dateStyle: "medium"}) : "—");
// A round top for the y axis, and three steps up to it.
const scale = most => {
if (most <= 0) {
return {top: 1, ticks: [0, 1]};
}
const raw = most / 4;
const power = 10 ** Math.floor(Math.log10(raw));
const step = [1, 2, 2.5, 5, 10].map(f => f * power).find(f => f >= raw) || raw;
const nice = Math.max(1, step < 1 && Number.isInteger(most) ? 1 : step);
const top = Math.ceil(most / nice) * nice;
const ticks = [];
for (let tick = 0; tick <= top + 1e-9; tick += nice) {
ticks.push(Math.round(tick * 100) / 100);
}
return {top, ticks};
};
// the frame of a chart: the y axis's lines and numbers, and up to
// `labels` evenly spaced names along the bottom.
const frame = (top, ticks, names, every) => {
const svg = svgEl("svg", {viewBox: `0 0 ${W} ${H}`, class: "stats-chart", role: "img"});
const plotH = H - PAD.top - PAD.bottom;
for (const tick of ticks) {
const y = PAD.top + plotH - tick / top * plotH;
svg.append(svgEl("line", {x1: PAD.left, x2: W - PAD.right, y1: y, y2: y, class: "axis"}));
svg.append(svgEl("text", {x: PAD.left - 6, y: y + 4, "text-anchor": "end"}, tick.toLocaleString()));
}
const plotW = W - PAD.left - PAD.right;
names.forEach((name, index) => {
if (index % every === 0) {
svg.append(svgEl("text", {x: PAD.left + (index + 0.5) * plotW / names.length, y: H - 8, "text-anchor": "middle"}, name));
}
});
return svg;
};
const labelEvery = count => Math.max(1, Math.ceil(count / 8));
// bars, one or two to a slot: [{values, dim}], names under them, and
// what hovering a slot says.
const bars = (sets, names, tip) => {
const most = Math.max(0, ...sets.flatMap(set => set.values.filter(value => value !== null)));
const {top, ticks} = scale(most);
const svg = frame(top, ticks, names, labelEvery(names.length));
const plotW = W - PAD.left - PAD.right;
const plotH = H - PAD.top - PAD.bottom;
const slot = plotW / names.length;
const width = Math.max(1, slot * 0.8 / sets.length);
names.forEach((name, index) => {
const group = svgEl("g");
group.append(svgEl("title", {}, tip(index)));
group.append(svgEl("rect", {x: PAD.left + index * slot, y: PAD.top, width: slot, height: plotH, class: "hit"}));
sets.forEach((set, which) => {
const value = set.values[index] || 0;
const height = value / top * plotH;
group.append(svgEl("rect", {x: PAD.left + index * slot + slot * 0.1 + which * width, y: PAD.top + plotH - height, width, height,
class: set.dim ? "bar dim" : "bar"}));
});
svg.append(group);
});
return svg;
};
// lines through points (null leaves a gap): [{values, dim}].
const lines = (sets, names, tip) => {
const most = Math.max(0, ...sets.flatMap(set => set.values.filter(value => value !== null)));
const {top, ticks} = scale(most);
const svg = frame(top, ticks, names, labelEvery(names.length));
const plotW = W - PAD.left - PAD.right;
const plotH = H - PAD.top - PAD.bottom;
const x = index => PAD.left + (index + 0.5) * plotW / names.length;
const y = value => PAD.top + plotH - value / top * plotH;
for (const set of [...sets].reverse()) {
let d = "";
let drawing = false;
set.values.forEach((value, index) => {
if (value === null) {
drawing = false;
return;
}
d += `${drawing ? "L" : "M"}${x(index).toFixed(1)},${y(value).toFixed(1)}`;
drawing = true;
});
svg.append(svgEl("path", {d: d || "M0,0", class: set.dim ? "line dim" : "line"}));
}
const slot = plotW / names.length;
names.forEach((name, index) => {
const hit = svgEl("rect", {x: PAD.left + index * slot, y: PAD.top, width: slot, height: plotH, class: "hit"});
hit.append(svgEl("title", {}, tip(index)));
svg.append(hit);
});
return svg;
};
const render = data => {
const {summary} = data;
const hourly = data.bucketSeconds < 86400;
const tiles = [
[summary.online.toLocaleString(), "Online now"],
[summary.peak.count.toLocaleString(), "Most at once", summary.peak.at ? when(summary.peak.at) : ""],
[summary.peakEver.count.toLocaleString(), "Most ever", summary.peakEver.at ? when(summary.peakEver.at, false) : ""],
[summary.logins.toLocaleString(), "Logins"],
[summary.players.toLocaleString(), "Players", "who logged in"],
[summary.newAccounts.toLocaleString(), "New accounts", `${summary.firstLogins.toLocaleString()} played`],
[summary.averageSessionSeconds ? played(summary.averageSessionSeconds) : "—", "Average visit", `${summary.sessions.toLocaleString()} visits`],
[played(summary.playedSeconds), "Time played"],
[summary.accounts.toLocaleString(), "Accounts in all"],
];
byId("stats-tiles").replaceChildren(...tiles.map(([value, name, sub]) => {
const tile = htmlEl("div", undefined, "stats-tile");
tile.append(htmlEl("div", value, "value"), htmlEl("div", name, "name"));
if (sub) {
tile.append(htmlEl("div", sub, "sub"));
}
return tile;
}));
const series = data.series;
const bucketName = at => {
const date = new Date(at * 1000);
return hourly ? date.toLocaleTimeString([], {hour: "numeric"}) : date.toLocaleDateString([], {month: "short", day: "numeric"});
};
const bucketLong = at => {
const date = new Date(at * 1000);
return hourly ? date.toLocaleString([], {weekday: "short", hour: "numeric", minute: "2-digit"}) : date.toLocaleDateString([], {weekday: "short", dateStyle: "medium"});
};
const names = series.map(bucket => bucketName(bucket.at));
byId("stats-online").replaceChildren(lines(
[{values: series.map(bucket => bucket.average)}, {values: series.map(bucket => bucket.most), dim: true}], names,
index => `${bucketLong(series[index].at)}\naverage ${series[index].average ?? "—"} · most ${series[index].most ?? "—"}`));
byId("stats-logins").replaceChildren(bars(
[{values: series.map(bucket => bucket.logins)}, {values: series.map(bucket => bucket.players), dim: true}], names,
index => `${bucketLong(series[index].at)}\n${series[index].logins} logins · ${series[index].players} players`));
byId("stats-new").replaceChildren(bars(
[{values: series.map(bucket => bucket.newAccounts)}], names,
index => `${bucketLong(series[index].at)}\n${series[index].newAccounts} new`));
const hourName = hour => new Date(2000, 0, 1, hour).toLocaleTimeString([], {hour: "numeric"});
byId("stats-hours").replaceChildren(bars(
[{values: data.hours.map(hour => hour.average)}], data.hours.map((hour, index) => hourName(index)),
index => `${hourName(index)}\naverage ${data.hours[index].average ?? "—"} online · ${data.hours[index].logins} logins`));
const heat = htmlEl("div", undefined, "stats-heat");
const busiest = Math.max(0, ...data.week.flat().filter(value => value !== null));
heat.append(htmlEl("div", "", "label"));
for (let hour = 0; hour < 24; hour++) {
heat.append(htmlEl("div", hour % 6 === 0 ? String(hour) : "", "hour"));
}
// Monday first.
for (const day of [1, 2, 3, 4, 5, 6, 0]) {
heat.append(htmlEl("div", DAYS[day], "label"));
data.week[day].forEach((value, hour) => {
const cell = htmlEl("div");
const share = busiest > 0 && value !== null ? value / busiest : 0;
const level = value === null ? 20 : Math.round(26 + share * 229);
cell.style.background = `rgb(${level}, ${level}, ${level})`;
cell.title = `${DAYS[day]} ${hourName(hour)}: ${value === null ? "no data" : `average ${value}`}`;
heat.append(cell);
});
}
byId("stats-week").replaceChildren(heat);
byId("stats-top").replaceChildren(...data.topPlaytime.map(entry => {
const row = htmlEl("tr");
row.append(htmlEl("td", entry.username), htmlEl("td", played(entry.seconds), "num"));
return row;
}));
byId("stats-no-top").hidden = data.topPlaytime.length > 0;
};
let api = null;
let loadedAt = 0;
let loadedRange = null;
// `call` is the page's own: (path) -> {ok, data}. asked again at most
// once a minute, however often the page refreshes.
const load = async (call, force = false) => {
api = call;
const range = byId("stats-range").value;
if (!force && range === loadedRange && Date.now() - loadedAt < 60000) {
return;
}
const offset = -new Date().getTimezoneOffset();
const result = await call(`stats?days=${range}&offset=${offset}`);
if (result.ok) {
loadedAt = Date.now();
loadedRange = range;
render(result.data);
}
};
byId("stats-range").addEventListener("change", () => {
if (api) {
load(api, true);
}
});
window.statsView = {load};
})();
</script>