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
+251 -63
View File
@@ -1,94 +1,282 @@
'use client'
"use client";
import { useState } from 'react'
import { getApiBase } from '../lib/auth'
import { useState } from "react";
import { getApiBase } from "../lib/auth";
export type Breakdown = { name: string; minutes: number }
export type Day = { date: string; minutes: number }
export type Breakdown = { name: string; minutes: number };
export type Day = { date: string; minutes: number };
export type Transcoding = {
video_minutes: number; audio_minutes: number; hardware_video_minutes: number; software_video_minutes: number
unknown_hardware_minutes: number; unknown_video_minutes: number; unknown_audio_minutes: number
hardware: Breakdown[]; audio_codecs: Breakdown[]; gpu_busy_minutes: null
}
video_minutes: number;
audio_minutes: number;
hardware_video_minutes: number;
software_video_minutes: number;
unknown_hardware_minutes: number;
unknown_video_minutes: number;
unknown_audio_minutes: number;
hardware: Breakdown[];
audio_codecs: Breakdown[];
gpu_busy_minutes: null;
};
export type Stats = {
state: 'ready' | 'not_configured' | 'unlinked'
is_admin: boolean
days: number
updated_at?: string
summary: null | { minutes: number; movies: number; episodes: number; plays: number; current_streak: number; longest_streak: number; active_days: number }
daily?: Day[]
patterns?: { average_play_minutes: number; longest_play_minutes: number; weekend_percent: number; weekdays: Breakdown[]; media: Breakdown[] }
top_titles?: { artwork_url?: string | null; title: string; type: string; minutes: number; plays: number }[]
recent?: { id: string; title: string; series: string; episode?: string; type: string; minutes: number; played_at: string; client: string; method: string; artwork_url?: string | null }[]
clients?: Breakdown[]
methods?: Breakdown[]
transcoding?: Transcoding
requests: { total: number; movies: number; tv: number; pending: number; approved: number; declined: number; recent: { request_id: number; title: string; media_type: string; status: number }[] }
}
state: "ready" | "not_configured" | "unlinked";
is_admin: boolean;
days: number;
updated_at?: string;
summary: null | {
minutes: number;
movies: number;
episodes: number;
plays: number;
current_streak: number;
longest_streak: number;
active_days: number;
};
daily?: Day[];
patterns?: {
average_play_minutes: number;
longest_play_minutes: number;
weekend_percent: number;
weekdays: Breakdown[];
media: Breakdown[];
};
top_titles?: { artwork_url?: string | null; title: string; type: string; minutes: number; plays: number }[];
recent?: {
id: string;
title: string;
series: string;
episode?: string;
type: string;
minutes: number;
played_at: string;
client: string;
method: string;
artwork_url?: string | null;
}[];
clients?: Breakdown[];
methods?: Breakdown[];
transcoding?: Transcoding;
requests: {
total: number;
movies: number;
tv: number;
pending: number;
approved: number;
declined: number;
recent: { request_id: number; title: string; media_type: string; status: number }[];
};
};
export const number = (value: number) => value.toLocaleString(undefined, { maximumFractionDigits: 0 })
export const dateLabel = (date: string) => new Date(date).toLocaleDateString(undefined, { month: 'short', day: 'numeric', timeZone: 'UTC' })
export const number = (value: number) => value.toLocaleString(undefined, { maximumFractionDigits: 0 });
export const dateLabel = (date: string) =>
new Date(date).toLocaleDateString(undefined, { month: "short", day: "numeric", timeZone: "UTC" });
export function ViewingChart({ daily }: { daily: Day[] }) {
const [selected, setSelected] = useState<number | null>(null)
const bucket = daily.length > 100 ? 7 : daily.length > 35 ? 3 : 1
const bars: { start: string; end: string; minutes: number }[] = []
const [selected, setSelected] = useState<number | null>(null);
const bucket = daily.length > 100 ? 7 : daily.length > 35 ? 3 : 1;
const bars: { start: string; end: string; minutes: number }[] = [];
for (let i = 0; i < daily.length; i += bucket) {
const group = daily.slice(i, i + bucket)
bars.push({ start: group[0].date, end: group[group.length - 1].date, minutes: group.reduce((sum, day) => sum + day.minutes, 0) })
const group = daily.slice(i, i + bucket);
bars.push({
start: group[0].date,
end: group[group.length - 1].date,
minutes: group.reduce((sum, day) => sum + day.minutes, 0),
});
}
const peak = Math.max(1, ...bars.map((bar) => bar.minutes))
const active = selected === null ? null : bars[selected]
const peak = Math.max(1, ...bars.map((bar) => bar.minutes));
const active = selected === null ? null : bars[selected];
return (
<section className="stats-panel stats-viewing" aria-labelledby="viewing-title">
<div className="stats-panel-heading"><div><h2 id="viewing-title">Your viewing rhythm</h2><p>{bucket === 1 ? 'Daily' : `${bucket}-day`} watch time · UTC</p></div><span className="stats-unit">Minutes</span></div>
<div className="stats-chart-detail" aria-live="polite">{active ? `${dateLabel(active.start)}${active.end !== active.start ? ` ${dateLabel(active.end)}` : ''} · ${number(active.minutes)} minutes` : 'Select a bar to explore your watch time.'}</div>
<div className="stats-panel-heading">
<div>
<h2 id="viewing-title">Your viewing rhythm</h2>
<p>{bucket === 1 ? "Daily" : `${bucket}-day`} watch time · UTC</p>
</div>
<span className="stats-unit">Minutes</span>
</div>
<div className="stats-chart-detail" aria-live="polite">
{active
? `${dateLabel(active.start)}${active.end !== active.start ? ` ${dateLabel(active.end)}` : ""} · ${number(active.minutes)} minutes`
: "Select a bar to explore your watch time."}
</div>
<div className="stats-chart">
<div className="stats-chart-scale" aria-hidden="true"><span>{number(peak)}</span><span>{number(peak / 2)}</span><span>0</span></div>
<div className="stats-chart-scale" aria-hidden="true">
<span>{number(peak)}</span>
<span>{number(peak / 2)}</span>
<span>0</span>
</div>
<div className="stats-chart-bars">
{bars.map((bar, index) => <button type="button" className={selected === index ? 'is-selected' : ''} key={bar.start} aria-label={`${dateLabel(bar.start)}${bar.end !== bar.start ? ` to ${dateLabel(bar.end)}` : ''}: ${number(bar.minutes)} minutes`} aria-pressed={selected === index} onClick={() => setSelected(index)} onFocus={() => setSelected(index)}><span style={{ height: `${bar.minutes > 0 ? Math.max(2, bar.minutes / peak * 100) : 1}%` }} /></button>)}
{bars.map((bar, index) => (
<button
type="button"
className={selected === index ? "is-selected" : ""}
key={bar.start}
aria-label={`${dateLabel(bar.start)}${bar.end !== bar.start ? ` to ${dateLabel(bar.end)}` : ""}: ${number(bar.minutes)} minutes`}
aria-pressed={selected === index}
onClick={() => setSelected(index)}
onFocus={() => setSelected(index)}
>
<span style={{ height: `${bar.minutes > 0 ? Math.max(2, (bar.minutes / peak) * 100) : 1}%` }} />
</button>
))}
</div>
</div>
<div className="stats-chart-axis" aria-hidden="true"><span>{bars[0] && dateLabel(bars[0].start)}</span><span>{bars.length > 0 && dateLabel(bars[bars.length - 1].end)}</span></div>
<div className="stats-chart-axis" aria-hidden="true">
<span>{bars[0] && dateLabel(bars[0].start)}</span>
<span>{bars.length > 0 && dateLabel(bars[bars.length - 1].end)}</span>
</div>
</section>
)
);
}
export function BreakdownCard({ title, rows }: { title: string; rows: Breakdown[] }) {
const total = rows.reduce((sum, row) => sum + row.minutes, 0)
return <section className="stats-panel"><div className="stats-panel-heading"><h2>{title}</h2></div>{rows.length ? <div className="stats-breakdown">{rows.map((row) => <div key={row.name}><div className="stats-breakdown-label"><span>{row.name}</span><strong>{number(row.minutes)} min</strong></div><div className="stats-meter"><span style={{ width: `${total ? row.minutes / total * 100 : 0}%` }} /></div></div>)}</div> : <p className="stats-muted">Your next watch will start the story here.</p>}</section>
const total = rows.reduce((sum, row) => sum + row.minutes, 0);
return (
<section className="stats-panel">
<div className="stats-panel-heading">
<h2>{title}</h2>
</div>
{rows.length ? (
<div className="stats-breakdown">
{rows.map((row) => (
<div key={row.name}>
<div className="stats-breakdown-label">
<span>{row.name}</span>
<strong>{number(row.minutes)} min</strong>
</div>
<div className="stats-meter">
<span style={{ width: `${total ? (row.minutes / total) * 100 : 0}%` }} />
</div>
</div>
))}
</div>
) : (
<p className="stats-muted">Your next watch will start the story here.</p>
)}
</section>
);
}
const minutes = (value: number) => `${value.toLocaleString(undefined, { maximumFractionDigits: 1 })} min`
const minutes = (value: number) => `${value.toLocaleString(undefined, { maximumFractionDigits: 1 })} min`;
export function StreamingCard({ rows, transcoding }: { rows: Breakdown[]; transcoding?: Transcoding }) {
const total = rows.reduce((sum, row) => sum + row.minutes, 0)
return <section className="stats-panel stats-streaming">
<div className="stats-panel-heading"><h2>How you streamed</h2></div>
<div className="stats-breakdown">{rows.map((row) => <div key={row.name}><div className="stats-breakdown-label"><span>{row.name}</span><strong>{minutes(row.minutes)}</strong></div><div className="stats-meter"><span style={{ width: `${total ? row.minutes / total * 100 : 0}%` }} /></div></div>)}</div>
{transcoding && <div className="stats-transcoding">
<h3>Transcoding playback time</h3>
<div className="stats-transcode-metrics">
<div><span>GPU-assisted video</span><strong>{transcoding.hardware_video_minutes === 0 && (transcoding.unknown_hardware_minutes > 0 || transcoding.unknown_video_minutes > 0) ? 'Not recorded' : minutes(transcoding.hardware_video_minutes)}</strong><small>{transcoding.hardware.map((entry) => `${entry.name} · ${minutes(entry.minutes)}`).join(' / ') || 'Hardware-accelerated video'}</small></div>
<div><span>Audio transcoding</span><strong>{transcoding.audio_minutes === 0 && transcoding.unknown_audio_minutes > 0 ? 'Not recorded' : minutes(transcoding.audio_minutes)}</strong><small>{transcoding.audio_codecs.slice(0, 3).map((entry) => `${entry.name} · ${minutes(entry.minutes)}`).join(' / ') || 'Audio converted for your player'}</small></div>
const total = rows.reduce((sum, row) => sum + row.minutes, 0);
return (
<section className="stats-panel stats-streaming">
<div className="stats-panel-heading">
<h2>How you streamed</h2>
</div>
<dl className="stats-transcode-details"><div><dt>Total video transcoding</dt><dd>{transcoding.video_minutes === 0 && transcoding.unknown_video_minutes > 0 ? 'Not recorded' : minutes(transcoding.video_minutes)}</dd></div>{transcoding.software_video_minutes > 0 && <div><dt>Software video</dt><dd>{minutes(transcoding.software_video_minutes)}</dd></div>}{transcoding.unknown_hardware_minutes > 0 && <div><dt>Video hardware not recorded</dt><dd>{minutes(transcoding.unknown_hardware_minutes)}</dd></div>}</dl>
{(transcoding.unknown_audio_minutes > 0 || transcoding.unknown_video_minutes > 0) && <p className="stats-muted">Some stream details are missing: video {minutes(transcoding.unknown_video_minutes)}, audio {minutes(transcoding.unknown_audio_minutes)}.</p>}
<p className="stats-muted">Playback minutes, with audio and video counted separately. They can overlap. GPU busy time is not recorded by Jellystat.</p>
</div>}
</section>
<div className="stats-breakdown">
{rows.map((row) => (
<div key={row.name}>
<div className="stats-breakdown-label">
<span>{row.name}</span>
<strong>{minutes(row.minutes)}</strong>
</div>
<div className="stats-meter">
<span style={{ width: `${total ? (row.minutes / total) * 100 : 0}%` }} />
</div>
</div>
))}
</div>
{transcoding && (
<div className="stats-transcoding">
<h3>Transcoding playback time</h3>
<div className="stats-transcode-metrics">
<div>
<span>GPU-assisted video</span>
<strong>
{transcoding.hardware_video_minutes === 0 &&
(transcoding.unknown_hardware_minutes > 0 || transcoding.unknown_video_minutes > 0)
? "Not recorded"
: minutes(transcoding.hardware_video_minutes)}
</strong>
<small>
{transcoding.hardware.map((entry) => `${entry.name} · ${minutes(entry.minutes)}`).join(" / ") ||
"Hardware-accelerated video"}
</small>
</div>
<div>
<span>Audio transcoding</span>
<strong>
{transcoding.audio_minutes === 0 && transcoding.unknown_audio_minutes > 0
? "Not recorded"
: minutes(transcoding.audio_minutes)}
</strong>
<small>
{transcoding.audio_codecs
.slice(0, 3)
.map((entry) => `${entry.name} · ${minutes(entry.minutes)}`)
.join(" / ") || "Audio converted for your player"}
</small>
</div>
</div>
<dl className="stats-transcode-details">
<div>
<dt>Total video transcoding</dt>
<dd>
{transcoding.video_minutes === 0 && transcoding.unknown_video_minutes > 0
? "Not recorded"
: minutes(transcoding.video_minutes)}
</dd>
</div>
{transcoding.software_video_minutes > 0 && (
<div>
<dt>Software video</dt>
<dd>{minutes(transcoding.software_video_minutes)}</dd>
</div>
)}
{transcoding.unknown_hardware_minutes > 0 && (
<div>
<dt>Video hardware not recorded</dt>
<dd>{minutes(transcoding.unknown_hardware_minutes)}</dd>
</div>
)}
</dl>
{(transcoding.unknown_audio_minutes > 0 || transcoding.unknown_video_minutes > 0) && (
<p className="stats-muted">
Some stream details are missing: video {minutes(transcoding.unknown_video_minutes)}, audio{" "}
{minutes(transcoding.unknown_audio_minutes)}.
</p>
)}
<p className="stats-muted">
Playback minutes, with audio and video counted separately. They can overlap. GPU busy time is not recorded
by Jellystat.
</p>
</div>
)}
</section>
);
}
export function RecentArtwork({ url, type }: { url?: string | null; type: string }) {
const [failed, setFailed] = useState(false)
return <div className={`stats-media-icon stats-media-icon-${type}`} aria-hidden="true">
{url && !failed ? <img src={`${getApiBase()}${url}`} alt="" width={44} height={66} loading="lazy" onError={() => setFailed(true)} /> : <span>{type === 'episode' ? 'TV' : type === 'movie' ? 'MV' : '▶'}</span>}
</div>
const [failed, setFailed] = useState(false);
return (
<div className={`stats-media-icon stats-media-icon-${type}`} aria-hidden="true">
{url && !failed ? (
<img
src={`${getApiBase()}${url}`}
alt=""
width={44}
height={66}
loading="lazy"
onError={() => setFailed(true)}
/>
) : (
<span>{type === "episode" ? "TV" : type === "movie" ? "MV" : "▶"}</span>
)}
</div>
);
}
export function StatsNavigation({ reports = false }: { reports?: boolean }) {
return <nav className="stats-view-tabs" aria-label="My Stats views">
<a href="/insights" aria-current={!reports ? 'page' : undefined}>Overview</a>
<a href="/insights/reports" aria-current={reports ? 'page' : undefined}>Monthly reports</a>
</nav>
return (
<nav className="stats-view-tabs" aria-label="My Stats views">
<a href="/insights" aria-current={!reports ? "page" : undefined}>
Overview
</a>
<a href="/insights/reports" aria-current={reports ? "page" : undefined}>
Monthly reports
</a>
</nav>
);
}
+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>
)
);
}
@@ -1,60 +1,108 @@
'use client'
"use client";
import { useEffect, useRef, useState } from 'react'
import { authFetch, getApiBase } from '../../lib/auth'
import { useEffect, useRef, useState } from "react";
import { authFetch, getApiBase } from "../../lib/auth";
type Delivery = { id: string; month: string; state: string; detail: string }
type Preference = { email: string | null; can_send: boolean; state: string; detail: string; deliveries: Delivery[] }
type Delivery = { id: string; month: string; state: string; detail: string };
type Preference = { email: string | null; can_send: boolean; state: string; detail: string; deliveries: Delivery[] };
export default function EmailReportControl({ month }: { month: string }) {
const [data, setData] = useState<Preference | null>(null)
const [busy, setBusy] = useState(false)
const [notice, setNotice] = useState('')
const [error, setError] = useState('')
const [revision, setRevision] = useState(0)
const request = useRef<{ month: string; id: string } | null>(null)
const pending = data?.deliveries.some((item) => ['queued', 'preparing', 'sending', 'retry'].includes(item.state)) ?? false
const [data, setData] = useState<Preference | null>(null);
const [busy, setBusy] = useState(false);
const [notice, setNotice] = useState("");
const [error, setError] = useState("");
const [revision, setRevision] = useState(0);
const request = useRef<{ month: string; id: string } | null>(null);
const pending =
data?.deliveries.some((item) => ["queued", "preparing", "sending", "retry"].includes(item.state)) ?? false;
useEffect(() => {
const abort = new AbortController()
void authFetch(`${getApiBase()}/profile/email-recaps`, { signal: abort.signal }).then(async (response) => {
if (!response.ok) throw new Error('Could not load your report email preferences. Refresh to try again.')
const result = await response.json()
if (!abort.signal.aborted) setData(result)
}).catch((err: Error) => { if (!abort.signal.aborted) setError(err.message) })
return () => abort.abort()
}, [revision])
void revision;
const abort = new AbortController();
void authFetch(`${getApiBase()}/profile/email-recaps`, { signal: abort.signal })
.then(async (response) => {
if (!response.ok) throw new Error("Could not load your report email preferences. Refresh to try again.");
const result = await response.json();
if (!abort.signal.aborted) setData(result);
})
.catch((err: Error) => {
if (!abort.signal.aborted) setError(err.message);
});
return () => abort.abort();
}, [revision]);
useEffect(() => {
if (!pending) return
const timer = window.setInterval(() => setRevision((value) => value + 1), 10000)
return () => window.clearInterval(timer)
}, [pending])
if (!pending) return;
const timer = window.setInterval(() => setRevision((value) => value + 1), 10000);
return () => window.clearInterval(timer);
}, [pending]);
const send = async () => {
if (busy || !data?.can_send) return
setBusy(true); setError(''); setNotice('')
if (request.current?.month !== month) request.current = { month, id: crypto.randomUUID() }
if (busy || !data?.can_send) return;
setBusy(true);
setError("");
setNotice("");
if (request.current?.month !== month) request.current = { month, id: crypto.randomUUID() };
try {
const response = await authFetch(`${getApiBase()}/profile/email-recaps/send`, {
method: 'POST', headers: { 'Content-Type': 'application/json' },
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ month, request_id: request.current.id }),
})
const result = await response.json().catch(() => ({}))
if (!response.ok) throw new Error(typeof result.detail === 'string' ? result.detail : 'Could not queue your report. Try again.')
setNotice(result.message); request.current = null
setRevision((value) => value + 1)
} catch (err) { setError(err instanceof Error ? err.message : 'Could not queue your report.') }
finally { setBusy(false) }
}
});
const result = await response.json().catch(() => ({}));
if (!response.ok)
throw new Error(typeof result.detail === "string" ? result.detail : "Could not queue your report. Try again.");
setNotice(result.message);
request.current = null;
setRevision((value) => value + 1);
} catch (err) {
setError(err instanceof Error ? err.message : "Could not queue your report.");
} finally {
setBusy(false);
}
};
return <section className="stats-panel report-email-panel" aria-label="Email your report">
<div className="stats-panel-heading"><h2>Email yourself this report</h2><a href="/profile#monthly-recaps">Email preferences</a></div>
<p>Choose a month above, including the current month so far, then send its viewing and request summary to your confirmed profile email.</p>
{data?.can_send ? <p><strong>{data.email}</strong> · One report email every five minutes.</p> : data && <p>{data.state === 'enabled' ? data.detail : 'Confirm your profile email in Email preferences first. You can choose on-demand delivery without automatic monthly emails.'}</p>}
<button type="button" disabled={busy || !data?.can_send} onClick={() => void send()}>{busy ? 'Queueing report…' : 'Email this report'}</button>
{notice && <p role="status">{notice}</p>}
{error && <p role="alert">{error}</p>}
{!!data?.deliveries.length && <details><summary>Recent report emails</summary><ul>{data.deliveries.map((item) => <li key={item.id}><strong>{item.month}</strong> · {item.state === 'sent' ? 'Accepted by mail server' : item.state} {item.detail || 'Waiting for delivery'}</li>)}</ul></details>}
</section>
return (
<section className="stats-panel report-email-panel" aria-label="Email your report">
<div className="stats-panel-heading">
<h2>Email yourself this report</h2>
<a href="/profile#monthly-recaps">Email preferences</a>
</div>
<p>
Choose a month above, including the current month so far, then send its viewing and request summary to your
confirmed profile email.
</p>
{data?.can_send ? (
<p>
<strong>{data.email}</strong> · One report email every five minutes.
</p>
) : (
data && (
<p>
{data.state === "enabled"
? data.detail
: "Confirm your profile email in Email preferences first. You can choose on-demand delivery without automatic monthly emails."}
</p>
)
)}
<button type="button" disabled={busy || !data?.can_send} onClick={() => void send()}>
{busy ? "Queueing report…" : "Email this report"}
</button>
{notice && <p role="status">{notice}</p>}
{error && <p role="alert">{error}</p>}
{!!data?.deliveries.length && (
<details>
<summary>Recent report emails</summary>
<ul>
{data.deliveries.map((item) => (
<li key={item.id}>
<strong>{item.month}</strong> · {item.state === "sent" ? "Accepted by mail server" : item.state} {" "}
{item.detail || "Waiting for delivery"}
</li>
))}
</ul>
</details>
)}
</section>
);
}
+508 -154
View File
@@ -1,177 +1,531 @@
'use client'
"use client";
import EmailReportControl from './EmailReportControl'
import EmailReportControl from "./EmailReportControl";
import { useCallback, useEffect, useRef, 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 './reports.css'
import { useCallback, useEffect, useRef, 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 "./reports.css";
type Change = { current: number; previous: number; difference: number; percent: number | null }
type MonthlyReport = Omit<Stats, 'days'> & {
month: string; available_months: string[]; is_partial: boolean; comparison_capped: boolean
period_start: string; period_end: string; comparison_month: string; comparison_start: string; comparison_end: string
previous_summary?: Stats['summary']; previous_requests?: Omit<Stats['requests'], 'recent'>
changes?: Record<'minutes' | 'movies' | 'episodes' | 'plays' | 'active_days' | 'longest_streak' | 'requests', Change>
}
type Change = { current: number; previous: number; difference: number; percent: number | null };
type MonthlyReport = Omit<Stats, "days"> & {
month: string;
available_months: string[];
is_partial: boolean;
comparison_capped: boolean;
period_start: string;
period_end: string;
comparison_month: string;
comparison_start: string;
comparison_end: string;
previous_summary?: Stats["summary"];
previous_requests?: Omit<Stats["requests"], "recent">;
changes?: Record<"minutes" | "movies" | "episodes" | "plays" | "active_days" | "longest_streak" | "requests", Change>;
};
const monthLabel = (month: string, short = false) => new Date(`${month}-01T00:00:00Z`).toLocaleDateString(undefined, { month: short ? 'short' : 'long', year: 'numeric', timeZone: 'UTC' })
const decimal = (value: number) => value.toLocaleString(undefined, { maximumFractionDigits: 1 })
const monthLabel = (month: string, short = false) =>
new Date(`${month}-01T00:00:00Z`).toLocaleDateString(undefined, {
month: short ? "short" : "long",
year: "numeric",
timeZone: "UTC",
});
const decimal = (value: number) => value.toLocaleString(undefined, { maximumFractionDigits: 1 });
function ChangeLabel({ change, unit = '' }: { change: Change; unit?: string }) {
const delta = change.difference
return <div className={`report-change ${delta > 0 ? 'is-up' : delta < 0 ? 'is-down' : 'is-flat'}`}>
<span>{delta === 0 ? 'No change' : `${delta > 0 ? '+' : ''}${decimal(Math.abs(delta))}${unit}${change.percent === null ? '' : ` (${delta > 0 ? '+' : ''}${decimal(Math.abs(change.percent))}%)`}`}</span>
<small>{change.percent === null ? 'No activity recorded in the comparison period' : `Previously ${decimal(change.previous)}${unit}`}</small>
</div>
function ChangeLabel({ change, unit = "" }: { change: Change; unit?: string }) {
const delta = change.difference;
return (
<div className={`report-change ${delta > 0 ? "is-up" : delta < 0 ? "is-down" : "is-flat"}`}>
<span>
{delta === 0
? "No change"
: `${delta > 0 ? "+" : ""}${decimal(Math.abs(delta))}${unit}${change.percent === null ? "" : ` (${delta > 0 ? "+" : ""}${decimal(Math.abs(change.percent))}%)`}`}
</span>
<small>
{change.percent === null
? "No activity recorded in the comparison period"
: `Previously ${decimal(change.previous)}${unit}`}
</small>
</div>
);
}
export default function MonthlyReportsPage() {
const router = useRouter()
const [month, setMonth] = useState('')
const [monthReady, setMonthReady] = useState(false)
const [months, setMonths] = useState<string[]>([])
const [data, setData] = useState<MonthlyReport | null>(null)
const [busy, setBusy] = useState(true)
const [error, setError] = useState('')
const [revision, setRevision] = useState(0)
const [downloading, setDownloading] = useState(false)
const [downloadError, setDownloadError] = useState('')
const downloadController = useRef<AbortController | null>(null)
const router = useRouter();
const [month, setMonth] = useState("");
const [monthReady, setMonthReady] = useState(false);
const [months, setMonths] = useState<string[]>([]);
const [data, setData] = useState<MonthlyReport | null>(null);
const [busy, setBusy] = useState(true);
const [error, setError] = useState("");
const [revision, setRevision] = useState(0);
const [downloading, setDownloading] = useState(false);
const [downloadError, setDownloadError] = useState("");
const downloadController = useRef<AbortController | null>(null);
useEffect(() => {
setMonth(new URLSearchParams(window.location.search).get('month') || '')
setMonthReady(true)
}, [])
setMonth(new URLSearchParams(window.location.search).get("month") || "");
setMonthReady(true);
}, []);
useEffect(() => {
if (monthReady) window.history.replaceState(null, '', `/insights/reports${month ? `?month=${encodeURIComponent(month)}` : ''}`)
}, [month, monthReady])
useEffect(() => () => downloadController.current?.abort(), [])
const load = useCallback(async (signal: AbortSignal) => {
setBusy(true)
setError('')
setData(null)
setDownloadError('')
try {
const query = month ? `?month=${encodeURIComponent(month)}` : ''
const response = await authFetch(`${getApiBase()}/insights/reports/monthly${query}`, { signal })
if (response.status === 401) { router.replace(`/login?next=${encodeURIComponent(`/insights/reports${query}`)}`); return }
if (response.status === 403) throw new Error('Your account cannot access viewing reports. Please contact an administrator.')
if (!response.ok) {
const result = await response.json().catch(() => ({}))
throw new Error(typeof result.detail === 'string' ? result.detail : 'Your report is temporarily unavailable. Please try again shortly.')
if (monthReady)
window.history.replaceState(null, "", `/insights/reports${month ? `?month=${encodeURIComponent(month)}` : ""}`);
}, [month, monthReady]);
useEffect(() => () => downloadController.current?.abort(), []);
const load = useCallback(
async (signal: AbortSignal) => {
setBusy(true);
setError("");
setData(null);
setDownloadError("");
try {
const query = month ? `?month=${encodeURIComponent(month)}` : "";
const response = await authFetch(`${getApiBase()}/insights/reports/monthly${query}`, { signal });
if (response.status === 401) {
router.replace(`/login?next=${encodeURIComponent(`/insights/reports${query}`)}`);
return;
}
if (response.status === 403)
throw new Error("Your account cannot access viewing reports. Please contact an administrator.");
if (!response.ok) {
const result = await response.json().catch(() => ({}));
throw new Error(
typeof result.detail === "string"
? result.detail
: "Your report is temporarily unavailable. Please try again shortly.",
);
}
const result = (await response.json()) as MonthlyReport;
if (!signal.aborted) {
setData(result);
setMonths(result.available_months);
}
} catch (err) {
if (!signal.aborted) setError(err instanceof Error ? err.message : "Could not load your report.");
} finally {
if (!signal.aborted) setBusy(false);
}
const result = await response.json() as MonthlyReport
if (!signal.aborted) { setData(result); setMonths(result.available_months) }
} catch (err) {
if (!signal.aborted) setError(err instanceof Error ? err.message : 'Could not load your report.')
} finally {
if (!signal.aborted) setBusy(false)
}
}, [month, router])
},
[month, router],
);
useEffect(() => {
if (!monthReady) return
const controller = new AbortController()
void load(controller.signal)
return () => controller.abort()
}, [load, revision, monthReady])
void revision;
if (!monthReady) return;
const controller = new AbortController();
void load(controller.signal);
return () => controller.abort();
}, [load, revision, monthReady]);
const download = async () => {
if (data?.state !== 'ready' || downloading) return
const selected = data.month
const controller = new AbortController()
downloadController.current = controller
setDownloading(true)
setDownloadError('')
if (data?.state !== "ready" || downloading) return;
const selected = data.month;
const controller = new AbortController();
downloadController.current = controller;
setDownloading(true);
setDownloadError("");
try {
const response = await authFetch(`${getApiBase()}/insights/reports/monthly.csv?month=${selected}`, { signal: controller.signal })
if (response.status === 401) { router.replace(`/login?next=${encodeURIComponent(`/insights/reports?month=${selected}`)}`); return }
if (!response.ok) throw new Error('The report could not be downloaded. Please try again.')
const blob = await response.blob()
if (controller.signal.aborted) return
const url = URL.createObjectURL(blob)
const link = document.createElement('a')
link.href = url
link.download = `magent-monthly-report-${selected}.csv`
document.body.appendChild(link)
link.click()
link.remove()
window.setTimeout(() => URL.revokeObjectURL(url), 1000)
const response = await authFetch(`${getApiBase()}/insights/reports/monthly.csv?month=${selected}`, {
signal: controller.signal,
});
if (response.status === 401) {
router.replace(`/login?next=${encodeURIComponent(`/insights/reports?month=${selected}`)}`);
return;
}
if (!response.ok) throw new Error("The report could not be downloaded. Please try again.");
const blob = await response.blob();
if (controller.signal.aborted) return;
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = `magent-monthly-report-${selected}.csv`;
document.body.appendChild(link);
link.click();
link.remove();
window.setTimeout(() => URL.revokeObjectURL(url), 1000);
} catch (err) {
if (!controller.signal.aborted) setDownloadError(err instanceof Error ? err.message : 'Could not download your report.')
if (!controller.signal.aborted)
setDownloadError(err instanceof Error ? err.message : "Could not download your report.");
} finally {
if (!controller.signal.aborted) setDownloading(false)
if (!controller.signal.aborted) setDownloading(false);
}
}
};
const selectedMonth = month || data?.month || ''
const monthIndex = months.indexOf(selectedMonth)
const summary = data?.summary
const changes = data?.changes
return <main className="stats-page reports-page">
<PageHeading title="Monthly report" description="Your month in viewing. See what you watched, what changed, and what you requested." actions={<>
<button className="ghost-button" type="button" disabled={busy || downloading} onClick={() => setRevision((value) => value + 1)}>Refresh report</button>
<button className="ghost-button" type="button" disabled={busy || downloading || data?.state !== 'ready'} onClick={() => void download()}>{downloading ? 'Downloading…' : 'Download CSV'}</button>
</>} />
<StatsNavigation reports />
<div className="stats-toolbar">
<div className="report-month-picker">
<button type="button" className="ghost-button" aria-label="Previous month" disabled={busy || downloading || monthIndex < 0 || monthIndex >= months.length - 1} onClick={() => setMonth(months[monthIndex + 1])}></button>
<label><span className="stats-sr-only">Report month</span><select value={selectedMonth} disabled={busy || downloading || !months.length} onChange={(event) => setMonth(event.target.value)}>{!selectedMonth && <option value="">Latest complete month</option>}{months.map((value, index) => <option value={value} key={value}>{monthLabel(value)}{index === 0 ? ' · month to date' : ''}</option>)}</select></label>
<button type="button" className="ghost-button" aria-label="Next month" disabled={busy || downloading || monthIndex <= 0} onClick={() => setMonth(months[monthIndex - 1])}></button>
</div>
<p className="stats-source"><span className={data?.state === 'ready' ? 'stats-source-dot is-ready' : 'stats-source-dot'} />From Jellystat · UTC</p>
</div>
{downloadError && <p className="stats-notice" role="alert">{downloadError}</p>}
{data?.state === 'ready' && !busy && <EmailReportControl month={data.month} />}
{busy && <div className="stats-state" role="status"><span className="stats-state-symbol" aria-hidden="true"></span><h2>Putting your month together</h2><p>Gathering your viewing history and the previous months comparison.</p></div>}
{error && <div className="stats-state" role="alert"><h2>Report couldnt load</h2><p>{error}</p><button type="button" className="ghost-button" onClick={() => setRevision((value) => value + 1)}>Try again</button>{month && <button type="button" className="ghost-button" onClick={() => setMonth('')}>Latest complete month</button>}</div>}
{data?.state === 'not_configured' && <section className="stats-state"><h2>Your monthly story starts here</h2><p>{data.is_admin ? 'Connect Jellystat to bring your monthly viewing reports into Magent.' : 'Monthly reports will appear 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 report needs your Jellyfin account link. Sign in using Jellyfin, or ask your administrator to review your user identities.</p>{data.is_admin && <a className="stats-action" href="/admin/identities">Review user identities</a>}</section>}
{data && summary && changes && <>
<section className="report-intro" aria-label="Report period">
<div><span className="report-kicker">{data.is_partial ? 'Month to date' : 'Your monthly recap'}</span><h2>{monthLabel(data.month)}</h2><p>{data.is_partial ? `Compared with the same elapsed time in ${monthLabel(data.comparison_month)}${data.comparison_capped ? ', capped at the end of that month' : ''}.` : `Compared with ${monthLabel(data.comparison_month)}.`}</p></div>
<div className="report-period-meta"><span>{data.is_partial ? 'In progress' : 'Complete month'}</span><small>{data.updated_at && `Updated ${new Date(data.updated_at).toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short', timeZone: 'UTC' })} UTC`}</small></div>
</section>
<section className="stats-metrics" aria-label="Monthly totals">
<article className="stats-metric stats-metric-accent"><span>Minutes watched</span><strong>{number(summary.minutes)}</strong><small>{decimal(summary.minutes / 60)} hours across {number(summary.plays)} plays</small><ChangeLabel change={changes.minutes} unit=" min" /></article>
<article className="stats-metric"><span>Movies played</span><strong>{number(summary.movies)}</strong><small>Different movies you pressed play on</small><ChangeLabel change={changes.movies} /></article>
<article className="stats-metric"><span>Episodes played</span><strong>{number(summary.episodes)}</strong><small>Different episodes in your history</small><ChangeLabel change={changes.episodes} /></article>
<article className="stats-metric"><span>Requests made</span><strong>{number(data.requests.total)}</strong><small>{data.requests.movies} movies · {data.requests.tv} TV requests</small><ChangeLabel change={changes.requests} /></article>
</section>
{summary.plays === 0 && <div className="stats-notice" role="status">No viewing history was recorded for this month. Your request totals and comparison are still shown.</div>}
<div className="stats-main-grid">
<ViewingChart key={`${data.month}-${revision}`} daily={data.daily ?? []} />
<section className="stats-panel report-highlights"><div className="stats-panel-heading"><h2>Your viewing habits</h2></div>
<div className="stats-highlight"><span className="stats-highlight-number">{summary.active_days}<small> days</small></span><div><strong>Days you watched</strong><p>At least one minute of viewing.</p><ChangeLabel change={changes.active_days} unit=" days" /></div></div>
<div className="stats-highlight"><span className="stats-highlight-number">{summary.longest_streak}<small> days</small></span><div><strong>Longest run</strong><p>Consecutive viewing days this month.</p><ChangeLabel change={changes.longest_streak} unit=" days" /></div></div>
<div className="stats-highlight"><span className="stats-highlight-number">{data.daily?.length ? number(summary.minutes / data.daily.length) : 0}<small> min</small></span><div><strong>Daily average</strong><p>Across the calendar days in this report.</p></div></div>
</section>
</div>
{data.patterns && <>
<section className="report-pattern-summary" aria-label="Viewing insights">
<article><span>Average play</span><strong>{decimal(data.patterns.average_play_minutes)} <small>min</small></strong><p>Time per recorded playback session.</p></article>
<article><span>Longest play</span><strong>{decimal(data.patterns.longest_play_minutes)} <small>min</small></strong><p>Your longest recorded session this month.</p></article>
<article><span>Weekend viewing</span><strong>{decimal(data.patterns.weekend_percent)}<small>%</small></strong><p>Share of viewing on Saturday and Sunday (UTC).</p></article>
</section>
<div className="stats-main-grid">
<BreakdownCard title="Your week in viewing (UTC)" rows={data.patterns.weekdays} />
<BreakdownCard title="Movies, TV and more" rows={data.patterns.media} />
const selectedMonth = month || data?.month || "";
const monthIndex = months.indexOf(selectedMonth);
const summary = data?.summary;
const changes = data?.changes;
return (
<main className="stats-page reports-page">
<PageHeading
title="Monthly report"
description="Your month in viewing. See what you watched, what changed, and what you requested."
actions={
<>
<button
className="ghost-button"
type="button"
disabled={busy || downloading}
onClick={() => setRevision((value) => value + 1)}
>
Refresh report
</button>
<button
className="ghost-button"
type="button"
disabled={busy || downloading || data?.state !== "ready"}
onClick={() => void download()}
>
{downloading ? "Downloading…" : "Download CSV"}
</button>
</>
}
/>
<StatsNavigation reports />
<div className="stats-toolbar">
<div className="report-month-picker">
<button
type="button"
className="ghost-button"
aria-label="Previous month"
disabled={busy || downloading || monthIndex < 0 || monthIndex >= months.length - 1}
onClick={() => setMonth(months[monthIndex + 1])}
>
</button>
<label>
<span className="stats-sr-only">Report month</span>
<select
value={selectedMonth}
disabled={busy || downloading || !months.length}
onChange={(event) => setMonth(event.target.value)}
>
{!selectedMonth && <option value="">Latest complete month</option>}
{months.map((value, index) => (
<option value={value} key={value}>
{monthLabel(value)}
{index === 0 ? " · month to date" : ""}
</option>
))}
</select>
</label>
<button
type="button"
className="ghost-button"
aria-label="Next month"
disabled={busy || downloading || monthIndex <= 0}
onClick={() => setMonth(months[monthIndex - 1])}
>
</button>
</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 report-top-titles">{data.top_titles.map((title, index) => <li key={`${title.title}-${index}`}><RecentArtwork url={title.artwork_url} type={title.type} /><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 most watched titles will appear here.</p>}</section>
<BreakdownCard title="Your players" rows={data.clients ?? []} />
<StreamingCard rows={data.methods ?? []} transcoding={data.transcoding} />
<p className="stats-source">
<span className={data?.state === "ready" ? "stats-source-dot is-ready" : "stats-source-dot"} />
From Jellystat · UTC
</p>
</div>
<div className="stats-main-grid">
<section className="stats-panel stats-history"><div className="stats-panel-heading"><h2>A look back</h2><span className="stats-unit">Latest 20 plays this month</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 during this month 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 {monthLabel(data.month, true)}</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 ? <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">No requests recorded during this month.</p>}<p className="stats-muted">Statuses reflect where these requests are now.</p></section>
</div>
<p className="stats-footnote">Private to your account · Based on history retained by Jellystat and requests available in Magent. Plays include unfinished watches. Dates and streaks use UTC. Reports may take a minute to refresh; historical totals can change when retained history or library metadata changes.</p>
</>}
</main>
{downloadError && (
<p className="stats-notice" role="alert">
{downloadError}
</p>
)}
{data?.state === "ready" && !busy && <EmailReportControl month={data.month} />}
{busy && (
<div className="stats-state" role="status">
<span className="stats-state-symbol" aria-hidden="true">
</span>
<h2>Putting your month together</h2>
<p>Gathering your viewing history and the previous months comparison.</p>
</div>
)}
{error && (
<div className="stats-state" role="alert">
<h2>Report couldnt load</h2>
<p>{error}</p>
<button type="button" className="ghost-button" onClick={() => setRevision((value) => value + 1)}>
Try again
</button>
{month && (
<button type="button" className="ghost-button" onClick={() => setMonth("")}>
Latest complete month
</button>
)}
</div>
)}
{data?.state === "not_configured" && (
<section className="stats-state">
<h2>Your monthly story starts here</h2>
<p>
{data.is_admin
? "Connect Jellystat to bring your monthly viewing reports into Magent."
: "Monthly reports will appear 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 report needs your Jellyfin account link. Sign in using Jellyfin, or ask your administrator to review
your user identities.
</p>
{data.is_admin && (
<a className="stats-action" href="/admin/identities">
Review user identities
</a>
)}
</section>
)}
{data && summary && changes && (
<>
<section className="report-intro" aria-label="Report period">
<div>
<span className="report-kicker">{data.is_partial ? "Month to date" : "Your monthly recap"}</span>
<h2>{monthLabel(data.month)}</h2>
<p>
{data.is_partial
? `Compared with the same elapsed time in ${monthLabel(data.comparison_month)}${data.comparison_capped ? ", capped at the end of that month" : ""}.`
: `Compared with ${monthLabel(data.comparison_month)}.`}
</p>
</div>
<div className="report-period-meta">
<span>{data.is_partial ? "In progress" : "Complete month"}</span>
<small>
{data.updated_at &&
`Updated ${new Date(data.updated_at).toLocaleString(undefined, { dateStyle: "medium", timeStyle: "short", timeZone: "UTC" })} UTC`}
</small>
</div>
</section>
<section className="stats-metrics" aria-label="Monthly totals">
<article className="stats-metric stats-metric-accent">
<span>Minutes watched</span>
<strong>{number(summary.minutes)}</strong>
<small>
{decimal(summary.minutes / 60)} hours across {number(summary.plays)} plays
</small>
<ChangeLabel change={changes.minutes} unit=" min" />
</article>
<article className="stats-metric">
<span>Movies played</span>
<strong>{number(summary.movies)}</strong>
<small>Different movies you pressed play on</small>
<ChangeLabel change={changes.movies} />
</article>
<article className="stats-metric">
<span>Episodes played</span>
<strong>{number(summary.episodes)}</strong>
<small>Different episodes in your history</small>
<ChangeLabel change={changes.episodes} />
</article>
<article className="stats-metric">
<span>Requests made</span>
<strong>{number(data.requests.total)}</strong>
<small>
{data.requests.movies} movies · {data.requests.tv} TV requests
</small>
<ChangeLabel change={changes.requests} />
</article>
</section>
{summary.plays === 0 && (
<div className="stats-notice" role="status">
No viewing history was recorded for this month. Your request totals and comparison are still shown.
</div>
)}
<div className="stats-main-grid">
<ViewingChart key={`${data.month}-${revision}`} daily={data.daily ?? []} />
<section className="stats-panel report-highlights">
<div className="stats-panel-heading">
<h2>Your viewing habits</h2>
</div>
<div className="stats-highlight">
<span className="stats-highlight-number">
{summary.active_days}
<small> days</small>
</span>
<div>
<strong>Days you watched</strong>
<p>At least one minute of viewing.</p>
<ChangeLabel change={changes.active_days} unit=" days" />
</div>
</div>
<div className="stats-highlight">
<span className="stats-highlight-number">
{summary.longest_streak}
<small> days</small>
</span>
<div>
<strong>Longest run</strong>
<p>Consecutive viewing days this month.</p>
<ChangeLabel change={changes.longest_streak} unit=" days" />
</div>
</div>
<div className="stats-highlight">
<span className="stats-highlight-number">
{data.daily?.length ? number(summary.minutes / data.daily.length) : 0}
<small> min</small>
</span>
<div>
<strong>Daily average</strong>
<p>Across the calendar days in this report.</p>
</div>
</div>
</section>
</div>
{data.patterns && (
<>
<section className="report-pattern-summary" aria-label="Viewing insights">
<article>
<span>Average play</span>
<strong>
{decimal(data.patterns.average_play_minutes)} <small>min</small>
</strong>
<p>Time per recorded playback session.</p>
</article>
<article>
<span>Longest play</span>
<strong>
{decimal(data.patterns.longest_play_minutes)} <small>min</small>
</strong>
<p>Your longest recorded session this month.</p>
</article>
<article>
<span>Weekend viewing</span>
<strong>
{decimal(data.patterns.weekend_percent)}
<small>%</small>
</strong>
<p>Share of viewing on Saturday and Sunday (UTC).</p>
</article>
</section>
<div className="stats-main-grid">
<BreakdownCard title="Your week in viewing (UTC)" rows={data.patterns.weekdays} />
<BreakdownCard title="Movies, TV and more" rows={data.patterns.media} />
</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 report-top-titles">
{data.top_titles.map((title, index) => (
<li key={`${title.title}-${index}`}>
<RecentArtwork url={title.artwork_url} type={title.type} />
<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 most watched titles will appear here.</p>
)}
</section>
<BreakdownCard title="Your players" rows={data.clients ?? []} />
<StreamingCard rows={data.methods ?? []} transcoding={data.transcoding} />
</div>
<div className="stats-main-grid">
<section className="stats-panel stats-history">
<div className="stats-panel-heading">
<h2>A look back</h2>
<span className="stats-unit">Latest 20 plays this month</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 during this month 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 {monthLabel(data.month, true)}</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 ? (
<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">No requests recorded during this month.</p>
)}
<p className="stats-muted">Statuses reflect where these requests are now.</p>
</section>
</div>
<p className="stats-footnote">
Private to your account · Based on history retained by Jellystat and requests available in Magent. Plays
include unfinished watches. Dates and streaks use UTC. Reports may take a minute to refresh; historical
totals can change when retained history or library metadata changes.
</p>
</>
)}
</main>
);
}