diff --git a/.github/workflows/tag-on-merge.yml b/.github/workflows/tag-on-merge.yml index ada2a42..a306015 100644 --- a/.github/workflows/tag-on-merge.yml +++ b/.github/workflows/tag-on-merge.yml @@ -8,6 +8,7 @@ on: paths-ignore: - '**.md' - 'docs/**' + - 'samples/**' - '.github/**' permissions: diff --git a/PLUGIN_AUTHORS.md b/PLUGIN_AUTHORS.md index 01df8c6..d256284 100644 --- a/PLUGIN_AUTHORS.md +++ b/PLUGIN_AUTHORS.md @@ -8,7 +8,7 @@ A plugin is a folder with a `plugin.json` file and ordinary web files: HTML, Jav The page runs in its own sandboxed browser. It talks to FourFold only through `window.fourfold`, a small API that gives it: -- read-only data from FourFold: the accounts, their XP and stats, and the timer (never logins); +- read-only data from FourFold: the accounts, their XP, stats, equipment, silver, gold and location, and the timer (never logins); - web requests to the sites the plugin declares; - a small private store; - overlay cards, drawn by FourFold. @@ -29,7 +29,7 @@ Users get plugins from the plugin hub: they open the plugin list (the wrench in When you build on a copy of a sample, change its `id` and `author` in `plugin.json` first. -The other sample, `samples/sandbox-check`, contacts example.com each time it runs. See [Check your own plugin](#check-your-own-plugin). +`samples/silver-tracker` is a fuller example: it reads `fourfold.profile`, keeps its maths in a module, and has a check that runs with Node. The third sample, `samples/sandbox-check`, contacts example.com each time it runs. See [Check your own plugin](#check-your-own-plugin). Every folder directly inside `dev-plugins` is one plugin. @@ -70,7 +70,7 @@ A `plugin.json` that breaks any rule below is rejected: the plugin doesn't load, | `version` | yes | `MAJOR.MINOR.PATCH`, digits only, such as `1.0.0`. | | `author` | yes | 1 to 40 characters. | | `description` | no | At most 200 characters. | -| `apiVersion` | yes | A whole number. FourFold supports `1`. A higher number is rejected with "Update FourFold to use this plugin." | +| `apiVersion` | yes | A whole number: the lowest API version the plugin needs. FourFold supports `1` and `2`. Declare `2` if the plugin calls `fourfold.profile` or reads `equipment`, so that an older FourFold tells the user to update instead of running a plugin that can't work. A higher number is rejected with "Update FourFold to use this plugin." | | `panel` | yes | Path to an existing `.html` file inside the plugin folder. Forward slashes only. | | `icon` | no | Path to a `.png` file inside the plugin folder, at most 256 by 256 pixels and 64 KB. Forward slashes only. Without one, the strip shows a default icon. | | `sites` | no | At most 10 websites the plugin may contact. Each is an origin: `https://host` or `https://host:port`, with no path, query or `user@`. The host must be a DNS name: no IP address, no trailing dot, and no name that only works on the local network. `localhost`, `.localhost`, `.local`, `.internal`, `.lan` and `.home.arpa` names are refused, and so is a single-label name such as `router`. A subdomain is its own site, so `https://example.com` doesn't cover `https://www.example.com`. An international host name is fine: FourFold converts it to its `xn--` form, and that form is what it shows users. After the conversion the host can contain only letters, digits, dots and dashes, so a name with an underscore or any other punctuation is refused. | @@ -151,7 +151,27 @@ const stats = await fourfold.stats.get(account.id); if (stats) console.log(stats.className, stats.level, stats.hp, stats.attack); ``` -`fourfold.stats.get(accountId)` returns `{ className, level, hp, sp, attack, magic, skill, speed, luck, defense, resistance }` for the account's active class, or `null` when the account is closed or hasn't been read yet. There is no stats event: read `stats.get` again when `xp.onUpdated` fires. `hp` to `resistance` are numbers, or `null` when unknown. An unknown account id is rejected with `invalid-argument`. +`fourfold.stats.get(accountId)` returns `{ className, level, hp, sp, attack, magic, skill, speed, luck, defense, resistance, equipment }` for the account's active class, or `null` when the account is closed or hasn't been read yet. There is no stats event: read `stats.get` again when `xp.onUpdated` fires. `hp` to `resistance` are numbers, or `null` when unknown. `equipment` is `{ armor, helmet, hair, weapon }`: each is the slot as the profile page words it, at most 64 characters, or `null` when unknown. An empty slot comes through as the page's own word for it (`Empty`, say), not as `null`. A plugin that reads `equipment` needs `"apiVersion": 2`. An unknown account id is rejected with `invalid-argument`. + +### Profile + +```js +const profile = await fourfold.profile.get(account.id); +if (!profile.isStale && profile.silver !== null) console.log(account.label, 'has', profile.silver, 'silver'); +``` + +`fourfold.profile.get(accountId)` returns facts from the account's public profile page. It needs `"apiVersion": 2`. + +| Field | Type | Meaning | +|---|---|---| +| `silver` | number or null | The account's silver. | +| `gold` | number or null | The account's gold. | +| `location` | string or null | Where the character is, as the profile page words it. At most 64 characters. | +| `playerId` | number or null | The account's public player id. Like `inGameName`, it is `null` unless the user has filled in that account's **Ranking username**. It is also `null` until the profile has been read under that name. | +| `updatedAt` | string or null | Time of the last successful read, as an ISO 8601 date. | +| `isStale` | boolean | `true` when there is no data yet, when the last read failed, and for a closed account. | + +The data comes from the same read as XP: about once a minute, for open accounts only. There is no profile event: read `profile.get` again when `xp.onUpdated` fires. That event also fires for changes that aren't a new read, and `updatedAt` only changes with a new one, so compare it to tell them apart. After a failed read `silver`, `gold`, `location` and `updatedAt` keep their last values and `isStale` is `true`. For a closed account the number and text fields are `null`. An unknown account id is rejected with `invalid-argument`. ### Timer @@ -387,7 +407,7 @@ If the user switches the plugin off in the plugin list, its cards are hidden eve - Read or control the game, or see its pages, cookies or sessions. - See logins: usernames, emails and passwords are never exposed. Plugins can't see other plugins or any file outside their own folder either. -- Get real-time data. XP data arrives about once a minute, and the timer sends no tick events. +- Get real-time data. XP and profile data arrive about once a minute, and the timer sends no tick events. - Use shortcut keys, sounds or desktop notifications. - Draw custom cards. Cards are FourFold's data cards. - Add a settings page behind the cog. Keep settings in your own panel. diff --git a/samples/silver-tracker/.check/rate.check.mjs b/samples/silver-tracker/.check/rate.check.mjs new file mode 100644 index 0000000..f0f789d --- /dev/null +++ b/samples/silver-tracker/.check/rate.check.mjs @@ -0,0 +1,72 @@ +// Checks rate.mjs outside FourFold. Run: node samples/silver-tracker/.check/rate.check.mjs +import assert from 'node:assert/strict'; +import { applyRead, createSession, parseGoal, rateAt, statusOf, toGoal } from '../rate.mjs'; + +const at = minutes => new Date(Date.UTC(2026, 9, 4, 12, 0) + minutes * 60000).toISOString(); +const read = (silver, minutes, isStale = false) => ({ silver, updatedAt: at(minutes), isStale }); +const feed = (...reads) => { + const session = createSession(); + for (const next of reads) applyRead(session, next); + return session; +}; +const rate = session => rateAt(session, session.lastAt); +const net = session => session.lastBalance - session.startBalance; + +// One read alone gives no rate. Two reads a minute apart: 600 silver in 60 seconds is 36,000 an hour. +assert.equal(rate(feed(read(1000, 0))), null); +let session = feed(read(1000, 0), read(1600, 1)); +assert.equal(session.earned, 600); +assert.equal(Math.round(rate(session)), 36000); + +// Spending adds nothing to earned and never makes the rate negative. Net does go negative. +session = feed(read(5000, 0), read(2000, 1), read(2500, 2)); +assert.equal(session.earned, 500); +assert.equal(net(session), -2500); +assert.equal(Math.round(rate(session)), 15000); + +// A failed read, then a good one half an hour later with far more silver: no interval spans the gap, so the rate +// doesn't spike. Net is still the true change. +session = feed(read(1000, 0), read(1100, 1), read(1100, 1, true), read(9000, 30), read(9100, 31)); +assert.equal(session.intervals.length, 2); +assert.equal(session.earned, 200); +assert.equal(net(session), 8100); +assert.equal(Math.round(rate(session)), 6000); + +// The same read twice, or one stamped earlier than the last, changes nothing. +session = feed(read(1000, 0), read(1600, 1), read(1600, 1), read(99999, 0)); +assert.equal(session.earned, 600); +assert.equal(session.intervals.length, 1); + +// A read with no silver or no time counts as missed, like a stale one. +session = feed(read(1000, 0), { silver: null, updatedAt: null, isStale: false }, read(5000, 1), read(5100, 2)); +assert.equal(session.earned, 100); + +// The status never calls old numbers live. If the page stops giving silver while the read itself still succeeds, +// the account shows as stale until silver is back. +assert.equal(statusOf(createSession()), 'No data yet'); +assert.equal(statusOf(feed(read(1000, 0))), 'Collecting baseline'); +assert.equal(statusOf(feed(read(1000, 0), read(1600, 1))), 'Tracking'); +session = feed(read(1000, 0), read(1600, 1), { silver: null, updatedAt: at(2), isStale: false }); +assert.equal(statusOf(session), 'Stale; the last read failed'); +applyRead(session, read(1700, 3)); +assert.equal(statusOf(session), 'Tracking'); +assert.equal(statusOf(feed(read(1000, 0), read(1000, 0, true))), 'Stale; the last read failed'); + +// Only the last hour counts. An interval that ended before it is dropped; one that straddles it counts in part. +session = feed(read(0, 0), read(60000, 1), read(60000, 90), read(60000, 91)); +assert.equal(rate(session), 0); +assert.equal(session.earned, 60000); +assert.equal(Math.round(rate(feed(read(0, 0), read(1200, 120)))), 600); + +// A goal is a whole number above zero, with commas or spaces as separators. Anything else is no goal. +assert.equal(parseGoal('1,000,000'), 1000000); +assert.equal(parseGoal(' 250 000 '), 250000); +for (const bad of ['', '0', '-5', '1.5', '1e9', 'abc', '9'.repeat(16)]) assert.equal(parseGoal(bad), null); + +// Time to a goal needs a rate above zero. A reached goal has nothing left. +assert.deepEqual(toGoal(1000, 400, 300), { remaining: 600, progress: 0.4, hours: 2 }); +assert.equal(toGoal(1000, 400, null).hours, null); +assert.equal(toGoal(1000, 400, 0).hours, null); +assert.deepEqual(toGoal(1000, 2500, 300), { remaining: 0, progress: 1, hours: null }); + +console.log('rate.mjs: all checks passed'); diff --git a/samples/silver-tracker/app.js b/samples/silver-tracker/app.js new file mode 100644 index 0000000..64e9df0 --- /dev/null +++ b/samples/silver-tracker/app.js @@ -0,0 +1,193 @@ +// Silver tracker: silver earned per hour, session totals and a silver goal for each open account, in the panel and +// on a card. The maths is in rate.mjs. +import { applyRead, createSession, parseGoal, rateAt, statusOf, toGoal } from './rate.mjs'; + +const container = document.getElementById('accounts'); +const empty = document.getElementById('empty'); +const sessions = new Map(); // account id -> session; open accounts only +const blocks = new Map(); // account id -> that account's elements in the panel +let goals = {}; + +const whole = value => Math.round(value).toLocaleString('en-US'); +const signed = value => (value > 0 ? '+' : '') + whole(value); +// A card's text can be at most 40 characters, and FourFold refuses a longer line, so clip it. +const fit = text => (text.length > 40 ? `${text.slice(0, 39)}…` : text); +const goalFor = id => (Number.isSafeInteger(goals[id]) && goals[id] > 0 ? goals[id] : null); + +function duration(hours) { + if (hours >= 10000) return '9,999h+'; + const minutes = Math.max(1, Math.round(hours * 60)); + return minutes < 60 ? `${minutes}m` : `${whole(Math.floor(minutes / 60))}h ${minutes % 60}m`; +} + +function goalText(left) { + if (left.remaining === 0) return 'Reached'; + const toGo = `${whole(left.remaining)} to go`; + return left.hours === null ? toGo : `${toGo} · ${duration(left.hours)}`; +} + +// Everything one account's block and card show. +function describe(account, session) { + const tracked = session.lastAt !== null; + const balance = tracked ? session.lastBalance : null; + const rate = tracked ? rateAt(session, session.lastAt) : null; + const goal = goalFor(account.id); + return { + id: account.id, + label: account.label, + balance, + rate, + earned: session.earned, + net: tracked ? balance - session.startBalance : null, + goal, + left: goal !== null && tracked ? toGoal(goal, balance, rate) : null, + status: statusOf(session) + }; +} + +async function setCard(view) { + if (view.balance === null) { + await fourfold.cards.clear('silver', view.id); + return; + } + const rows = [ + { label: 'Silver/hr', value: fit(view.rate === null ? 'No rate yet' : whole(view.rate)) }, + { label: 'Session', value: fit(`+${whole(view.earned)} (net ${signed(view.net)})`) } + ]; + if (view.left) rows.push({ label: 'Goal', value: fit(goalText(view.left)), progress: view.left.progress }); + await fourfold.cards.set('silver', view.id, { + summary: fit(view.rate === null ? 'No rate yet' : `${whole(view.rate)}/hr`), + rows + }); +} + +function element(tag, className, parent) { + const created = document.createElement(tag); + if (className) created.className = className; + parent.append(created); + return created; +} + +// One account's block, built once. Its handlers look the account up by id, so they never hold stale data. +function createBlock(id) { + const root = document.createElement('div'); + root.className = 'account'; + const parts = { root, title: element('h2', '', root), rate: element('p', 'rate', root) }; + parts.session = element('p', '', root); + parts.balance = element('p', '', root); + const label = element('label', '', root); + label.textContent = 'Goal'; + parts.input = element('input', '', label); + parts.input.type = 'text'; + parts.input.inputMode = 'numeric'; + parts.input.placeholder = 'Target silver'; + parts.bar = element('div', 'bar', root); + parts.fill = element('div', '', parts.bar); + parts.goal = element('p', '', root); + parts.status = element('p', 'status', root); + const reset = element('button', '', root); + reset.type = 'button'; + reset.textContent = 'Reset'; + + parts.input.addEventListener('change', async () => { + const goal = parseGoal(parts.input.value); + if (goal === null) delete goals[id]; + else goals[id] = goal; + await saveGoals(); + await render(); + }); + // Leaving the box redraws it at once, so a goal that wasn't accepted doesn't stay on show. + parts.input.addEventListener('blur', render); + // Ending the session is enough: the next refresh starts a new one from the latest read. + reset.addEventListener('click', () => { + sessions.delete(id); + render(); + }); + return parts; +} + +function updateBlock(parts, view) { + parts.title.textContent = view.label; + parts.title.title = view.label; + parts.rate.textContent = view.rate === null ? 'No rate yet' : `${whole(view.rate)} silver/hr`; + const tracked = view.balance !== null; + parts.session.hidden = !tracked; + parts.balance.hidden = !tracked; + if (tracked) { + parts.session.textContent = `Session: +${whole(view.earned)} earned, ${signed(view.net)} net`; + parts.balance.textContent = `Balance: ${whole(view.balance)}`; + } + // Never rewrite the box under the user's cursor. + if (document.activeElement !== parts.input) parts.input.value = view.goal === null ? '' : whole(view.goal); + parts.bar.hidden = !view.left; + parts.goal.hidden = !view.left; + if (view.left) { + parts.fill.style.width = `${Math.round(view.left.progress * 100)}%`; + parts.goal.textContent = goalText(view.left); + } + parts.status.textContent = view.status; +} + +function paint(views) { + for (const [id, parts] of blocks) { + if (views.every(view => view.id !== id)) { + parts.root.remove(); + blocks.delete(id); + } + } + views.forEach((view, index) => { + let parts = blocks.get(view.id); + if (!parts) blocks.set(view.id, (parts = createBlock(view.id))); + // Moving a block drops its focus, so only move one that is out of place. + if (container.children[index] !== parts.root) container.insertBefore(parts.root, container.children[index] ?? null); + updateBlock(parts, view); + }); + empty.hidden = views.length > 0; +} + +async function refresh() { + const open = (await fourfold.accounts.list()).filter(account => account.isOpen); + // A closed account's session is over, and its card goes with it. + for (const id of [...sessions.keys()]) { + if (open.every(account => account.id !== id)) { + sessions.delete(id); + await fourfold.cards.clear('silver', id).catch(() => {}); + } + } + + const views = []; + for (const account of open) { + let session = sessions.get(account.id); + if (!session) sessions.set(account.id, (session = createSession())); + applyRead(session, await fourfold.profile.get(account.id)); + const view = describe(account, session); + // A refused card must not stop the panel from updating. + await setCard(view).catch(error => console.warn(error.code ?? error.message)); + views.push(view); + } + paint(views); +} + +// Events arrive in bursts (xp.onUpdated fires once per account), so refreshes run one after another, never +// overlapping. +let queue = Promise.resolve(); +const render = () => (queue = queue.then(refresh).catch(error => console.warn(error.code ?? error.message))); + +async function saveGoals() { + // Goals for accounts that no longer exist go, so the store doesn't grow for ever. + const known = new Set((await fourfold.accounts.list()).map(account => account.id)); + for (const id of Object.keys(goals)) { + if (!known.has(id)) delete goals[id]; + } + await fourfold.storage.set('goals', goals); +} + +async function start() { + const saved = await fourfold.storage.get('goals'); + goals = saved && typeof saved === 'object' && !Array.isArray(saved) ? saved : {}; + fourfold.accounts.onChanged(render); + fourfold.xp.onUpdated(render); + await render(); +} + +start().catch(error => { container.textContent = `Silver tracker failed: ${error.message}`; }); diff --git a/samples/silver-tracker/index.html b/samples/silver-tracker/index.html new file mode 100644 index 0000000..13d4fe2 --- /dev/null +++ b/samples/silver-tracker/index.html @@ -0,0 +1,15 @@ + + +
+ +Silver earned per hour for each open account.
+Open an account to track its silver.
+ + + + diff --git a/samples/silver-tracker/plugin.json b/samples/silver-tracker/plugin.json new file mode 100644 index 0000000..9736cc5 --- /dev/null +++ b/samples/silver-tracker/plugin.json @@ -0,0 +1,11 @@ +{ + "id": "fourfold.silver-tracker", + "name": "Silver tracker", + "shortLabel": "Silver", + "version": "1.0.0", + "author": "FourFold", + "description": "Silver per hour, session totals and a silver goal for each open account.", + "apiVersion": 2, + "panel": "index.html", + "cards": [{ "id": "silver", "name": "Silver", "scope": "account" }] +} diff --git a/samples/silver-tracker/rate.mjs b/samples/silver-tracker/rate.mjs new file mode 100644 index 0000000..e874c01 --- /dev/null +++ b/samples/silver-tracker/rate.mjs @@ -0,0 +1,74 @@ +// Session, rate and goal maths for the Silver tracker. Nothing here touches the page or window.fourfold, so +// .check/rate.check.mjs can run it with Node. + +const HOUR_MS = 3600000; + +// One account's session: what has been seen since tracking started. Times are milliseconds since the epoch. +export function createSession() { + return { startBalance: null, lastBalance: null, lastAt: null, intervals: [], earned: 0, missed: false }; +} + +// Takes one answer from fourfold.profile.get. +export function applyRead(session, read) { + const at = typeof read.updatedAt === 'string' ? Date.parse(read.updatedAt) : NaN; + if (read.isStale || !Number.isFinite(read.silver) || Number.isNaN(at)) { + session.missed = true; + return; + } + // The same read again: xp.onUpdated also fires for changes that aren't a new read. + if (session.lastAt !== null && at <= session.lastAt) return; + if (session.lastAt === null || session.missed) { + // Nothing trustworthy to measure from. FourFold's XP tracker starts over after a missed read too. + session.startBalance ??= read.silver; + session.missed = false; + } else { + // Silver earned only: a drop is spending, and adds nothing. + const gain = Math.max(0, read.silver - session.lastBalance); + session.intervals.push({ from: session.lastAt, to: at, gain }); + session.earned += gain; + } + session.lastBalance = read.silver; + session.lastAt = at; + session.intervals = session.intervals.filter(interval => interval.to > at - HOUR_MS); +} + +// Silver per hour over the hour ending at `now`, or null when nothing in that hour was measured. The same sum as +// FourFold's XpRateWindow: each interval counts for the part of it inside the hour. +export function rateAt(session, now) { + const start = now - HOUR_MS; + let gain = 0; + let covered = 0; + for (const interval of session.intervals) { + const overlap = Math.min(interval.to, now) - Math.max(interval.from, start); + if (overlap <= 0) continue; + gain += interval.gain * overlap / (interval.to - interval.from); + covered += overlap; + } + return covered > 0 ? gain / covered * HOUR_MS : null; +} + +// The account's status line. A missed read shows as stale whatever the reason, so old numbers never pass as live. +export function statusOf(session) { + if (session.lastAt === null) return 'No data yet'; + if (session.missed) return 'Stale; the last read failed'; + return rateAt(session, session.lastAt) === null ? 'Collecting baseline' : 'Tracking'; +} + +// A goal as the user typed it: digits, with commas or spaces as thousands separators. Null when it isn't a whole +// number above zero. A dot is refused, not read as a separator: "1.5" must not become 15. +export function parseGoal(text) { + const digits = String(text).replace(/[\s,]/g, ''); + if (!/^\d{1,15}$/.test(digits)) return null; + const goal = Number(digits); + return goal > 0 ? goal : null; +} + +// What is left to a goal and how long it takes at this rate. hours is null without a rate above zero. +export function toGoal(goal, balance, rate) { + const remaining = Math.max(0, goal - balance); + return { + remaining, + progress: Math.min(1, Math.max(0, balance / goal)), + hours: remaining > 0 && rate > 0 ? remaining / rate : null + }; +} diff --git a/samples/silver-tracker/style.css b/samples/silver-tracker/style.css new file mode 100644 index 0000000..256d87b --- /dev/null +++ b/samples/silver-tracker/style.css @@ -0,0 +1,14 @@ +body { margin: 0; padding: 14px; background: var(--ff-surface); color: var(--ff-text); font: 13px "Segoe UI", sans-serif; } +h1 { margin: 0 0 4px; font-size: 16px; font-weight: 600; } +.muted { color: var(--ff-text-muted); margin: 0 0 12px; } +.account { background: var(--ff-surface-raised); border: 1px solid var(--ff-border); border-radius: 6px; padding: 10px; margin-bottom: 8px; } +.account h2 { margin: 0 0 6px; font-size: 13px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.account p { margin: 3px 0 0; font-size: 11px; } +.account .rate { margin: 0; font-size: 17px; font-weight: 700; color: var(--ff-accent); font-variant-numeric: tabular-nums; } +.account label { display: block; color: var(--ff-text-muted); font-size: 11px; margin-top: 9px; } +.account input { display: block; box-sizing: border-box; width: 100%; margin-top: 3px; background: var(--ff-background); color: var(--ff-text); border: 1px solid var(--ff-border); border-radius: 4px; padding: 3px 6px; font: inherit; } +.account .status { color: var(--ff-text-muted); font-size: 10px; margin-top: 9px; } +.account button { margin-top: 8px; background: var(--ff-surface); color: var(--ff-text); border: 1px solid var(--ff-border); border-radius: 4px; padding: 3px 10px; font: inherit; cursor: pointer; } +.account button:hover { border-color: var(--ff-accent); } +.bar { height: 4px; border-radius: 2px; background: var(--ff-border); margin-top: 8px; } +.bar > div { height: 100%; border-radius: 2px; background: var(--ff-accent); } diff --git a/src/FourFoldAccountManager.Core.Tests/Plugins/PluginManifestReaderTests.cs b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginManifestReaderTests.cs index 2d728c6..ec57ddc 100644 --- a/src/FourFoldAccountManager.Core.Tests/Plugins/PluginManifestReaderTests.cs +++ b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginManifestReaderTests.cs @@ -99,7 +99,7 @@ public void AValidManifestLoadsWithItsSitesAndCards() [InlineData("\"id\": \"nul.tools\"")] [InlineData("\"id\": \"com1.tools\"")] [InlineData("\"id\": \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"")] - [InlineData("\"apiVersion\": 2")] + [InlineData("\"apiVersion\": 3")] [InlineData("\"apiVersion\": \"1\"")] [InlineData("\"panel\": \"missing.html\"")] [InlineData("\"panel\": \"plugin.json\"")] diff --git a/src/FourFoldAccountManager.Core.Tests/Tracking/PlayerProfileHtmlParserTests.cs b/src/FourFoldAccountManager.Core.Tests/Tracking/PlayerProfileHtmlParserTests.cs new file mode 100644 index 0000000..c044991 --- /dev/null +++ b/src/FourFoldAccountManager.Core.Tests/Tracking/PlayerProfileHtmlParserTests.cs @@ -0,0 +1,46 @@ +using FourFoldAccountManager.Core.Tracking; +using Xunit; + +namespace FourFoldAccountManager.Core.Tests.Tracking; + +public sealed class PlayerProfileHtmlParserTests +{ + // The shape of social_profile.php: the game-stats strip sits above the class cards. + private static string Page(string gameStats) => $$""" + + {{gameStats}} + + """; + + private static string Strip(string silver) => $$""" + + """; + + [Fact] + public void AChangedGameStatsStripNeverBreaksTheClasses() + { + // XP tracking and the leaderboard don't need the strip. Without it, or with a silver value that isn't a + // number, the classes still parse and silver is simply unknown. + foreach (var strip in new[] { "", Strip("lots"), Strip("-5"), Strip("") }) + { + var snapshot = PlayerProfileHtmlParser.Parse(Page(strip)); + + Assert.Null(snapshot.Silver); + Assert.Equal("Warrior", snapshot.ActiveClassName); + Assert.Equal(5, snapshot.Classes["Warrior"].CurrentXp); + } + + var read = PlayerProfileHtmlParser.Parse(Page(Strip("13,025,343"))); + + Assert.Equal(13_025_343, read.Silver); + Assert.Equal(95_050, read.Gold); + Assert.Equal("Arena", read.Location); + } +} diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs b/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs index 95a278b..000f073 100644 --- a/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs +++ b/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs @@ -8,7 +8,8 @@ namespace FourFoldAccountManager.Core.Plugins; public static partial class PluginManifestReader { - public const int SupportedApiVersion = 1; + // 2 added fourfold.profile, and equipment on stats.get. + public const int SupportedApiVersion = 2; // author.plugin-name: lowercase letters, digits and dashes in dot-separated parts, with at least one dot. public const string IdPattern = @"[a-z0-9]+(-[a-z0-9]+)*(\.[a-z0-9]+(-[a-z0-9]+)*)+"; diff --git a/src/FourFoldAccountManager.Core/Tracking/PlayerProfileHtmlParser.cs b/src/FourFoldAccountManager.Core/Tracking/PlayerProfileHtmlParser.cs index 3a68acf..f3b7f13 100644 --- a/src/FourFoldAccountManager.Core/Tracking/PlayerProfileHtmlParser.cs +++ b/src/FourFoldAccountManager.Core/Tracking/PlayerProfileHtmlParser.cs @@ -73,9 +73,24 @@ public static PlayerProgressSnapshot Parse(string html) }); } - return new PlayerProgressSnapshot(username, activeClassName, classes, invalid); + return new PlayerProgressSnapshot(username, activeClassName, classes, invalid) + { + Silver = ReadGameNumber(document, "Silver"), + Gold = ReadGameNumber(document, "Gold"), + Location = ReadGameStat(document, "Location") is { Length: > 0 } location ? location : null + }; } + // The strip of facts above the classes: . + // Nothing that tracks XP needs it, so a missing or changed strip gives null and never throws. + private static string? ReadGameStat(IDocument document, string label) => + document.QuerySelectorAll(".social-game-stats .social-game-stat") + .FirstOrDefault(stat => stat.QuerySelector("span")?.TextContent.Trim() == label) + ?.QuerySelector("strong")?.TextContent.Trim(); + + private static long? ReadGameNumber(IDocument document, string label) => + TryParseNonnegativeLong(ReadGameStat(document, label), out var value) ? value : null; + private static ProfileStats ReadStats(IElement card) => new( ParseDisplayedStat(ReadMeta(card, "HP"), useMaximum: true), ParseDisplayedStat(ReadMeta(card, "SP"), useMaximum: true), diff --git a/src/FourFoldAccountManager.Core/Tracking/PlayerProgressSnapshot.cs b/src/FourFoldAccountManager.Core/Tracking/PlayerProgressSnapshot.cs index 387e646..180fcc8 100644 --- a/src/FourFoldAccountManager.Core/Tracking/PlayerProgressSnapshot.cs +++ b/src/FourFoldAccountManager.Core/Tracking/PlayerProgressSnapshot.cs @@ -4,4 +4,10 @@ public sealed record PlayerProgressSnapshot( string Username, string? ActiveClassName, IReadOnlyDictionary