chore: standardize security and quality foundations
Magent CI/CD / verify (push) Failing after 9m34s
Magent CI/CD / deploy-beta (push) Skipped

This commit is contained in:
2026-09-17 20:03:47 +12:00
parent 5639dbcb83
commit f852e7c941
127 changed files with 17928 additions and 10741 deletions
+318 -68
View File
@@ -1,86 +1,336 @@
'use client'
"use client";
import { useCallback, useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'
import { authFetch, getApiBase } from '../lib/auth'
import PageHeading from '../ui/PageHeading'
import { type Stats, BreakdownCard, RecentArtwork, StatsNavigation, StreamingCard, ViewingChart, dateLabel, number } from './components'
import './stats.css'
import { useCallback, useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { authFetch, getApiBase } from "../lib/auth";
import PageHeading from "../ui/PageHeading";
import {
type Stats,
BreakdownCard,
RecentArtwork,
StatsNavigation,
StreamingCard,
ViewingChart,
dateLabel,
number,
} from "./components";
import "./stats.css";
export default function InsightsPage() {
const router = useRouter()
const [days, setDays] = useState(30)
const [data, setData] = useState<Stats | null>(null)
const [busy, setBusy] = useState(true)
const [error, setError] = useState('')
const [revision, setRevision] = useState(0)
const load = useCallback(async (signal: AbortSignal) => {
setBusy(true)
setError('')
setData(null)
try {
const response = await authFetch(`${getApiBase()}/insights?days=${days}`, { signal })
if (response.status === 401) { router.replace('/login?next=%2Finsights'); return }
if (response.status === 403) throw new Error('Your account cannot access viewing stats. Please contact an administrator.')
if (!response.ok) {
const result = await response.json().catch(() => ({}))
throw new Error(typeof result.detail === 'string' ? result.detail : 'Your viewing stats are temporarily unavailable. Please try again shortly.')
const router = useRouter();
const [days, setDays] = useState(30);
const [data, setData] = useState<Stats | null>(null);
const [busy, setBusy] = useState(true);
const [error, setError] = useState("");
const [revision, setRevision] = useState(0);
const load = useCallback(
async (signal: AbortSignal) => {
setBusy(true);
setError("");
setData(null);
try {
const response = await authFetch(`${getApiBase()}/insights?days=${days}`, { signal });
if (response.status === 401) {
router.replace("/login?next=%2Finsights");
return;
}
if (response.status === 403)
throw new Error("Your account cannot access viewing stats. Please contact an administrator.");
if (!response.ok) {
const result = await response.json().catch(() => ({}));
throw new Error(
typeof result.detail === "string"
? result.detail
: "Your viewing stats are temporarily unavailable. Please try again shortly.",
);
}
const result = (await response.json()) as Stats;
if (!signal.aborted) setData(result);
} catch (err) {
if (!signal.aborted) setError(err instanceof Error ? err.message : "Could not load your stats.");
} finally {
if (!signal.aborted) setBusy(false);
}
const result = await response.json() as Stats
if (!signal.aborted) setData(result)
} catch (err) {
if (!signal.aborted) setError(err instanceof Error ? err.message : 'Could not load your stats.')
} finally {
if (!signal.aborted) setBusy(false)
}
}, [days, router])
},
[days, router],
);
useEffect(() => {
const controller = new AbortController()
void load(controller.signal)
return () => controller.abort()
}, [load, revision])
void revision;
const controller = new AbortController();
void load(controller.signal);
return () => controller.abort();
}, [load, revision]);
const summary = data?.summary
const summary = data?.summary;
return (
<main className="stats-page">
<PageHeading title="My Stats" description="Your viewing, in numbers. Watch time, favourite stories, and the requests that started it all." actions={<button className="ghost-button" type="button" disabled={busy} onClick={() => setRevision((value) => value + 1)}>{busy ? 'Loading…' : 'Refresh stats'}</button>} />
<PageHeading
title="My Stats"
description="Your viewing, in numbers. Watch time, favourite stories, and the requests that started it all."
actions={
<button
className="ghost-button"
type="button"
disabled={busy}
onClick={() => setRevision((value) => value + 1)}
>
{busy ? "Loading…" : "Refresh stats"}
</button>
}
/>
<StatsNavigation />
<div className="stats-toolbar">
<fieldset className="stats-period"><legend className="stats-sr-only">Stats period</legend>{[7, 30, 90, 365].map((value) => <button type="button" key={value} aria-pressed={days === value} onClick={() => setDays(value)}>{value === 365 ? 'Past year' : `${value} days`}</button>)}</fieldset>
<p className="stats-source"><span className={data?.state === 'ready' ? 'stats-source-dot is-ready' : 'stats-source-dot'} />From Jellystat{data?.updated_at && <span> · Updated {new Date(data.updated_at).toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' })}</span>}</p>
<fieldset className="stats-period">
<legend className="stats-sr-only">Stats period</legend>
{[7, 30, 90, 365].map((value) => (
<button type="button" key={value} aria-pressed={days === value} onClick={() => setDays(value)}>
{value === 365 ? "Past year" : `${value} days`}
</button>
))}
</fieldset>
<p className="stats-source">
<span className={data?.state === "ready" ? "stats-source-dot is-ready" : "stats-source-dot"} />
From Jellystat
{data?.updated_at && (
<span>
{" "}
· Updated{" "}
{new Date(data.updated_at).toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit" })}
</span>
)}
</p>
</div>
{busy && <div className="stats-state" role="status"><span className="stats-state-symbol" aria-hidden="true"></span><h2>Gathering your stats</h2><p>Fetching your viewing history from Jellystat.</p></div>}
{error && <div className="stats-state" role="alert"><h2>Stats couldnt load</h2><p>{error}</p><button type="button" className="ghost-button" onClick={() => setRevision((value) => value + 1)}>Try again</button></div>}
{data?.state === 'not_configured' && <section className="stats-state"><span className="stats-state-symbol" aria-hidden="true"></span><h2>Your viewing story starts here</h2><p>{data.is_admin ? 'Connect your Jellystat instance to bring personal viewing stats into Magent.' : 'Viewing stats will appear here once your administrator connects Jellystat.'}</p>{data.is_admin && <a className="stats-action" href="/admin/jellystat">Connect Jellystat</a>}</section>}
{data?.state === 'unlinked' && <section className="stats-state"><h2>Link your viewing account</h2><p>Your Magent account needs a Jellyfin identity to find your stats. Sign in using Jellyfin, or ask your administrator to sync Jellyfin users.</p></section>}
{summary && <>
<section className="stats-metrics" aria-label="Viewing totals">
<article className="stats-metric stats-metric-accent"><span>Minutes watched</span><strong>{number(summary.minutes)}</strong><small>{number(summary.minutes / 60)} hours across {number(summary.plays)} plays</small></article>
<article className="stats-metric"><span>Movies played</span><strong>{number(summary.movies)}</strong><small>Different movies you pressed play on</small></article>
<article className="stats-metric"><span>Episodes played</span><strong>{number(summary.episodes)}</strong><small>Different episodes in your history</small></article>
<article className="stats-metric"><span>Requests made</span><strong>{number(data.requests.total)}</strong><small>{number(data.requests.movies)} movies · {number(data.requests.tv)} TV requests</small></article>
{busy && (
<div className="stats-state" role="status">
<span className="stats-state-symbol" aria-hidden="true">
</span>
<h2>Gathering your stats</h2>
<p>Fetching your viewing history from Jellystat.</p>
</div>
)}
{error && (
<div className="stats-state" role="alert">
<h2>Stats couldnt load</h2>
<p>{error}</p>
<button type="button" className="ghost-button" onClick={() => setRevision((value) => value + 1)}>
Try again
</button>
</div>
)}
{data?.state === "not_configured" && (
<section className="stats-state">
<span className="stats-state-symbol" aria-hidden="true">
</span>
<h2>Your viewing story starts here</h2>
<p>
{data.is_admin
? "Connect your Jellystat instance to bring personal viewing stats into Magent."
: "Viewing stats will appear here once your administrator connects Jellystat."}
</p>
{data.is_admin && (
<a className="stats-action" href="/admin/jellystat">
Connect Jellystat
</a>
)}
</section>
{summary.plays === 0 && <div className="stats-notice" role="status">No viewing history in this period yet. Try a longer period, or come back after your next watch.</div>}
)}
{data?.state === "unlinked" && (
<section className="stats-state">
<h2>Link your viewing account</h2>
<p>
Your Magent account needs a Jellyfin identity to find your stats. Sign in using Jellyfin, or ask your
administrator to sync Jellyfin users.
</p>
</section>
)}
{summary && (
<>
<section className="stats-metrics" aria-label="Viewing totals">
<article className="stats-metric stats-metric-accent">
<span>Minutes watched</span>
<strong>{number(summary.minutes)}</strong>
<small>
{number(summary.minutes / 60)} hours across {number(summary.plays)} plays
</small>
</article>
<article className="stats-metric">
<span>Movies played</span>
<strong>{number(summary.movies)}</strong>
<small>Different movies you pressed play on</small>
</article>
<article className="stats-metric">
<span>Episodes played</span>
<strong>{number(summary.episodes)}</strong>
<small>Different episodes in your history</small>
</article>
<article className="stats-metric">
<span>Requests made</span>
<strong>{number(data.requests.total)}</strong>
<small>
{number(data.requests.movies)} movies · {number(data.requests.tv)} TV requests
</small>
</article>
</section>
{summary.plays === 0 && (
<div className="stats-notice" role="status">
No viewing history in this period yet. Try a longer period, or come back after your next watch.
</div>
)}
<div className="stats-main-grid">
<ViewingChart key={`${days}-${revision}`} daily={data.daily ?? []} />
<section className="stats-panel stats-highlights">
<div className="stats-panel-heading">
<h2>A little watch history</h2>
</div>
<div className="stats-highlight">
<span className="stats-highlight-number">
{summary.current_streak}
<small> days</small>
</span>
<div>
<strong>Current streak</strong>
<p>Consecutive viewing days through today or yesterday.</p>
</div>
</div>
<div className="stats-highlight">
<span className="stats-highlight-number">
{summary.longest_streak}
<small> days</small>
</span>
<div>
<strong>Longest run</strong>
<p>Your best streak in this period.</p>
</div>
</div>
<div className="stats-highlight">
<span className="stats-highlight-number">
{summary.active_days}
<small> days</small>
</span>
<div>
<strong>Time for a story</strong>
<p>Days with at least a minute watched.</p>
</div>
</div>
</section>
</div>
<div className="stats-three-grid">
<section className="stats-panel">
<div className="stats-panel-heading">
<h2>Most watched</h2>
<span className="stats-unit">By minutes</span>
</div>
{data.top_titles?.length ? (
<ol className="stats-top-titles">
{data.top_titles.map((title, index) => (
<li key={`${title.title}-${index}`}>
<span className="stats-rank">{String(index + 1).padStart(2, "0")}</span>
<div>
<strong>{title.title}</strong>
<small>
{title.type === "series" ? "TV series" : title.type === "movie" ? "Movie" : "Other media"} ·{" "}
{title.plays} plays
</small>
</div>
<span>
{number(title.minutes)}
<small>min</small>
</span>
</li>
))}
</ol>
) : (
<p className="stats-muted">Your favourites will find their place here.</p>
)}
</section>
<BreakdownCard title="Your players" rows={data.clients ?? []} />
<StreamingCard rows={data.methods ?? []} transcoding={data.transcoding} />
</div>
</>
)}
{data && (
<div className="stats-main-grid">
<ViewingChart key={`${days}-${revision}`} daily={data.daily ?? []} />
<section className="stats-panel stats-highlights"><div className="stats-panel-heading"><h2>A little watch history</h2></div>
<div className="stats-highlight"><span className="stats-highlight-number">{summary.current_streak}<small> days</small></span><div><strong>Current streak</strong><p>Consecutive viewing days through today or yesterday.</p></div></div>
<div className="stats-highlight"><span className="stats-highlight-number">{summary.longest_streak}<small> days</small></span><div><strong>Longest run</strong><p>Your best streak in this period.</p></div></div>
<div className="stats-highlight"><span className="stats-highlight-number">{summary.active_days}<small> days</small></span><div><strong>Time for a story</strong><p>Days with at least a minute watched.</p></div></div>
{summary && (
<section className="stats-panel stats-history">
<div className="stats-panel-heading">
<h2>Recently watched</h2>
<span className="stats-unit">Latest 20 plays</span>
</div>
{data.recent?.length ? (
<div className="stats-history-list">
{data.recent.map((play) => (
<article key={play.id}>
<RecentArtwork key={play.artwork_url ?? play.id} url={play.artwork_url} type={play.type} />
<div className="stats-history-title">
<strong>{play.series || play.title}</strong>
<small>
{play.series ? `${play.episode} · ${play.title}` : play.type === "movie" ? "Movie" : "Media"}
</small>
<span>
{play.client} · {play.method}
</span>
</div>
<div className="stats-history-time">
<strong>{number(play.minutes)} min</strong>
<time dateTime={play.played_at}>{dateLabel(play.played_at)}</time>
</div>
</article>
))}
</div>
) : (
<p className="stats-muted">Plays recorded by Jellystat will appear here.</p>
)}
</section>
)}
<section className="stats-panel stats-requests">
<div className="stats-panel-heading">
<h2>Your requests</h2>
<a href="/">View all</a>
</div>
<div className="stats-request-total">
<strong>{data.requests.total}</strong>
<span>submitted in the past {days} days</span>
</div>
<div className="stats-request-counts">
<span>
<strong>{data.requests.pending}</strong> Pending
</span>
<span>
<strong>{data.requests.approved}</strong> Approved
</span>
<span>
<strong>{data.requests.declined}</strong> Declined
</span>
</div>
{data.requests.recent.length > 0 ? (
<ul className="stats-request-list">
{data.requests.recent.map((request) => (
<li key={request.request_id}>
<a href={`/requests/${request.request_id}`}>
{request.title || `Request ${request.request_id}`}
<span aria-hidden="true"></span>
</a>
</li>
))}
</ul>
) : (
<p className="stats-muted">
Something on your watchlist? <a href="/new-requests">Make a request.</a>
</p>
)}
</section>
</div>
<div className="stats-three-grid">
<section className="stats-panel"><div className="stats-panel-heading"><h2>Most watched</h2><span className="stats-unit">By minutes</span></div>{data.top_titles?.length ? <ol className="stats-top-titles">{data.top_titles.map((title, index) => <li key={`${title.title}-${index}`}><span className="stats-rank">{String(index + 1).padStart(2, '0')}</span><div><strong>{title.title}</strong><small>{title.type === 'series' ? 'TV series' : title.type === 'movie' ? 'Movie' : 'Other media'} · {title.plays} plays</small></div><span>{number(title.minutes)}<small>min</small></span></li>)}</ol> : <p className="stats-muted">Your favourites will find their place here.</p>}</section>
<BreakdownCard title="Your players" rows={data.clients ?? []} />
<StreamingCard rows={data.methods ?? []} transcoding={data.transcoding} />
</div>
</>}
{data && <div className="stats-main-grid">
{summary && <section className="stats-panel stats-history"><div className="stats-panel-heading"><h2>Recently watched</h2><span className="stats-unit">Latest 20 plays</span></div>{data.recent?.length ? <div className="stats-history-list">{data.recent.map((play) => <article key={play.id}><RecentArtwork key={play.artwork_url ?? play.id} url={play.artwork_url} type={play.type} /><div className="stats-history-title"><strong>{play.series || play.title}</strong><small>{play.series ? `${play.episode} · ${play.title}` : play.type === 'movie' ? 'Movie' : 'Media'}</small><span>{play.client} · {play.method}</span></div><div className="stats-history-time"><strong>{number(play.minutes)} min</strong><time dateTime={play.played_at}>{dateLabel(play.played_at)}</time></div></article>)}</div> : <p className="stats-muted">Plays recorded by Jellystat will appear here.</p>}</section>}
<section className="stats-panel stats-requests"><div className="stats-panel-heading"><h2>Your requests</h2><a href="/">View all</a></div><div className="stats-request-total"><strong>{data.requests.total}</strong><span>submitted in the past {days} days</span></div><div className="stats-request-counts"><span><strong>{data.requests.pending}</strong> Pending</span><span><strong>{data.requests.approved}</strong> Approved</span><span><strong>{data.requests.declined}</strong> Declined</span></div>{data.requests.recent.length > 0 ? <ul className="stats-request-list">{data.requests.recent.map((request) => <li key={request.request_id}><a href={`/requests/${request.request_id}`}>{request.title || `Request ${request.request_id}`}<span aria-hidden="true"></span></a></li>)}</ul> : <p className="stats-muted">Something on your watchlist? <a href="/new-requests">Make a request.</a></p>}</section>
</div>}
{summary && <p className="stats-footnote">Private to your account · Stats come from Jellystat and may take a minute to refresh. Counts describe plays, including unfinished watches. Movies are identified from Jellystats movie libraries; other media still contributes to watch time. Charts and streaks use UTC and the activity dates recorded by Jellystat.</p>}
)}
{summary && (
<p className="stats-footnote">
Private to your account · Stats come from Jellystat and may take a minute to refresh. Counts describe plays,
including unfinished watches. Movies are identified from Jellystats movie libraries; other media still
contributes to watch time. Charts and streaks use UTC and the activity dates recorded by Jellystat.
</p>
)}
</main>
)
);
}