diff --git a/.github/workflows/osv-scanner.yml b/.github/workflows/osv-scanner.yml index c1845567..32d503b3 100644 --- a/.github/workflows/osv-scanner.yml +++ b/.github/workflows/osv-scanner.yml @@ -52,7 +52,7 @@ jobs: contents: read security-events: write actions: read - uses: "google/osv-scanner-action/.github/workflows/osv-scanner-reusable.yml@b1d267aea5211fa648d9d442fa64b90dbdcbdd36" # v2.7.0 + uses: "google/osv-scanner-action/.github/workflows/osv-scanner-reusable.yml@32d3cd482bdadfb38b186c0ad1b031902d55d932" # v2.7.1 with: scan-args: |- -r @@ -65,7 +65,7 @@ jobs: contents: read security-events: write actions: read - uses: "google/osv-scanner-action/.github/workflows/osv-scanner-reusable-pr.yml@b1d267aea5211fa648d9d442fa64b90dbdcbdd36" # v2.7.0 + uses: "google/osv-scanner-action/.github/workflows/osv-scanner-reusable-pr.yml@32d3cd482bdadfb38b186c0ad1b031902d55d932" # v2.7.1 with: scan-args: |- -r diff --git a/.github/workflows/scorecard.yml b/.github/workflows/scorecard.yml index 18260dc8..50b27d61 100644 --- a/.github/workflows/scorecard.yml +++ b/.github/workflows/scorecard.yml @@ -40,7 +40,7 @@ jobs: persist-credentials: false - name: "Run analysis" - uses: ossf/scorecard-action@fa7117db83c52d787ae5a89f350999701505d78e # v2.5.0 + uses: ossf/scorecard-action@23f22cd43608bae7a1f1fa2603d7314dee9538a5 # v2.6.0 with: results_file: results.sarif results_format: sarif diff --git a/CHANGELOG.md b/CHANGELOG.md index 0b3fce34..22f9a6c6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,14 @@ Condensed release history, newest first. ## Unreleased +Nothing yet. + +--- + +## 2026-11-28 — v1.2.1: backups without tokens, one play per song, room for your own GPU work + +Fixes found in the two weeks after 1.2.0, on the owner's NAS and PC: + **Curatarr steps aside for training and tagging runs, not only for games.** A PyTorch run is `python.exe`, and `python.exe` counted as a system process: the card check never saw it. A training run that drew 82-92 % of the card with under 1 GB of VRAM also slipped past the full-card gate (memory @@ -35,9 +43,16 @@ other self-hosted apps, the backup holds what cannot be rebuilt: the database. discovery follow a redirect only on the app's own scheme, host and port (one NAS, an app per port). SoulSync's logo shows again: its icon link carries a `?v=` query, which the address check refused. -**From the bots:** the setup wizard moves focus to the new step's heading, the arr discovery checks -each redirect hop, and the Wrap-Up's comebacks find a title's last earlier play through the title -indexes. +**From the bots:** the setup wizard moves focus to the new step's heading and keeps it when a +connect button is redrawn; tab rows have one Tab stop and move with the arrow keys; the arr +discovery checks each redirect hop; the Wrap-Up's comebacks and discoveries find a title's earlier +plays through the title indexes (a play exactly a year before still counts as a comeback). The +nightly backup also drops the Jellyfin webhook secret, and a media-server switch's restore point, +which keeps every token, stays 0600 whatever `BACKUP_GROUP_READABLE` says. + +**A test that broke with the calendar.** The milestone announcement window read the real clock +while its test used a fixed date, so every CI run turned red from 2026-11-22. The window takes the +same clock as the rest now; the app's behaviour is unchanged. --- diff --git a/deploy/truenas/catalog/SUBMITTING.md b/deploy/truenas/catalog/SUBMITTING.md index ad92e7af..11f31c9c 100644 --- a/deploy/truenas/catalog/SUBMITTING.md +++ b/deploy/truenas/catalog/SUBMITTING.md @@ -16,7 +16,7 @@ the issue, the fork and the pull request carry his account. 1. **A release.** The catalog pins a fixed image tag: publish one (`docs/RELEASING.md`), then set it in `ix_values.yaml` (`images.image.tag`) - and in `app.yaml` (`app_version`). Both say `1.2.0`, the newest release. + and in `app.yaml` (`app_version`). Both say `1.2.1`, the newest release. 2. **Icon and screenshots.** The catalog hosts them on the TrueNAS CDN: attach `assets/brand/curatarr-app-icon.png` and three screenshots from `docs/screenshots/desktop/` to the pull request; the reviewer uploads them diff --git a/deploy/truenas/catalog/curatarr/app.yaml b/deploy/truenas/catalog/curatarr/app.yaml index 15b1a74f..2bfc61be 100644 --- a/deploy/truenas/catalog/curatarr/app.yaml +++ b/deploy/truenas/catalog/curatarr/app.yaml @@ -1,6 +1,6 @@ annotations: min_scale_version: 24.10.2.2 -app_version: 1.2.0 +app_version: 1.2.1 capabilities: [] categories: - media diff --git a/deploy/truenas/catalog/curatarr/ix_values.yaml b/deploy/truenas/catalog/curatarr/ix_values.yaml index acfb6ac0..1f4f0715 100644 --- a/deploy/truenas/catalog/curatarr/ix_values.yaml +++ b/deploy/truenas/catalog/curatarr/ix_values.yaml @@ -1,7 +1,7 @@ images: image: repository: ghcr.io/randomname653/curatarr - tag: "1.2.0" + tag: "1.2.1" container_utils_image: repository: ghcr.io/truenas/containers/container-utils tag: "1.1.2@sha256:6ddfdc314af9d18cfacb836ad266ef0ed91fecaa3686b20be72e464972860c08" diff --git a/frontend/js/app.js b/frontend/js/app.js index 43165229..1e612581 100644 --- a/frontend/js/app.js +++ b/frontend/js/app.js @@ -7,7 +7,7 @@ import { submitSetupCode, setupCodeKey, useOllama, hideOnboarding, onSetupCurato import { activityTabKey, cancelTask, loadScheduled, loadTaskHistory, reloadPage, runScheduledJob, setHistoryFilter, showActivityTab, showNoopRuns, toggleHideNoop } from './activity.js'; import { checkMappingCoverage, closeKbDrilldown, kbDismissFinding, kbFixMatch, kbIgnore, kbRetry, kbUnignore, loadCacheInventory, loadEnrichStatus, loadKbAttention, loadKbItems, loadMappingStats, loadProfiles, runMaintenance, showKbTab, startBackfill, startSprint, stopBackfill, stopSprint } from './kb.js'; import { checkOrphans, loadLibraryConfig, saveLibraries, searchOnEnter } from './libraries.js'; -import { _errMsg, activeDialog, closeMenus, syncTabRoles, closeModal, toggleMenu, keyActivate, hideOnError, onPageLoad, posterLoaded, toast, trapFocus } from './ui.js'; +import { _errMsg, activeDialog, closeMenus, syncTabRoles, tabRowKey, closeModal, toggleMenu, keyActivate, hideOnError, onPageLoad, posterLoaded, toast, trapFocus } from './ui.js'; import { condensePrinciples, downscaleDone, liftProtection, loadDownscale, loadJudgeProtections, loadPrinciples, loadRedundancy, loadUpgrades, setPrinciple, shutdownServer, curationSection, checkUncensored } from './curation.js'; import { answerFollowup, askTonight, correctChatAnchor, explainFollowup, hideMoment, hideTonight, momentPlaylist, titleKeep, titleWatchlist, tonightNext, tonightWatchlist, deleteFromDiscussion, discussLastPlayed, exitDiscussion, fillPrompt, handleKey, hideFollowup, jumpLatest, newChat, onApplyOrphanRepair, onDiscussDeletion, onDiscussRec, saveComment, sendMessage, useStarter } from './chat.js'; import { discussPrinciple, loadUnreadMessages, respondToMessage, skipMessage, toggleMsgPanel } from './notifications.js'; @@ -103,6 +103,7 @@ window.addEventListener('storage', ev => { }); document.addEventListener('keydown', ev => { if (ev.key === 'Tab') { trapFocus(ev, activeDialog()); return; } + tabRowKey(ev); if (ev.key !== 'Escape') return; const menu = document.querySelector('.menu.open'); if (menu) { // innermost layer first; focus back on its button diff --git a/frontend/js/setup.js b/frontend/js/setup.js index c87dd529..1cb62feb 100644 --- a/frontend/js/setup.js +++ b/frontend/js/setup.js @@ -87,6 +87,7 @@ export function jellyfinConnectAgain() { state.setupData.jellyfin_ticket = ''; state.setupData.jellyfin_connected = null; renderSetupStep(state.setupStep); + document.getElementById('s-jellyfin-url')?.focus(); // the button that was pressed is gone } // A radio change redraws the whole step; focus would fall to
and the @@ -181,6 +182,7 @@ export async function startPlexConnect(btn) { state.setupData._plex_code = r.code; state.setupData._plex_login = {id: r.login_id, nonce: r.nonce}; renderSetupStep(state.setupStep); + document.getElementById('plex-connect-btn')?.focus(); // the redraw replaced the pressed button const until = Date.now() + (r.expires_in || 900) * 1000; stopPlexConnect(); _plexPoll = setInterval(async () => { @@ -220,6 +222,7 @@ export function plexConnectAgain() { Object.assign(state.setupData, {plex_ticket: '', plex_servers: null, plex_server_id: '', plex_account: '', _plex_code: null, _plex_login: null}); renderSetupStep(state.setupStep); + document.getElementById('plex-connect-btn')?.focus(); // the link that was pressed is gone } export function pickPlexServer(el) { diff --git a/frontend/js/swipe.js b/frontend/js/swipe.js index 0b02c68d..d8250be2 100644 --- a/frontend/js/swipe.js +++ b/frontend/js/swipe.js @@ -136,8 +136,10 @@ export function swipeCategory(cat) { function _renderTabs() { const el = _el('swipe-tabs'); if (!el) return; + const had = el.contains(document.activeElement); // the redraw would drop a keyboard user's focus el.innerHTML = _cats().map(([c, label]) => ``).join(''); + if (had) el.querySelector('.cat-tab.active')?.focus(); } function _renderReactions() { diff --git a/frontend/js/ui.js b/frontend/js/ui.js index 030544e3..ca0084cb 100644 --- a/frontend/js/ui.js +++ b/frontend/js/ui.js @@ -471,9 +471,30 @@ export function syncTabRoles(root = document) { tab.setAttribute('role', 'tab'); tab.setAttribute('aria-selected', String(tab.classList.contains('active'))); } + // One Tab stop per row, on the chosen tab; the arrows move along it. + const tabs = [...list.querySelectorAll(':scope > [role="tab"]')]; + const stop = tabs.find(x => x.classList.contains('active')) || tabs.find(x => !x.hidden); + for (const tab of tabs) tab.tabIndex = tab === stop ? 0 : -1; } } +// Arrow keys, Home and End move focus along a tab row (WAI-ARIA tabs, +// manual activation: Enter or Space picks the tab, as the button already +// does). Activity's own row has its handler and is left to it. +export function tabRowKey(ev) { + const keys = ['ArrowRight', 'ArrowLeft', 'Home', 'End']; + if (!keys.includes(ev.key) || ev.altKey || ev.ctrlKey || ev.metaKey) return; + const list = ev.target.closest?.('.cat-tabs, .arr-tabs'); + if (!list || list.classList.contains('act-tabs') || ev.target.parentElement !== list) return; + const tabs = [...list.querySelectorAll(':scope > [role="tab"]')].filter(x => !x.hidden); + const i = tabs.indexOf(ev.target); + if (i < 0) return; + const j = ev.key === 'Home' ? 0 : ev.key === 'End' ? tabs.length - 1 + : (i + (ev.key === 'ArrowRight' ? 1 : -1) + tabs.length) % tabs.length; + ev.preventDefault(); + tabs[j].focus(); +} + // skeletonHtml(label, {kind, n}) — the shape of what is loading, shimmering // like a poster that has not arrived: 'cards' (recommendations, deletions), // 'rows' (lists), 'tiles' (Wrap-Up). The label stays for screen readers and diff --git a/src/config.py b/src/config.py index c657de51..7dcefe8e 100644 --- a/src/config.py +++ b/src/config.py @@ -18,7 +18,7 @@ class Settings(BaseSettings): # Beta: feature-complete enough to run a household, not # stable enough to promise anything. One declaration only — # the file headers deliberately carry no version. - VERSION: str = "1.2.0" + VERSION: str = "1.2.1" # HOST is the BIND address only (0.0.0.0 = serve the LAN, intentional for # the multi-user household). It is NOT a navigable origin — browser-facing # defaults (PLEX_REDIRECT_URI, CORS_ORIGINS) stay localhost-based and must diff --git a/src/database/connection.py b/src/database/connection.py index 92d3cbbb..cfacf44d 100644 --- a/src/database/connection.py +++ b/src/database/connection.py @@ -741,7 +741,8 @@ def backup_modes() -> tuple: def _secure_db_files() -> None: """Ensure SQLite files in data/ and .env are 0600; backups follow - backup_modes() (POSIX only).""" + backup_modes() (POSIX only) - except a media-server switch's restore + point (backups/rebind-*/), a full copy with the tokens, which stays 0600.""" import os import stat import logging as _logging @@ -761,8 +762,10 @@ def _secure_db_files() -> None: for ext in ("*.db", "*.sqlite3", "*.sqlite3-wal", "*.sqlite3-shm", "*.db-wal", "*.db-shm"): for p in DATA_DIR.rglob(ext): try: - in_backups = backups in p.resolve().parents - os.chmod(p, backup_modes()[0] if in_backups else stat.S_IRUSR | stat.S_IWUSR) + rp = p.resolve() + stripped = (backups in rp.parents + and not rp.relative_to(backups).parts[0].startswith("rebind-")) + os.chmod(p, backup_modes()[0] if stripped else stat.S_IRUSR | stat.S_IWUSR) except FileNotFoundError: pass # a -wal/-shm sidecar checkpointed away mid-scan except OSError as e: diff --git a/src/services/media_server/rebind.py b/src/services/media_server/rebind.py index 73a6f805..0be7bb53 100644 --- a/src/services/media_server/rebind.py +++ b/src/services/media_server/rebind.py @@ -472,10 +472,14 @@ async def apply_plan(plan: Plan, *, target_adapter, chroma=None, backup_root: Op if (m := running_manifest(root)) is not None: raise RuntimeError(f"an unfinished rebind is on record ({m}) - finish it with --undo first") folder = root / f"rebind-{datetime.utcnow():%Y%m%d-%H%M%S}" - folder.mkdir() + # The restore point is the whole database, members' Plex tokens included + # (the nightly copy blanks them, this one must restore as it was): 0600 + # in a 0700 folder like the live database, not the umask's 0644. + folder.mkdir(mode=0o700) snap = str(folder / "curatarr.db") if not await run_read(scheduler._snapshot_sqlite, _db_path(), snap): raise RuntimeError("the database backup failed its integrity check - nothing was changed") + os.chmod(snap, 0o600) pairs = dict(plan.items) users = {sid: tid for _, (sid, tid, _) in plan.users.items()} libs = {s: t for s, (t, _) in plan.libraries.items()} diff --git a/src/services/milestones.py b/src/services/milestones.py index 46126b38..2fa80ff4 100644 --- a/src/services/milestones.py +++ b/src/services/milestones.py @@ -183,12 +183,13 @@ def history(user_id: int) -> list: return sorted(items, key=lambda m: m["reached_at"], reverse=True) -def pending_announcements(user_id: int) -> list: - """Newly reached milestones the curator has not offered yet. Blocking.""" +def pending_announcements(user_id: int, now: Optional[datetime] = None) -> list: + """Newly reached milestones the curator has not offered yet. Blocking. + ``now`` as in store(): a test's fixed clock, the real one otherwise.""" d = _load(user_id) keys = set(d.get("pending") or []) off = kinds_off(user_id) - now = datetime.utcnow() + now = now or datetime.utcnow() out = [] for m in d.get("items") or []: if _mkey(m) not in keys or m.get("kind") in off: diff --git a/src/services/scheduler.py b/src/services/scheduler.py index a7e3ad0a..f45a74e7 100644 --- a/src/services/scheduler.py +++ b/src/services/scheduler.py @@ -1512,12 +1512,16 @@ def _snapshot_sqlite(db_path: str, dest: str) -> bool: # server's own token lives in .env, never in the database. Plex keeps its # token out of its database backups the same way. _SECRET_COLUMNS = (("users", "plex_token"), ("sessions", "access_token"), ("sessions", "refresh_token")) +# app_state rows that are credentials. The Jellyfin webhook secret: without +# it the route is off, and the admin's next look at the setup card makes a +# new one to paste into the plugin. +_SECRET_STATE_KEYS = ("jellyfin_hook_secret",) def _strip_secrets(dest: str) -> bool: - """Blank the token columns in a backup copy, overwriting the old bytes - (secure_delete), and leave it one file (out of WAL mode). True when the - copy still checks.""" + """Blank the token columns and drop the secret app_state rows in a + backup copy, overwriting the old bytes (secure_delete), and leave it one + file (out of WAL mode). True when the copy still checks.""" con = sqlite_connect(dest) try: con.execute("PRAGMA journal_mode=DELETE") @@ -1526,6 +1530,8 @@ def _strip_secrets(dest: str) -> bool: for table, col in _SECRET_COLUMNS: if table in tables and col in {r[1] for r in con.execute(f'PRAGMA table_info("{table}")')}: # nosec B608 - literals above con.execute(f'UPDATE "{table}" SET "{col}" = NULL WHERE "{col}" IS NOT NULL') # nosec B608 - literals above + if "app_state" in tables: + con.executemany("DELETE FROM app_state WHERE key = ?", [(k,) for k in _SECRET_STATE_KEYS]) con.commit() return (con.execute("PRAGMA quick_check(1)").fetchone() or ["?"])[0] == "ok" finally: diff --git a/src/services/wrapup_facts.py b/src/services/wrapup_facts.py index d457c1c9..277045df 100644 --- a/src/services/wrapup_facts.py +++ b/src/services/wrapup_facts.py @@ -594,9 +594,15 @@ def _discovery(db, W, user_id, period, types, titles) -> dict: return {} keys = [t["title"] for t in titles] key = func.coalesce(W.series_title, W.title) - known = {k for (k,) in db.query(key).filter( - W.user_id == user_id, W.viewed_at < period.start, - W.media_type.in_(types), key.in_(keys)).distinct()} + # One index probe per title that stops at its first earlier play: a regular + # artist has thousands, and DISTINCT over them all was the cost. + known = set() + for k in keys: + if db.query(W.id).filter( + W.user_id == user_id, W.viewed_at < period.start, W.media_type.in_(types), + # Spelled out like _comebacks: ``coalesce(...) = k`` walks every earlier play. + (W.series_title == k) | (W.series_title.is_(None) & (W.title == k))).first(): + known.add(k) total = sum(t["hours"] for t in titles) or 1 new = [t for t in titles if t["title"] not in known] return {"new_share": round(sum(t["hours"] for t in new) / total, 2), @@ -617,7 +623,16 @@ def _comebacks(db, W, user_id, period, types) -> list: W.viewed_at >= period.start, W.viewed_at < period.end).group_by(key).all() if k} if not inside: return [] - names = list(inside) + # A title played inside the year before the latest first play cannot have a + # gap that long; one range scan on ix_wh_user_type_viewed drops those, so + # the max() look-up below only walks the history of the few that remain + # (an artist the member plays all the time has thousands of earlier plays). + cutoff = max(inside.values()) - timedelta(days=_COMEBACK_GAP_DAYS) + recent = {k for (k,) in db.query(key).filter( + W.user_id == user_id, W.media_type.in_(types), + # strictly after: a play exactly a year before is still a comeback + W.viewed_at > cutoff, W.viewed_at < period.start).distinct()} + names = [k for k in inside if k not in recent] out = [] for i in range(0, len(names), 500): for k, last in db.query(key, func.max(W.viewed_at)).filter( diff --git a/tests/test_a11y_nav.py b/tests/test_a11y_nav.py index c02c8229..5336edd7 100644 --- a/tests/test_a11y_nav.py +++ b/tests/test_a11y_nav.py @@ -413,6 +413,91 @@ def test_setup_nav_focuses_step_heading(): '.setup-heading[tabindex="-1"]:focus' in styles()) +def test_tab_rows_roving_and_arrows(): + ui = _read("ui.js") + sync, key = _fn(ui, "syncTabRoles"), _fn(ui, "tabRowKey") + check("syncTabRoles and tabRowKey exist", bool(sync) and bool(key)) + out = _node(r""" +const mkTab = (n, active = false, hidden = false) => ({name: n, hidden, tabIndex: 0, attrs: {}, classList: {contains: c => c === 'active' && active}, + setAttribute(k, v) { this.attrs[k] = v; }, focus() { document.activeElement = this; }}); +const tabs = [mkTab('a'), mkTab('b', true), mkTab('c'), mkTab('gone', false, true)]; +const list = {classList: {contains: () => false}, querySelectorAll: () => tabs}; +tabs.forEach(t => { t.parentElement = list; t.closest = () => list; }); +globalThis.document = {activeElement: null, querySelectorAll: () => [list]}; +list.setAttribute = () => {}; +%s +%s +syncTabRoles(); +const out = {stops: tabs.map(t => t.tabIndex)}; +const press = (at, k, extra = {}) => { document.activeElement = at; let p = false; + tabRowKey({key: k, target: at, preventDefault() { p = true; }, ...extra}); return [document.activeElement.name, p]; }; +out.right = press(tabs[1], 'ArrowRight'); +out.wrap = press(tabs[2], 'ArrowRight'); +out.left = press(tabs[0], 'ArrowLeft'); +out.end = press(tabs[0], 'End'); +out.home = press(tabs[2], 'Home'); +out.other = press(tabs[0], 'a'); +out.ctrl = press(tabs[0], 'ArrowRight', {ctrlKey: true}); +console.log(JSON.stringify(out)); +""" % (sync, key)) if sync and key else None + if out is not None: + check("one Tab stop per row: the active tab", out.get("stops") == [-1, 0, -1, -1]) + check("ArrowRight moves to the next tab, wrapping past the last (hidden tabs skipped)", + out.get("right") == ["c", True] and out.get("wrap") == ["a", True]) + check("ArrowLeft wraps to the last visible tab; Home and End jump", out.get("left") == ["c", True] + and out.get("end") == ["c", True] and out.get("home") == ["a", True]) + check("other keys and modified arrows are left alone", + out.get("other") == ["a", False] and out.get("ctrl") == ["a", False]) + sw = _fn(_read("swipe.js"), "_renderTabs") + out = _node(r""" +const act = () => '', esc = x => x, _cats = () => [['a', 'A'], ['b', 'B']]; let _cat = 'b'; +let focused = null; const active = {focus() { focused = 'active'; }}; +let inside = true; +const el = {contains: () => inside, set innerHTML(v) {}, querySelector: () => active}; +globalThis.document = {activeElement: {}, getElementById: () => el}; +const _el = id => document.getElementById(id); +%s +_renderTabs(); const kept = focused; focused = null; inside = false; _renderTabs(); +console.log(JSON.stringify({kept, left: focused})); +""" % sw) if sw else None + if out is not None: + check("Swipe's tab redraw refocuses the active tab, only if focus was on the row", + out.get("kept") == "active" and out.get("left") is None) + + +# ── 6. the wizard's "connect again" actions keep keyboard focus ────────────── + +def test_setup_connect_redraws_keep_focus(): + """Starting a Plex sign-in, "Use another Plex account" and "Connect + another server" redraw the step, replacing the control that was just + pressed; focus fell to (WCAG 2.4.3). Each now focuses the control + that took its place.""" + setup = _read("setup.js") + cases = [("startPlexConnect", "plex-connect-btn"), ("plexConnectAgain", "plex-connect-btn"), + ("jellyfinConnectAgain", "s-jellyfin-url")] + for name, want in cases: + fn = _fn(setup, name) + # Fakes: a drawn step swaps in a fresh element; only that one can be focused. + out = _node(""" +const state = {setupStep: 0, setupData: {}}; +let focusedId = null, drawn = 0; +globalThis.document = {getElementById: id => ({focus() { focusedId = drawn ? id : null; }})}; +globalThis.window = {open: () => null}; +const renderSetupStep = () => { drawn++; }; +const stopPlexConnect = () => {}, btnBusy = () => {}, btnDone = () => {}, t = k => k, toast = () => {}; +const api = async () => ({code: 'C', auth_url: 'x', login_id: '1', nonce: 'n'}); +let _plexPoll = null; const setInterval = () => 0; +%s +(async () => { + await %s(%s); + console.log(JSON.stringify({drawn, focusedId})); +})(); +""" % (fn, name, "{}" if name == "startPlexConnect" else "")) if fn else {} + if out is not None: + check("%s redraws, then focuses #%s" % (name, want), + out.get("drawn") == 1 and out.get("focusedId") == want) + + if __name__ == "__main__": for name, fn in list(globals().items()): if name.startswith("test_") and callable(fn): diff --git a/tests/test_backup_perms.py b/tests/test_backup_perms.py index 7165d4f8..35740d7e 100644 --- a/tests/test_backup_perms.py +++ b/tests/test_backup_perms.py @@ -2,7 +2,8 @@ * No tokens: users' Plex tokens are blanked in the backup copy, and their bytes overwritten (secure_delete) - a restore asks each member to sign in - once, as Plex keeps its own token out of its database backups. + once, as Plex keeps its own token out of its database backups. The + Jellyfin webhook secret (an app_state row) goes too. * 0600 like the live database, unless the operator sets BACKUP_GROUP_READABLE (0640, folders 0750) to copy backups off a NAS share. The start-up pass used to force every backup to 0600 whatever was @@ -30,6 +31,7 @@ POSIX = os.name == "posix" TOKEN = "zQ7plexTokenAbc123xy" +HOOK_SECRET = "hK9jellyfinHookSecret42" def mode(p): @@ -43,6 +45,9 @@ def mode(p): c.execute("create table users (id integer primary key, plex_username text, plex_token text)") c.execute("create table sessions (id integer primary key, access_token text, refresh_token text)") c.execute("insert into users (plex_username, plex_token) values ('owner', ?), ('member', ?)", (TOKEN, TOKEN[::-1])) +c.execute("create table app_state (key text primary key, value text, updated_at text)") +c.execute("insert into app_state (key, value) values ('jellyfin_hook_secret', ?), ('last_sync_at', '2026-11-17')", + (HOOK_SECRET,)) c.commit() c.close() dest = TMP / "backup.db" @@ -56,6 +61,13 @@ def mode(p): blob = dest.read_bytes() check("the token's bytes are gone from the file, not just unlinked (secure_delete)", TOKEN.encode() not in blob and TOKEN[::-1].encode() not in blob) +c = sqlite3.connect(f"file:{dest}?mode=ro", uri=True) +check("the Jellyfin webhook secret is not in the backup; the rest of app_state stays", + c.execute("select key from app_state").fetchall() == [("last_sync_at",)]) +c.close() +check("...nor its bytes", HOOK_SECRET.encode() not in blob) +from src.services.media_server import jellyfin_hook # noqa: E402 +check("the stripped key is the one the webhook route reads", jellyfin_hook.SECRET_KEY in sched._SECRET_STATE_KEYS) check("the backup is one file (no -wal beside it)", not (TMP / "backup.db-wal").exists()) c = sqlite3.connect(f"file:{src_db}?mode=ro", uri=True) check("the live database keeps its tokens", c.execute("select count(*) from users where plex_token is not null").fetchone()[0] == 2) @@ -77,8 +89,11 @@ def db(p): backup = data / "backups" / "curatarr_20261114_214712.db" +# A media-server switch's restore point: the whole database, tokens and all. +(data / "backups" / "rebind-20261110-120000").mkdir() +switch_copy = data / "backups" / "rebind-20261110-120000" / "curatarr.db" for p in (data / "curatarr.db", data / "cache" / "enrichment.db", backup, - data / "backups" / "caches" / "cache" / "lyrics.db"): + data / "backups" / "caches" / "cache" / "lyrics.db", switch_copy): db(p) env = root / ".env" env.write_text("JWT_SECRET=x\n", encoding="utf-8") @@ -103,6 +118,8 @@ def secure(group_readable): mode(backup) == 0o640 and mode(data / "backups" / "caches" / "cache" / "lyrics.db") == 0o640) check("...while the live database, a cache and .env stay 0600", {mode(data / "curatarr.db"), mode(data / "cache" / "enrichment.db"), mode(env)} == {0o600}) + check("...and so does a switch's restore point: its tokens are not blanked", + mode(switch_copy) == 0o600, oct(mode(switch_copy))) if not POSIX: check("(Windows: file modes are POSIX-only; the pass ran without error)", True) diff --git a/tests/test_milestones.py b/tests/test_milestones.py index 10234ae5..50e8ff1c 100644 --- a/tests/test_milestones.py +++ b/tests/test_milestones.py @@ -75,16 +75,16 @@ def play(cat, title, at, series=None, done=True, dur=None, off=None, s=None, e=N "1 year since the first play"]) first = ms.store(1, items, now=NOW) -check("the first run is history: nothing to announce", first == [] and ms.pending_announcements(1) == []) +check("the first run is history: nothing to announce", first == [] and ms.pending_announcements(1, now=NOW) == []) new = {"kind": "films", "value": 50, "reached_at": NOW - timedelta(days=2), "title": "Fiftieth"} fresh = ms.store(1, items + [new], now=NOW) check("a later run announces what is new and recent", [m["title"] for m in fresh] == ["Fiftieth"] - and [m["title"] for m in ms.pending_announcements(1)] == ["Fiftieth"]) + and [m["title"] for m in ms.pending_announcements(1, now=NOW)] == ["Fiftieth"]) ms.mark_announced(1, ["films:50"]) -check("...once", ms.pending_announcements(1) == []) +check("...once", ms.pending_announcements(1, now=NOW) == []) ms.store(1, items + [new, {"kind": "episodes", "value": 100, "reached_at": NOW - timedelta(days=30), "title": "Old News"}], now=NOW) -check("one reached a month before it was seen is history, not news", ms.pending_announcements(1) == []) +check("one reached a month before it was seen is history, not news", ms.pending_announcements(1, now=NOW) == []) ms.set_kind(1, "years", False) check("a kind switched off leaves the history", not any(m["kind"] == "years" for m in ms.history(1)) and ms.kinds_off(1) == {"years"}) diff --git a/tests/test_rebind.py b/tests/test_rebind.py index 9bee2a6b..542dab9f 100644 --- a/tests/test_rebind.py +++ b/tests/test_rebind.py @@ -27,6 +27,8 @@ import asyncio import json +import os +import stat import tempfile from pathlib import Path @@ -197,6 +199,13 @@ def rekey_facets(self, pairs): check("setting flipped, backup kept, manifest completed", flips == ["jellyfin"] and Path(m["backup"]).exists() and m["status"] == "completed" and m["settings"] == "plex-was-blank") +if os.name == "posix": + # The restore point keeps every member's Plex token: 0600 in a 0700 + # folder like the live database, whatever the umask or BACKUP_GROUP_READABLE. + snap = Path(m["backup"]) + check("the backup is 0600 in a 0700 folder (it carries the tokens)", + stat.S_IMODE(snap.stat().st_mode) == 0o600 and stat.S_IMODE(snap.parent.stat().st_mode) == 0o700, + (oct(snap.stat().st_mode), oct(snap.parent.stat().st_mode))) with conn_mod.engine.connect() as c: mem = dict(c.execute(text("SELECT canonical_key, jellyfin_id FROM server_id_map WHERE entity_type='user'")).fetchall()) check("users filed in the id memory", mem == {"user:1": JANE, "user:2": SAM}) diff --git a/tests/test_wrapup_comebacks_index.py b/tests/test_wrapup_comebacks_index.py index f13954a6..80df7551 100644 --- a/tests/test_wrapup_comebacks_index.py +++ b/tests/test_wrapup_comebacks_index.py @@ -30,7 +30,18 @@ def row(i, title, mt, at, series=None): row(9003, "ep 1", "show", now - timedelta(days=900), "Old Show"), # series: keyed by series row(9004, "ep 9", "show", now - timedelta(days=1), "Old Show"), row(9005, "Recent Film", "movie", now - timedelta(days=100)), # gap < a year - row(9006, "Recent Film", "movie", now - timedelta(days=1))] + row(9006, "Recent Film", "movie", now - timedelta(days=1)), + # played inside the year before: no comeback, and never worth the max() look-up + row(9007, "Regular", "movie", now - timedelta(days=40)), + row(9008, "Regular", "movie", now - timedelta(days=2)), + # just under / just over a year of silence before the week's first play + row(9009, "Edge Under", "movie", now - timedelta(days=364 + 2)), + row(9010, "Edge Under", "movie", now - timedelta(days=2)), + row(9011, "Edge Over", "movie", now - timedelta(days=366 + 2)), + row(9012, "Edge Over", "movie", now - timedelta(days=2)), + # exactly a year: the latest first play of the week minus 365 days + row(9013, "Edge Exact", "movie", now - timedelta(days=365 + 1)), + row(9014, "Edge Exact", "movie", now - timedelta(days=1))] db.bulk_insert_mappings(W, rows) db.commit() with conn.engine.begin() as c: @@ -49,8 +60,17 @@ def _grab(c, cur, stmt, params, *a): check("a film with no series_title comes back after 700 days", got.get("Old Film") == 698) check("a series comes back keyed by series_title", got.get("Old Show") == 899) check("a gap under a year is no comeback", "Recent Film" not in got) +check("a title played the year before is no comeback", "Regular" not in got) +check("364 days of silence is no comeback, 366 is", "Edge Under" not in got and got.get("Edge Over") == 366) stmt, params = next(s for s in statements if "max(watch_history.viewed_at)" in s[0]) +check("titles played within the year are not looked up at all", + not {"Regular", "Recent Film"} & set(params)) +# Exactly a year before the latest first play (now - 1 day - 365): still a +# comeback (gap >= 365), so the pre-filter must keep it for the look-up. It +# is the fourth-largest gap here, so the top three leave it out of ``got``. +check("a play exactly a year before is looked up, not filtered away (> cutoff, not >=)", + "Edge Exact" in set(params), params) raw = conn.engine.raw_connection() plan = " ".join(r[3] for r in raw.cursor().execute("EXPLAIN QUERY PLAN " + stmt, params)) raw.close() diff --git a/tests/test_wrapup_discovery_index.py b/tests/test_wrapup_discovery_index.py new file mode 100644 index 00000000..c5ea1027 --- /dev/null +++ b/tests/test_wrapup_discovery_index.py @@ -0,0 +1,62 @@ +"""The Wrap-Up's discovery look-up (wrapup_facts._discovery) asks "was this title +played before the period?" with one probe per title that stops at the first hit, +through the title indexes. `coalesce(series_title, title) IN (...)` plus DISTINCT +walked every earlier play of a regular artist (0.6 s a week on a 384k-play table, +0.04 s probing).""" +from _harness import app_db, check + +conn = app_db() +from datetime import datetime, timedelta, timezone # noqa: E402 + +from sqlalchemy import event, text # noqa: E402 + +import src.services.wrapup_facts as wf # noqa: E402 +from src.database.models import User, WatchHistoryEntry as W # noqa: E402 + +now = datetime(2026, 11, 15, 12, 0) +with conn.get_db_session() as db: + u = User(plex_user_id="p1", plex_username="u1") + db.add(u) + db.flush() + uid = u.id + + def row(i, title, mt, at, series=None): + return dict(user_id=uid, plex_user_id="p1", plex_item_id=f"i{i}", title=title, + media_type=mt, series_title=series, viewed_at=at, completed=True) + + rows = [row(i, f"track {i}", "music", now - timedelta(days=30 + i % 300), f"artist {i % 40}") + for i in range(4000)] + rows += [row(9001, "Old Film", "movie", now - timedelta(days=50)), + row(9002, "Old Film", "movie", now - timedelta(days=2)), + row(9003, "ep 1", "show", now - timedelta(days=60), "Old Show"), + row(9004, "ep 9", "show", now - timedelta(days=1), "Old Show"), + row(9005, "New Film", "movie", now - timedelta(days=1)), + row(9006, "Other", "movie", now - timedelta(days=50), "Old Film")] # series_title shadows title + db.bulk_insert_mappings(W, rows) + db.commit() +with conn.engine.begin() as c: + c.execute(text("ANALYZE")) + +statements = [] + +@event.listens_for(conn.engine, "before_cursor_execute") +def _grab(c, cur, stmt, params, *a): + statements.append((stmt, params)) + +period = wf.resolve_period("week:2026-W46", now, timezone.utc) +titles = [{"title": t, "hours": 1.0} for t in ("Old Film", "Old Show", "New Film", "artist 3")] +with conn.get_db_session() as db: + out = wf._discovery(db, W, uid, period, wf.scope_types("all"), titles) +check("only the title never played before is new", out["new_titles"] == 1 and out["best_new"] == "New Film", out) +check("returning titles counted (film, series, artist)", out["returning_titles"] == 3, out) + +probe = next((s for s in statements if "watch_history.viewed_at <" in s[0] and "LIMIT" in s[0]), None) +check("one first-hit probe per title, not a DISTINCT walk", probe is not None) +if probe is None: + check.done() +raw = conn.engine.raw_connection() +plan = " ".join(r[3] for r in raw.cursor().execute("EXPLAIN QUERY PLAN " + probe[0], probe[1])) +raw.close() +check("the look-up is an index search on both title columns, no scan", + "ix_wh_title" in plan and "SEARCH" in plan and "SCAN" not in plan, plan) +check.done()