Add history page with list, timeline and year in review
- Backend: /history/years and /history/:year return every movie and episode watch in a year, with entry posters, genres, networks and buddies - History tab: watches by month and day, back-to-back episodes grouped - Timeline tab: latest to oldest, month dividers, stacked binge sessions - Year in Review tab: hours, top shows and genres, streaks, busiest day, biggest binge, monthly and weekday charts, buddies and new shows - Year picker, movies/TV filter, state kept in the URL; unknown-date watches badged and excluded from the review by default - History link in the sidebar and command palette
This commit is contained in:
1 parent
c4aa0488d4
commit
760afd8e84
13 files changed
+1724
No files matched your search
@@ -0,0 +1,373 @@
|
||||
import { getMediaUrl, getTmdbImageUrl } from "@/lib/api";
|
||||
import type { HistoryEntry, HistoryEpisode, HistoryEvent } from "@/api/history";
|
||||
|
||||
export type HistoryTypeFilter = "all" | "movies" | "tv";
|
||||
|
||||
export const MONTH_NAMES = Array.from({ length: 12 }, (_, m) =>
|
||||
new Date(2000, m, 1).toLocaleDateString("en-US", { month: "long" }),
|
||||
);
|
||||
export const WEEKDAY_NAMES = Array.from({ length: 7 }, (_, d) =>
|
||||
// 2000-01-02 was a Sunday
|
||||
new Date(2000, 0, 2 + d).toLocaleDateString("en-US", { weekday: "short" }),
|
||||
);
|
||||
|
||||
const DEFAULT_POSTER = "/images/default-poster.png";
|
||||
|
||||
/** Selected local poster first, then the TMDB poster. */
|
||||
export function posterUrl(entry: HistoryEntry | undefined, size = "w185") {
|
||||
if (!entry) return DEFAULT_POSTER;
|
||||
const local = entry.medias?.find((m) => m.type === "poster" && m.isSelected);
|
||||
if (local) return getMediaUrl("entries", "posters", "preview", local.path);
|
||||
return entry.poster_path
|
||||
? getTmdbImageUrl(entry.poster_path, size)
|
||||
: DEFAULT_POSTER;
|
||||
}
|
||||
|
||||
export function episodeCode(ep: HistoryEpisode | null | undefined) {
|
||||
if (!ep) return "";
|
||||
const s = ep.season_number ?? "?";
|
||||
return `S${s}E${ep.episode_number}`;
|
||||
}
|
||||
|
||||
export function eventRuntime(
|
||||
event: HistoryEvent,
|
||||
entries: Record<number, HistoryEntry>,
|
||||
) {
|
||||
if (event.kind === "episode") {
|
||||
return event.episode?.runtime ?? entries[event.entry_id]?.runtime ?? 0;
|
||||
}
|
||||
return entries[event.entry_id]?.runtime ?? 0;
|
||||
}
|
||||
|
||||
export function filterEvents(events: HistoryEvent[], type: HistoryTypeFilter) {
|
||||
if (type === "movies") return events.filter((e) => e.kind === "movie");
|
||||
if (type === "tv") return events.filter((e) => e.kind === "episode");
|
||||
return events;
|
||||
}
|
||||
|
||||
/** Local calendar day, e.g. "2024-12-31". */
|
||||
export function dayKey(date: string | Date) {
|
||||
const d = new Date(date);
|
||||
const mm = String(d.getMonth() + 1).padStart(2, "0");
|
||||
const dd = String(d.getDate()).padStart(2, "0");
|
||||
return `${d.getFullYear()}-${mm}-${dd}`;
|
||||
}
|
||||
|
||||
export function formatMinutes(minutes: number) {
|
||||
if (minutes < 60) return `${minutes}m`;
|
||||
const h = Math.floor(minutes / 60);
|
||||
const m = minutes % 60;
|
||||
return m ? `${h}h ${m}m` : `${h}h`;
|
||||
}
|
||||
|
||||
/* ---------- Sessions ---------- */
|
||||
|
||||
/**
|
||||
* A movie watch, or a run of episodes of the same show watched one after the
|
||||
* other on the same day.
|
||||
*/
|
||||
export interface HistorySession {
|
||||
key: string;
|
||||
kind: "movie" | "episode";
|
||||
entry: HistoryEntry | undefined;
|
||||
entryId: number;
|
||||
date: string; // latest watch in the session
|
||||
day: string;
|
||||
events: HistoryEvent[]; // oldest → newest
|
||||
minutes: number;
|
||||
unknownDate: boolean;
|
||||
}
|
||||
|
||||
/** Groups newest-first events into sessions (also newest-first). */
|
||||
export function buildSessions(
|
||||
events: HistoryEvent[],
|
||||
entries: Record<number, HistoryEntry>,
|
||||
): HistorySession[] {
|
||||
const sessions: HistorySession[] = [];
|
||||
for (const event of events) {
|
||||
const day = dayKey(event.date_seen);
|
||||
const last = sessions.at(-1);
|
||||
if (
|
||||
last &&
|
||||
event.kind === "episode" &&
|
||||
last.kind === "episode" &&
|
||||
last.entryId === event.entry_id &&
|
||||
last.day === day
|
||||
) {
|
||||
last.events.unshift(event);
|
||||
last.minutes += eventRuntime(event, entries);
|
||||
last.unknownDate ||= event.accuracy === "UNKNOWN";
|
||||
continue;
|
||||
}
|
||||
sessions.push({
|
||||
key: event.id,
|
||||
kind: event.kind,
|
||||
entry: entries[event.entry_id],
|
||||
entryId: event.entry_id,
|
||||
date: event.date_seen,
|
||||
day,
|
||||
events: [event],
|
||||
minutes: eventRuntime(event, entries),
|
||||
unknownDate: event.accuracy === "UNKNOWN",
|
||||
});
|
||||
}
|
||||
// Episodes within a session in watch order (season, episode)
|
||||
for (const s of sessions) {
|
||||
if (s.kind === "episode" && s.events.length > 1) {
|
||||
s.events.sort(
|
||||
(a, b) =>
|
||||
(a.episode?.season_number ?? 0) - (b.episode?.season_number ?? 0) ||
|
||||
(a.episode?.episode_number ?? 0) - (b.episode?.episode_number ?? 0),
|
||||
);
|
||||
}
|
||||
}
|
||||
return sessions;
|
||||
}
|
||||
|
||||
/** "S1 E1–E5" for a session's episodes, or "S1 E3" for one. */
|
||||
export function sessionEpisodeLabel(session: HistorySession) {
|
||||
const eps = session.events.map((e) => e.episode).filter(Boolean);
|
||||
if (eps.length === 0) return "";
|
||||
if (eps.length === 1) return episodeCode(eps[0]);
|
||||
const first = eps[0]!;
|
||||
const last = eps.at(-1)!;
|
||||
if (first.season_number === last.season_number) {
|
||||
return `S${first.season_number} E${first.episode_number}–E${last.episode_number}`;
|
||||
}
|
||||
return `${episodeCode(first)} – ${episodeCode(last)}`;
|
||||
}
|
||||
|
||||
/** Episode page for a single episode, otherwise the entry page. */
|
||||
export function sessionLink(session: HistorySession) {
|
||||
if (session.kind === "episode" && session.events.length === 1) {
|
||||
const ep = session.events[0].episode;
|
||||
if (ep) {
|
||||
return `/entry/${session.entryId}/season/${ep.season_id}/episode/${ep.id}`;
|
||||
}
|
||||
}
|
||||
return `/entry/${session.entryId}`;
|
||||
}
|
||||
|
||||
export interface MonthGroup {
|
||||
month: number; // 0-11
|
||||
sessions: HistorySession[];
|
||||
movies: number;
|
||||
episodes: number;
|
||||
minutes: number;
|
||||
}
|
||||
|
||||
/** Sessions bucketed by month, December first. Empty months are skipped. */
|
||||
export function groupByMonth(sessions: HistorySession[]): MonthGroup[] {
|
||||
const months = new Map<number, MonthGroup>();
|
||||
for (const s of sessions) {
|
||||
const month = new Date(s.date).getMonth();
|
||||
let group = months.get(month);
|
||||
if (!group) {
|
||||
group = { month, sessions: [], movies: 0, episodes: 0, minutes: 0 };
|
||||
months.set(month, group);
|
||||
}
|
||||
group.sessions.push(s);
|
||||
group.minutes += s.minutes;
|
||||
if (s.kind === "movie") group.movies++;
|
||||
else group.episodes += s.events.length;
|
||||
}
|
||||
return [...months.values()].sort((a, b) => b.month - a.month);
|
||||
}
|
||||
|
||||
/* ---------- Year in review ---------- */
|
||||
|
||||
export interface YearReview {
|
||||
totalMinutes: number;
|
||||
movieWatches: number;
|
||||
uniqueMovies: number;
|
||||
episodeWatches: number;
|
||||
uniqueShows: number;
|
||||
activeDays: number;
|
||||
topShows: { entry: HistoryEntry; episodes: number; minutes: number }[];
|
||||
topMovies: { entry: HistoryEntry; rating: number; watches: number }[];
|
||||
rewatches: { entry: HistoryEntry; watches: number }[];
|
||||
topGenres: { name: string; minutes: number; share: number }[];
|
||||
topNetworks: { name: string; logo_path: string | null; episodes: number }[];
|
||||
monthly: { movies: number; episodes: number; minutes: number }[];
|
||||
weekdays: number[];
|
||||
busiestDay: { day: string; watches: number; minutes: number } | null;
|
||||
longestStreak: { days: number; start: string; end: string } | null;
|
||||
biggestBinge: { entry: HistoryEntry; day: string; episodes: number } | null;
|
||||
startedShows: HistoryEntry[];
|
||||
topBuddies: { id: number; name: string; watches: number }[];
|
||||
first: HistoryEvent | null;
|
||||
last: HistoryEvent | null;
|
||||
}
|
||||
|
||||
const top = <T>(items: T[], score: (t: T) => number, n: number) =>
|
||||
[...items].sort((a, b) => score(b) - score(a)).slice(0, n);
|
||||
|
||||
/** Year-in-review stats from a year's events (any order). */
|
||||
export function computeReview(
|
||||
events: HistoryEvent[],
|
||||
entries: Record<number, HistoryEntry>,
|
||||
): YearReview {
|
||||
const sorted = [...events].sort(
|
||||
(a, b) => new Date(a.date_seen).getTime() - new Date(b.date_seen).getTime(),
|
||||
);
|
||||
|
||||
let totalMinutes = 0;
|
||||
const movieCounts = new Map<number, number>();
|
||||
const showStats = new Map<number, { episodes: number; minutes: number }>();
|
||||
const genreMinutes = new Map<string, number>();
|
||||
const networkEpisodes = new Map<string, { logo: string | null; n: number }>();
|
||||
const monthly = Array.from({ length: 12 }, () => ({
|
||||
movies: 0,
|
||||
episodes: 0,
|
||||
minutes: 0,
|
||||
}));
|
||||
const weekdays = Array(7).fill(0) as number[];
|
||||
const days = new Map<string, { watches: number; minutes: number }>();
|
||||
const showDays = new Map<string, number>(); // `${entryId}|${day}` → episodes
|
||||
const firstEpisodeOfShow = new Map<number, HistoryEvent>();
|
||||
const buddies = new Map<number, { name: string; watches: number }>();
|
||||
|
||||
for (const event of sorted) {
|
||||
const entry = entries[event.entry_id];
|
||||
const minutes = eventRuntime(event, entries);
|
||||
const date = new Date(event.date_seen);
|
||||
const day = dayKey(date);
|
||||
totalMinutes += minutes;
|
||||
|
||||
if (event.kind === "movie") {
|
||||
movieCounts.set(
|
||||
event.entry_id,
|
||||
(movieCounts.get(event.entry_id) ?? 0) + 1,
|
||||
);
|
||||
monthly[date.getMonth()].movies++;
|
||||
} else {
|
||||
const s = showStats.get(event.entry_id) ?? { episodes: 0, minutes: 0 };
|
||||
s.episodes++;
|
||||
s.minutes += minutes;
|
||||
showStats.set(event.entry_id, s);
|
||||
monthly[date.getMonth()].episodes++;
|
||||
const k = `${event.entry_id}|${day}`;
|
||||
showDays.set(k, (showDays.get(k) ?? 0) + 1);
|
||||
if (!firstEpisodeOfShow.has(event.entry_id)) {
|
||||
firstEpisodeOfShow.set(event.entry_id, event);
|
||||
}
|
||||
for (const n of entry?.networks ?? []) {
|
||||
const cur = networkEpisodes.get(n.name) ?? { logo: n.logo_path, n: 0 };
|
||||
cur.n++;
|
||||
networkEpisodes.set(n.name, cur);
|
||||
}
|
||||
}
|
||||
monthly[date.getMonth()].minutes += minutes;
|
||||
weekdays[date.getDay()]++;
|
||||
|
||||
const d = days.get(day) ?? { watches: 0, minutes: 0 };
|
||||
d.watches++;
|
||||
d.minutes += minutes;
|
||||
days.set(day, d);
|
||||
|
||||
for (const g of entry?.genres ?? []) {
|
||||
genreMinutes.set(g, (genreMinutes.get(g) ?? 0) + minutes);
|
||||
}
|
||||
for (const b of event.buddies) {
|
||||
const cur = buddies.get(b.id) ?? { name: b.name, watches: 0 };
|
||||
cur.watches++;
|
||||
buddies.set(b.id, cur);
|
||||
}
|
||||
}
|
||||
|
||||
// Longest run of consecutive days with at least one watch
|
||||
let longestStreak: YearReview["longestStreak"] = null;
|
||||
const dayList = [...days.keys()].sort();
|
||||
let runStart = 0;
|
||||
for (let i = 1; i <= dayList.length; i++) {
|
||||
const prev = new Date(dayList[i - 1]);
|
||||
const isNext =
|
||||
i < dayList.length &&
|
||||
new Date(dayList[i]).getTime() - prev.getTime() <= 36 * 60 * 60 * 1000;
|
||||
if (!isNext) {
|
||||
const length = i - runStart;
|
||||
if (!longestStreak || length > longestStreak.days) {
|
||||
longestStreak = {
|
||||
days: length,
|
||||
start: dayList[runStart],
|
||||
end: dayList[i - 1],
|
||||
};
|
||||
}
|
||||
runStart = i;
|
||||
}
|
||||
}
|
||||
|
||||
const busiest = top([...days.entries()], ([, d]) => d.minutes, 1)[0];
|
||||
const binge = top([...showDays.entries()], ([, n]) => n, 1)[0];
|
||||
const totalGenreMinutes =
|
||||
[...genreMinutes.values()].reduce((a, b) => a + b, 0) || 1;
|
||||
|
||||
const movieEntries = [...movieCounts.keys()]
|
||||
.map((id) => entries[id])
|
||||
.filter(Boolean);
|
||||
|
||||
return {
|
||||
totalMinutes,
|
||||
movieWatches: sorted.filter((e) => e.kind === "movie").length,
|
||||
uniqueMovies: movieCounts.size,
|
||||
episodeWatches: sorted.filter((e) => e.kind === "episode").length,
|
||||
uniqueShows: showStats.size,
|
||||
activeDays: days.size,
|
||||
topShows: top([...showStats.entries()], ([, s]) => s.episodes, 5)
|
||||
.filter(([id]) => entries[id])
|
||||
.map(([id, s]) => ({ entry: entries[id], ...s })),
|
||||
topMovies: top(movieEntries, (e) => e.entryRating?.user_rating || 0, 5)
|
||||
.filter((e) => (e.entryRating?.user_rating ?? 0) > 0)
|
||||
.map((e) => ({
|
||||
entry: e,
|
||||
rating: e.entryRating!.user_rating!,
|
||||
watches: movieCounts.get(e.id) ?? 1,
|
||||
})),
|
||||
rewatches: top(
|
||||
movieEntries.filter((e) => (movieCounts.get(e.id) ?? 0) > 1),
|
||||
(e) => movieCounts.get(e.id) ?? 0,
|
||||
5,
|
||||
).map((e) => ({ entry: e, watches: movieCounts.get(e.id)! })),
|
||||
topGenres: top([...genreMinutes.entries()], ([, m]) => m, 6).map(
|
||||
([name, minutes]) => ({
|
||||
name,
|
||||
minutes,
|
||||
share: minutes / totalGenreMinutes,
|
||||
}),
|
||||
),
|
||||
topNetworks: top([...networkEpisodes.entries()], ([, v]) => v.n, 5).map(
|
||||
([name, v]) => ({ name, logo_path: v.logo, episodes: v.n }),
|
||||
),
|
||||
monthly,
|
||||
weekdays,
|
||||
busiestDay: busiest
|
||||
? {
|
||||
day: busiest[0],
|
||||
watches: busiest[1].watches,
|
||||
minutes: busiest[1].minutes,
|
||||
}
|
||||
: null,
|
||||
longestStreak,
|
||||
biggestBinge:
|
||||
binge && binge[1] > 1 && entries[Number(binge[0].split("|")[0])]
|
||||
? {
|
||||
entry: entries[Number(binge[0].split("|")[0])],
|
||||
day: binge[0].split("|")[1],
|
||||
episodes: binge[1],
|
||||
}
|
||||
: null,
|
||||
// Shows whose first episode watched this year was S1E1
|
||||
startedShows: [...firstEpisodeOfShow.values()]
|
||||
.filter(
|
||||
(e) =>
|
||||
e.episode?.season_number === 1 && e.episode?.episode_number === 1,
|
||||
)
|
||||
.map((e) => entries[e.entry_id])
|
||||
.filter(Boolean),
|
||||
topBuddies: top([...buddies.entries()], ([, b]) => b.watches, 5).map(
|
||||
([id, b]) => ({ id, ...b }),
|
||||
),
|
||||
first: sorted[0] ?? null,
|
||||
last: sorted.at(-1) ?? null,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user