feat(history): browse my listening by year and month

GET /listens/months counts the listens that count in each calendar month,
newest first, in the time zone the client sends (the zone database is built
into the binary). GET /listens takes from and until to read one month, and
each listen now names its artists.

The web app has a History page: a button for each year with its listens, the
months of the year as bars, and the listens of the chosen month a day at a
time, with the choice kept in the address.
This commit is contained in:
tgiachi 2026-11-15 12:07:19 +01:00
commit 9f63121028
9 changed files with 909 additions and 16 deletions

31
web/src/api/history.ts Normal file
View file

@ -0,0 +1,31 @@
import { useQuery } from '@tanstack/react-query'
import { api } from '@/api/client'
import type { components } from '@/api/schema'
import { usePagedList } from '@/api/catalog'
export type ListenItem = components['schemas']['ListenItem']
export type ListenMonth = { year: number; month: number; plays: number }
/** The time zone of this browser: months start where the listener's own start. */
export const browserZone = () => Intl.DateTimeFormat().resolvedOptions().timeZone
/** How many listens that count were made in each month, newest first (months with none are not there). */
export function useListenMonths() {
return useQuery({
queryKey: ['/listens/months', browserZone()],
queryFn: () => api.get<{ months: ListenMonth[] }>('/listens/months', { tz: browserZone() }),
select: (data) => data.months,
})
}
/** The listens that count in one month of this browser's time zone, newest first, a page after the other. */
export function useMonthListens(month: { year: number; month: number } | null) {
// The first of the month at midnight, in the zone of the browser, is the same moment the server counted from.
const from = month ? new Date(month.year, month.month - 1, 1) : null
const until = month ? new Date(month.year, month.month, 1) : null
return usePagedList<ListenItem>(
'/listens',
{ counted: 'true', from: from?.toISOString(), until: until?.toISOString() },
{ pageSize: 100, enabled: month !== null },
)
}

View file

@ -2146,6 +2146,29 @@ export interface paths {
patch?: never;
trace?: never;
};
"/listens/months": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
/**
* How much you listened in each month
* @description The number of listens that count (see `POST /listens`) in each calendar month, newest month first. Months
* are counted in the time zone of `tz` (UTC when absent), so they start where yours do. A month with none is
* not in the list. Use it to browse `GET /listens` by month with `from` and `until`. Nobody else's history
* is visible.
*/
get: operations["listListenMonths"];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/listens": {
parameters: {
query?: never;
@ -3300,6 +3323,12 @@ export interface components {
/** Format: int64 */
id: number;
title: string;
/** @description The artists credited on the track, the main ones first. */
artists: {
/** Format: int64 */
id: number;
name: string;
}[];
};
/** @enum {string} */
event_type: "play" | "complete" | "skip";
@ -7882,6 +7911,36 @@ export interface operations {
};
};
};
listListenMonths: {
parameters: {
query?: {
/** @description An IANA time zone name, like `Europe/Rome`. Anything else is `invalid_input`. */
tz?: string;
};
header?: never;
path?: never;
cookie?: never;
};
requestBody?: never;
responses: {
/** @description The months. */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
months: {
year: number;
month: number;
plays: number;
}[];
};
};
};
401: components["responses"]["Unauthorized"];
};
};
listListens: {
parameters: {
query?: {
@ -7890,6 +7949,10 @@ export interface operations {
offset?: components["parameters"]["Offset"];
/** @description Send `true` to list only the events that count as a listen. */
counted?: true;
/** @description Only the events from this moment (included), like `2025-03-01T00:00:00Z`. */
from?: string;
/** @description Only the events before this moment (excluded). It must be after `from` when both are sent (`invalid_input`). */
until?: string;
};
header?: never;
path?: never;

View file

@ -27,7 +27,7 @@ function renderSidebar(friends: { id: number; name: string }[] = [], path = '/al
test('the menu is words, one for each page, and the page that is open is the current one', () => {
const nav = renderSidebar()
for (const name of ['Home', 'Search', 'Discover', 'Artists', 'Albums', 'Songs', 'Mixes', 'Playlists', 'Smart playlists', 'Import', 'Admin', 'Settings']) {
for (const name of ['Home', 'Search', 'Discover', 'Artists', 'Albums', 'Songs', 'Mixes', 'Playlists', 'Smart playlists', 'History', 'Import', 'Admin', 'Settings']) {
expect(within(nav).getByRole('link', { name })).toBeInTheDocument()
}
expect(within(nav).getByRole('link', { name: 'Albums' })).toHaveAttribute('aria-current', 'page')

View file

@ -15,6 +15,7 @@ const LINKS: { to: string; key: string; end: boolean; adminOnly: boolean; friend
{ to: '/mixes', key: 'nav.mixes', end: false, adminOnly: false },
{ to: '/playlists', key: 'nav.playlists', end: false, adminOnly: false },
{ to: '/smart-playlists', key: 'nav.smartPlaylists', end: false, adminOnly: false },
{ to: '/history', key: 'nav.history', end: false, adminOnly: false },
{ to: '/import', key: 'nav.import', end: false, adminOnly: false },
{ to: '/friends', key: 'nav.friends', end: false, adminOnly: false, friends: true },
{ to: '/admin', key: 'nav.admin', end: false, adminOnly: true },

View file

@ -19,6 +19,7 @@
"friends": "Friends",
"admin": "Admin",
"settings": "Settings",
"history": "History",
"import": "Import",
"more": "More",
"tabs": "Tabs"
@ -840,6 +841,16 @@
"missing": "Artists you play on Spotify and have no music of here",
"missingMore": "and {{count}} more"
},
"history": {
"years": "Years",
"months": "Months of {{year}}",
"monthButton": "{{month}}: {{count}} plays",
"plays_one": "{{count}} listen",
"plays_other": "{{count}} listens",
"none": "You have no listens yet. What you play here, and what you import from Spotify, will be listed by year and month.",
"import": "Import your history from Spotify",
"noneMonth": "No listens in this month."
},
"import": {
"spotify": "Spotify",
"past": "Past imports",

View file

@ -19,6 +19,7 @@
"friends": "Amici",
"admin": "Admin",
"settings": "Impostazioni",
"history": "Cronologia",
"import": "Importa",
"more": "Altro",
"tabs": "Schede"
@ -840,6 +841,16 @@
"missing": "Artisti che ascolti su Spotify e di cui qui non hai musica",
"missingMore": "e altri {{count}}"
},
"history": {
"years": "Anni",
"months": "Mesi del {{year}}",
"monthButton": "{{month}}: {{count}} ascolti",
"plays_one": "{{count}} ascolto",
"plays_other": "{{count}} ascolti",
"none": "Non hai ancora ascolti. Quello che ascolti qui, e quello che importi da Spotify, sarà elencato per anno e mese.",
"import": "Importa la tua cronologia da Spotify",
"noneMonth": "Nessun ascolto in questo mese."
},
"import": {
"spotify": "Spotify",
"past": "Importazioni passate",

View file

@ -0,0 +1,151 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { render, screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter, useLocation } from 'react-router-dom'
import { beforeEach, expect, test, vi } from 'vitest'
import { initI18n } from '@/i18n'
import { apiError, mockFetch, type MockRoutes } from '@/test/mockFetch'
import HistoryPage from './HistoryPage'
beforeEach(async () => {
vi.spyOn(navigator, 'language', 'get').mockReturnValue('en-US')
await initI18n()
})
const months = [
{ year: 2026, month: 3, plays: 5 },
{ year: 2026, month: 1, plays: 2 },
{ year: 2025, month: 12, plays: 9 },
]
// Mid-month and mid-day, so the zone of the machine running the tests does not move a listen to another day.
const listen = (id: number, at: string, title: string, artists: [number, string][]) => ({
id,
track: { id: id + 100, title, artists: artists.map(([aid, name]) => ({ id: aid, name })) },
event_type: 'complete',
occurred_at: at,
duration_played_ms: 1000,
counted: true,
})
const march = [
listen(3, '2026-03-16T13:30:00Z', 'Karma Police', [[1, 'Radiohead']]),
listen(2, '2026-03-16T12:00:00Z', 'Debaser', [[2, 'Pixies'], [3, 'Frank Black']]),
listen(1, '2026-03-10T12:00:00Z', 'Song 2', [[4, 'Blur']]),
]
const page = (items: object[], total = items.length) => ({ items, total, limit: 100, offset: 0 })
function Where() {
const l = useLocation()
return <p data-testid="where">{l.pathname + l.search}</p>
}
function setup(routes: MockRoutes = {}, at = '/history') {
const mocked = mockFetch({
'GET /api/v1/listens/months': () => ({ months }),
'GET /api/v1/listens': () => page(march),
...routes,
})
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
render(
<QueryClientProvider client={client}>
<MemoryRouter initialEntries={[at]}>
<HistoryPage />
<Where />
</MemoryRouter>
</QueryClientProvider>,
)
return mocked
}
test('it opens on the latest month, with a button for each year and its listens a day at a time', async () => {
const { calls } = setup()
expect(screen.getByRole('heading', { level: 1, name: 'History' })).toBeInTheDocument()
const years = await screen.findByRole('group', { name: 'Years' })
expect(within(years).getByRole('button', { name: /2026/ })).toHaveAttribute('aria-pressed', 'true')
expect(within(years).getByRole('button', { name: /2026/ })).toHaveTextContent('7') // 5 + 2
expect(within(years).getByRole('button', { name: /2025/ })).toHaveAttribute('aria-pressed', 'false')
const month = await screen.findByRole('region', { name: 'March 2026' })
expect(within(month).getByText('5 listens')).toBeInTheDocument()
expect(await within(month).findByText('Karma Police')).toBeInTheDocument()
expect(within(month).getByRole('link', { name: 'Frank Black' })).toHaveAttribute('href', '/artists/3')
expect(within(month).getAllByRole('region').map((r) => r.getAttribute('aria-label'))).toEqual(['Monday, March 16, 2026', 'Tuesday, March 10, 2026'])
const asked = calls.find((c) => c.key === 'GET /api/v1/listens')!
expect(asked.url.searchParams.get('counted')).toBe('true')
expect(asked.url.searchParams.get('from')).toBe(new Date(2026, 2, 1).toISOString())
expect(asked.url.searchParams.get('until')).toBe(new Date(2026, 3, 1).toISOString())
const zone = calls.find((c) => c.key === 'GET /api/v1/listens/months')!
expect(zone.url.searchParams.get('tz')).toBe(Intl.DateTimeFormat().resolvedOptions().timeZone)
})
test('the months of the year are buttons, and one with no listens is off', async () => {
setup()
const group = await screen.findByRole('group', { name: 'Months of 2026' })
expect(within(group).getByRole('button', { name: 'Mar: 5 plays' })).toHaveAttribute('aria-pressed', 'true')
expect(within(group).getByRole('button', { name: 'Feb: 0 plays' })).toBeDisabled()
expect(within(group).getAllByRole('button')).toHaveLength(12)
})
test('choosing a month or a year changes the address and reads its listens', async () => {
const { calls } = setup({
'GET /api/v1/listens': ({ url }) => (url.searchParams.get('from') === new Date(2026, 0, 1).toISOString() ? page([listen(9, '2026-01-15T12:00:00Z', 'Nancy Boy', [[5, 'Placebo']])]) : page(march)),
})
await userEvent.click(await screen.findByRole('button', { name: 'Jan: 2 plays' }))
expect(screen.getByTestId('where')).toHaveTextContent('/history?year=2026&month=1')
expect(await screen.findByText('Nancy Boy')).toBeInTheDocument()
expect(calls.filter((c) => c.key === 'GET /api/v1/listens')).toHaveLength(2)
await userEvent.click(screen.getByRole('button', { name: /2025/ }))
expect(screen.getByTestId('where')).toHaveTextContent('/history?year=2025')
expect(await screen.findByRole('region', { name: 'December 2025' })).toBeInTheDocument()
})
test('the address says which year and month, and a bad one is ignored', async () => {
setup({}, '/history?year=2025&month=12')
expect(await screen.findByRole('region', { name: 'December 2025' })).toBeInTheDocument()
expect(screen.getByRole('button', { name: /2025/ })).toHaveAttribute('aria-pressed', 'true')
})
test('a year or month that does not exist falls back to the latest', async () => {
setup({}, '/history?year=1999&month=13')
expect(await screen.findByRole('region', { name: 'March 2026' })).toBeInTheDocument()
})
test('a month longer than a page has a button for the next one', async () => {
const { calls } = setup({
'GET /api/v1/listens': ({ url }) =>
url.searchParams.get('offset') === '0' ? { items: [march[0]], total: 2, limit: 100, offset: 0 } : { items: [march[1]], total: 2, limit: 100, offset: 1 },
})
await screen.findByText('Karma Police')
await userEvent.click(screen.getByRole('button', { name: 'Show more' }))
expect(await screen.findByText('Debaser')).toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Show more' })).not.toBeInTheDocument()
expect(calls.filter((c) => c.key === 'GET /api/v1/listens')).toHaveLength(2)
})
test('with no listens at all it says where they come from', async () => {
setup({ 'GET /api/v1/listens/months': () => ({ months: [] }) })
expect(await screen.findByText(/You have no listens yet/)).toBeInTheDocument()
expect(screen.getByRole('link', { name: 'Import your history from Spotify' })).toHaveAttribute('href', '/import')
})
test('a month that cannot be read has a way to try again', async () => {
let fail = true
setup({ 'GET /api/v1/listens': () => (fail ? apiError(500, 'internal', 'x') : page(march)) })
const retry = await screen.findByRole('button', { name: 'Try again' })
fail = false
await userEvent.click(retry)
expect(await screen.findByText('Karma Police')).toBeInTheDocument()
})
test('months that cannot be read have a way to try again', async () => {
let fail = true
setup({ 'GET /api/v1/listens/months': () => (fail ? apiError(500, 'internal', 'x') : { months }) })
const retry = await screen.findByRole('button', { name: 'Try again' })
fail = false
await userEvent.click(retry)
expect(await screen.findByRole('group', { name: 'Years' })).toBeInTheDocument()
})

View file

@ -0,0 +1,168 @@
import { useTranslation } from 'react-i18next'
import { Link, useSearchParams } from 'react-router-dom'
import { useListenMonths, useMonthListens, type ListenItem, type ListenMonth } from '@/api/history'
import PageTitle from '@/components/PageTitle'
import { EmptyMessage, ErrorMessage, Loading } from '@/components/Status'
import { Button } from '@/components/ui/button'
import { cn } from '@/lib/utils'
const number = (value: string | null) => {
const n = Number(value)
return Number.isInteger(n) && n > 0 ? n : null
}
/** One day of listens: the day in words, and each listen with its time, its song and its artists. */
function Day({ day, items }: { day: Date; items: ListenItem[] }) {
const { i18n } = useTranslation()
const date = new Intl.DateTimeFormat(i18n.language, { dateStyle: 'full' }).format(day)
const time = new Intl.DateTimeFormat(i18n.language, { timeStyle: 'short' })
return (
<section aria-label={date} className="flex flex-col gap-1">
<h3 className="text-lg font-bold">{date}</h3>
<ul>
{items.map((it) => (
<li key={it.id} className="flex flex-wrap items-baseline gap-x-4 border-b border-border/60 py-2">
<span className="w-20 shrink-0 text-sm whitespace-nowrap tabular-nums text-muted-foreground">{time.format(new Date(it.occurred_at))}</span>
<span className="min-w-40 flex-1 break-words font-semibold">{it.track.title}</span>
<span className="text-sm break-words text-muted-foreground">
{it.track.artists.map((a, i) => (
<span key={a.id}>
{i > 0 && ', '}
<Link to={`/artists/${a.id}`} className="hover:underline">
{a.name}
</Link>
</span>
))}
</span>
</li>
))}
</ul>
</section>
)
}
/** The listens of one month, a day at a time, with a button for the next page. */
function MonthList({ month }: { month: ListenMonth }) {
const { t } = useTranslation()
const list = useMonthListens(month)
if (list.isError) return <ErrorMessage error={list.error} onRetry={() => void list.refetch()} />
if (list.isPending) return <Loading />
if (list.data.items.length === 0) return <EmptyMessage>{t('history.noneMonth')}</EmptyMessage>
const days: { day: Date; items: ListenItem[] }[] = []
for (const it of list.data.items) {
const at = new Date(it.occurred_at)
const last = days[days.length - 1]
if (last && last.day.toDateString() === at.toDateString()) last.items.push(it)
else days.push({ day: at, items: [it] })
}
return (
<div className="flex flex-col gap-6">
{days.map((d) => (
<Day key={d.day.toDateString()} day={d.day} items={d.items} />
))}
{list.hasNextPage && (
<Button variant="outline" className="self-start" disabled={list.isFetchingNextPage} onClick={() => void list.fetchNextPage()}>
{t('common.showMore')}
</Button>
)}
</div>
)
}
/**
* What you listened to, by year and by month: a button for each year with its plays, the months of the chosen year
* as bars, and the listens of the chosen month a day at a time. The choice is in the address.
*/
export default function HistoryPage() {
const { t, i18n } = useTranslation()
const [params, setParams] = useSearchParams()
const months = useListenMonths()
const all = months.data ?? []
const years = [...new Set(all.map((m) => m.year))]
const year = years.includes(number(params.get('year')) ?? 0) ? (number(params.get('year')) as number) : years[0]
const ofYear = all.filter((m) => m.year === year)
const chosen = ofYear.find((m) => m.month === number(params.get('month'))) ?? ofYear[0] ?? null
const biggest = Math.max(1, ...ofYear.map((m) => m.plays))
const monthName = new Intl.DateTimeFormat(i18n.language, { month: 'short' })
const monthLong = new Intl.DateTimeFormat(i18n.language, { month: 'long', year: 'numeric' })
function choose(next: { year: number; month?: number }) {
setParams(next.month ? { year: String(next.year), month: String(next.month) } : { year: String(next.year) })
}
return (
<div className="flex flex-col gap-8">
<PageTitle>{t('nav.history')}</PageTitle>
{months.isError ? (
<ErrorMessage error={months.error} onRetry={() => void months.refetch()} />
) : months.isPending ? (
<Loading />
) : all.length === 0 ? (
<div className="flex max-w-xl flex-col gap-3">
<EmptyMessage>{t('history.none')}</EmptyMessage>
<Link to="/import" className="self-start font-semibold underline underline-offset-4">
{t('history.import')}
</Link>
</div>
) : (
<>
<div role="group" aria-label={t('history.years')} className="flex flex-wrap gap-2">
{years.map((y) => {
const total = all.filter((m) => m.year === y).reduce((sum, m) => sum + m.plays, 0)
return (
<Button key={y} variant={y === year ? 'default' : 'outline'} aria-pressed={y === year} onClick={() => choose({ year: y })}>
<span>{y}</span>
<span className="ml-2 text-sm font-normal tabular-nums opacity-80">{total}</span>
</Button>
)
})}
</div>
<div role="group" aria-label={t('history.months', { year })} className="grid grid-cols-6 gap-2 sm:grid-cols-12">
{Array.from({ length: 12 }, (_, i) => i + 1).map((m) => {
const found = ofYear.find((x) => x.month === m)
const plays = found?.plays ?? 0
const on = chosen?.month === m
return (
<button
key={m}
type="button"
disabled={!found}
aria-pressed={on}
aria-label={t('history.monthButton', { month: monthName.format(new Date(year, m - 1, 1)), count: plays })}
onClick={() => choose({ year, month: m })}
className={cn(
'flex min-h-28 flex-col items-center justify-end gap-1 rounded-md border px-1 pb-2 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring',
on ? 'border-primary bg-card' : 'border-border',
found ? 'hover:border-primary' : 'opacity-40',
)}
>
<span aria-hidden="true" className="text-xs tabular-nums text-muted-foreground">
{plays}
</span>
<span aria-hidden="true" className="w-full rounded-sm bg-primary" style={{ height: `${Math.max(plays > 0 ? 4 : 0, (plays / biggest) * 56)}px` }} />
<span aria-hidden="true" className="text-sm font-semibold">
{monthName.format(new Date(year, m - 1, 1))}
</span>
</button>
)
})}
</div>
{chosen && (
<section aria-label={monthLong.format(new Date(chosen.year, chosen.month - 1, 1))} className="flex flex-col gap-4">
<h2 className="text-2xl font-bold">
{monthLong.format(new Date(chosen.year, chosen.month - 1, 1))}
<span className="ml-3 text-base font-normal text-muted-foreground">{t('history.plays', { count: chosen.plays })}</span>
</h2>
<MonthList key={`${chosen.year}-${chosen.month}`} month={chosen} />
</section>
)}
</>
)}
</div>
)
}

View file

@ -34,6 +34,7 @@ export const routes: RouteObject[] = [
{ path: '/smart-playlists/suggested/:key', lazy: page(() => import('@/pages/SuggestedSmartPage')) },
{ path: '/smart-playlists/:id', lazy: page(() => import('@/pages/SmartPlaylistPage')) },
{ path: '/smart-playlists/:id/edit', lazy: page(() => import('@/pages/SmartEditorPage')) },
{ path: '/history', lazy: page(() => import('@/pages/HistoryPage')) },
{ path: '/import', lazy: page(() => import('@/pages/ImportPage')) },
{ path: '/settings', lazy: page(() => import('@/pages/SettingsPage')) },
{