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:
parent
9ce7beb42d
commit
9f63121028
20 changed files with 909 additions and 16 deletions
|
|
@ -29,6 +29,7 @@ It is a single executable, one database (SQLite by default, PostgreSQL if you pr
|
|||
- **Your own settings.** `GET` and `PATCH /me/settings` hold choices that belong to you, not to the server. Everyone starts private: `discover_from_listening` is off, so this setting never sends your listening to a provider. When you turn it on, Discover may start from the artists you listen to most, and their names are sent to Last.fm (only if an admin switched it on). What Last.fm answers is kept in the shared database like any other lookup, so another local user can see, from `retrieved_at` of `GET /artists/{id}/similar`, that someone looked up an artist, but not who.
|
||||
- **Importing from Spotify.** `POST /me/import/spotify` brings your listening history and your playlists from a Spotify data export into your own account. Ask Spotify for your data (Account, Privacy, "Extended streaming history" and "Account data") and send what it gives, as a multipart form with a `files` field for each file: the zip itself, or the JSON files in it (`Streaming_History_Audio_*.json`, the older `StreamingHistory_music_*.json` and `Playlist*.json`); a request may be up to 512 MB, and the rest of the export (the account, the searches, the library) is never opened. It all happens on your server and nothing is sent anywhere; the files are read from the request and not kept, and of each play only the song, the artist, the album, the time and how it ended are read, never the IP addresses, the country or the platform in the file. Of a play of a song you do not have that counts as listened, the name of the artist and the time are kept (and nothing else), so that Sonda can learn which artists you play together. A play is matched to a song of your library by artist and title (case, accents and punctuation do not matter, a `Remastered` note on either side does not, any credited artist will do, and a play of a compilation is matched by its album when Spotify says `Various Artists`). A match is recorded as a listen at the time of the play: `complete` when it ran to its end (or nine tenths were played), `skip` when Spotify says it was skipped or it lasted less than a listen, `play` otherwise; nothing is posted to Mastodon. Importing the same files again records nothing twice, and the same play in the extended and in the older history is one. A playlist becomes a playlist of yours with the songs that were found, in order; one whose name you already have is left alone, and one with none of its songs in your library is not made. The report counts what was added, what was already there and what is not in your library (and lists those artists, most played first), so you can see what is missing. One import of yours runs at a time. The report is kept: `GET /me/import/spotify` lists your past imports, newest first, with the numbers of each (never the files). The web app has an Import page for the form and for those numbers.
|
||||
- **Suggestions from your own listening.** `GET /me/suggestions` learns which artists you play together: your history is split into sittings (plays less than 30 minutes apart) and two artists that turn up in the same sitting often are linked (a cosine over the sittings of each). It is a count over your own data, built on your server in a moment and again when plays are added, with no provider and nothing sent anywhere; it needs `discover_from_listening` in `PATCH /me/settings`. The model reads your listening events and the plays of artists you have no music of that an import kept (the artist and the time only). `library` are artists you have that go with what you play and that you did not play for two months; `missing` are artists you played at least three times and have no music of, the ones you play most that also go with what you play now first. Each says which of your artists it goes with. `POST /me/suggestions/wishlist` puts an artist you played on your wishlist by name (it is made without music and without a MusicBrainz id: Sonda never looks one up by name, so it cannot be sent to Lidarr from here). The web app has a "From your listening" tab in Discover.
|
||||
- **Listening history by year and month.** `GET /listens/months` says how many listens that count you made in each calendar month, newest first, in the time zone you send as `tz` (UTC without it), and `GET /listens` takes `from` and `until` to read the listens of one of them; each listen now names its artists. The web app has a History page: a button for each year, the months of the year as bars, and the listens of the month a day at a time.
|
||||
- **Sharing on Mastodon.** `PUT /me/mastodon` connects your own Mastodon account (the address of your instance and an access token that can only write posts); `GET` shows which account is connected and `DELETE` forgets it and the token. Nothing is connected by default. Once it is, each track of this server that counts as a listen is posted to your account as an unlisted status with the title, artists, album and `#NowPlaying`, and no link: at most one post a minute, never music of a friend. The token stays on the server and is never sent back. If the instance refuses the token on a post (it was revoked or expired), `GET /me/mastodon` says `problem: token_refused`, Settings shows it, and nothing is posted until you connect again with a new token. The address of the instance must be a domain name on https, and the server never connects to a private, loopback or link-local address for it, never follows a redirect and ignores proxy settings.
|
||||
- **Tags.** `GET /artists/{id}/tags` shows what Last.fm and MusicBrainz say kind of music an artist plays, each with its own weights, and the genres of the artist's own files, read offline. See [External providers](#external-providers).
|
||||
- **Similar artists.** With Last.fm switched on, `GET /artists/{id}/similar` lists artists similar to an artist, and says which of them you already have. See [External providers](#external-providers). Without it, Sonda makes no outbound network requests at all.
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ import (
|
|||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
_ "time/tzdata" // the time zones that browsers send, also on a machine that has none
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.uber.org/zap"
|
||||
|
|
|
|||
|
|
@ -598,6 +598,13 @@ func TestResponsesMatchTheSpec(t *testing.T) {
|
|||
if onlyCounted["total"] != float64(1) {
|
||||
t.Fatalf("counted history = %v, want one", onlyCounted)
|
||||
}
|
||||
c.expect(c.call("GET", "/listens?from=2000-01-01T00:00:00Z&until=2100-01-01T00:00:00Z", token, nil), 200, "history of a range")
|
||||
c.expect(c.call("GET", "/listens?from=never", token, nil), 400, "history of a bad range", "invalid_input")
|
||||
listenMonths := c.expect(c.call("GET", "/listens/months", token, nil), 200, "listening months")
|
||||
if months, _ := listenMonths["months"].([]any); len(months) != 1 {
|
||||
c.t.Fatalf("months = %v, want the month of the one event that counts", listenMonths)
|
||||
}
|
||||
c.expect(c.call("GET", "/listens/months", "", nil), 401, "months without token", "unauthorized")
|
||||
c.expect(c.call("GET", "/listens", "", nil), 401, "history without token", "unauthorized")
|
||||
c.expect(c.call("GET", "/listens?counted=maybe", token, nil), 400, "history bad filter", "invalid_input")
|
||||
c.expect(c.call("POST", "/listens", token, map[string]any{"track_id": 999, "event_type": "play", "idempotency_key": "k2"}), 404, "listen unknown track", "track_not_found")
|
||||
|
|
|
|||
|
|
@ -77,13 +77,19 @@ func (h *listenHandlers) record(c *gin.Context) {
|
|||
}
|
||||
}
|
||||
|
||||
type listenTrackJSON struct {
|
||||
ID int64 `json:"id"`
|
||||
Title string `json:"title"`
|
||||
Artists []artistRefJSON `json:"artists"`
|
||||
}
|
||||
|
||||
type listenItemJSON struct {
|
||||
ID int64 `json:"id"`
|
||||
Track albumRefJSON `json:"track"`
|
||||
EventType string `json:"event_type"`
|
||||
OccurredAt string `json:"occurred_at"`
|
||||
DurationPlayedMs int64 `json:"duration_played_ms"`
|
||||
Counted bool `json:"counted"`
|
||||
ID int64 `json:"id"`
|
||||
Track listenTrackJSON `json:"track"`
|
||||
EventType string `json:"event_type"`
|
||||
OccurredAt string `json:"occurred_at"`
|
||||
DurationPlayedMs int64 `json:"duration_played_ms"`
|
||||
Counted bool `json:"counted"`
|
||||
}
|
||||
|
||||
// list returns the signed-in user's own listening history, newest first.
|
||||
|
|
@ -97,6 +103,16 @@ func (h *listenHandlers) list(c *gin.Context) {
|
|||
return
|
||||
}
|
||||
f := listening.Filter{Limit: clampInt(limit), Offset: clampInt(offset)}
|
||||
for name, into := range map[string]*time.Time{"from": &f.From, "until": &f.Until} {
|
||||
if raw := c.Query(name); raw != "" {
|
||||
t, err := time.Parse(time.RFC3339, raw)
|
||||
if err != nil {
|
||||
writeError(c, http.StatusBadRequest, "invalid_input", name+" must be a date and time like 2025-03-01T00:00:00Z")
|
||||
return
|
||||
}
|
||||
*into = t
|
||||
}
|
||||
}
|
||||
switch c.Query("counted") {
|
||||
case "":
|
||||
case "true":
|
||||
|
|
@ -121,7 +137,7 @@ func (h *listenHandlers) list(c *gin.Context) {
|
|||
for i, it := range page.Items {
|
||||
items[i] = listenItemJSON{
|
||||
ID: it.ID,
|
||||
Track: albumRefJSON{ID: it.TrackID, Title: it.TrackTitle},
|
||||
Track: listenTrackJSON{ID: it.TrackID, Title: it.TrackTitle, Artists: artistRefs(it.Artists)},
|
||||
EventType: string(it.Type),
|
||||
OccurredAt: it.OccurredAt.UTC().Format(time.RFC3339),
|
||||
DurationPlayedMs: it.DurationPlayedMs,
|
||||
|
|
@ -130,3 +146,34 @@ func (h *listenHandlers) list(c *gin.Context) {
|
|||
}
|
||||
c.JSON(http.StatusOK, gin.H{"items": items, "total": page.Total, "limit": page.Limit, "offset": page.Offset})
|
||||
}
|
||||
|
||||
func artistRefs(in []listening.Artist) []artistRefJSON {
|
||||
out := make([]artistRefJSON, 0, len(in))
|
||||
for _, a := range in {
|
||||
out = append(out, artistRefJSON{ID: a.ID, Name: a.Name})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// months says how many listens the signed-in person made in each month, newest first.
|
||||
func (h *listenHandlers) months(c *gin.Context) {
|
||||
loc := time.UTC
|
||||
if name := c.Query("tz"); name != "" {
|
||||
var err error
|
||||
if loc, err = time.LoadLocation(name); err != nil {
|
||||
writeError(c, http.StatusBadRequest, "invalid_input", "tz must be a time zone like Europe/Rome")
|
||||
return
|
||||
}
|
||||
}
|
||||
got, err := h.svc.Months(c.Request.Context(), currentUserID(c), loc)
|
||||
if err != nil {
|
||||
_ = c.Error(err)
|
||||
writeError(c, http.StatusInternalServerError, "internal", "internal error")
|
||||
return
|
||||
}
|
||||
out := make([]gin.H, 0, len(got))
|
||||
for _, m := range got {
|
||||
out = append(out, gin.H{"year": m.Year, "month": m.Month, "plays": m.Plays})
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"months": out})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -102,7 +102,7 @@ func TestListeningHistory(t *testing.T) {
|
|||
items := r.Body["items"].([]any)
|
||||
first := items[0].(map[string]any)
|
||||
sameKeys(t, "item", first, "id", "track", "event_type", "occurred_at", "duration_played_ms", "counted")
|
||||
sameKeys(t, "item.track", first["track"].(map[string]any), "id", "title")
|
||||
sameKeys(t, "item.track", first["track"].(map[string]any), "id", "title", "artists")
|
||||
if first["event_type"] != "complete" || first["occurred_at"] != "2026-01-01T12:00:00Z" ||
|
||||
first["counted"] != true || first["track"].(map[string]any)["title"] != "Hundred seconds" {
|
||||
t.Errorf("newest event = %v", first)
|
||||
|
|
@ -153,3 +153,72 @@ func TestListeningHistoryRejectsBadParameters(t *testing.T) {
|
|||
t.Errorf("limit=9999: %v, want it lowered to 200", r.Body["limit"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestListeningHistoryCanBeReadForAMonth(t *testing.T) {
|
||||
f := newListenFixture(t)
|
||||
f.listen(t, f.admin, ev(1, "complete", 1_000, "dec", "2025-12-31T23:59:59Z"))
|
||||
f.listen(t, f.admin, ev(1, "complete", 1_000, "jan1", "2026-01-01T00:00:00Z"))
|
||||
f.listen(t, f.admin, ev(2, "complete", 1_000, "jan2", "2026-01-31T23:59:59Z"))
|
||||
f.listen(t, f.admin, ev(1, "complete", 1_000, "feb", "2026-02-01T00:00:00Z"))
|
||||
|
||||
r := do(t, f.h, "GET", "/api/v1/listens?from=2026-01-01T00:00:00Z&until=2026-02-01T00:00:00Z", f.admin, nil)
|
||||
if r.Code != http.StatusOK || r.Body["total"] != float64(2) {
|
||||
t.Fatalf("January: %d %v, want its two", r.Code, r.Body)
|
||||
}
|
||||
items := r.Body["items"].([]any)
|
||||
if items[0].(map[string]any)["occurred_at"] != "2026-01-31T23:59:59Z" || items[1].(map[string]any)["occurred_at"] != "2026-01-01T00:00:00Z" {
|
||||
t.Errorf("January = %v, want the 31st then the 1st", items)
|
||||
}
|
||||
if r := do(t, f.h, "GET", "/api/v1/listens?from=2026-02-01T00:00:00Z", f.admin, nil); r.Body["total"] != float64(1) {
|
||||
t.Errorf("from February: %v, want 1", r.Body["total"])
|
||||
}
|
||||
for _, q := range []string{"from=yesterday", "until=2026-13-01", "from=2026-02-01T00:00:00Z&until=2026-01-01T00:00:00Z", "from=2026-01-01T00:00:00Z&until=2026-01-01T00:00:00Z"} {
|
||||
if r := do(t, f.h, "GET", "/api/v1/listens?"+q, f.admin, nil); r.Code != http.StatusBadRequest || errCode(r) != "invalid_input" {
|
||||
t.Errorf("?%s: %d %v, want 400 invalid_input", q, r.Code, r.Body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestListeningMonthsCountWhatCountsNewestFirstAndOnlyMine(t *testing.T) {
|
||||
f := newListenFixture(t)
|
||||
f.listen(t, f.admin, ev(1, "complete", 1_000, "a", "2025-12-31T23:59:59Z"))
|
||||
f.listen(t, f.admin, ev(1, "play", 25_000, "b", "2026-01-05T10:00:00Z"))
|
||||
f.listen(t, f.admin, ev(1, "play", 5_000, "c", "2026-01-06T10:00:00Z")) // too short
|
||||
f.listen(t, f.admin, ev(2, "complete", 1_000, "d", "2026-01-07T10:00:00Z"))
|
||||
f.listen(t, f.bob, ev(2, "complete", 1_000, "e", "2026-03-07T10:00:00Z"))
|
||||
|
||||
r := do(t, f.h, "GET", "/api/v1/listens/months", f.admin, nil)
|
||||
if r.Code != http.StatusOK {
|
||||
t.Fatalf("months: %d %v", r.Code, r.Body)
|
||||
}
|
||||
sameKeys(t, "months", r.Body, "months")
|
||||
months := r.Body["months"].([]any)
|
||||
if len(months) != 2 {
|
||||
t.Fatalf("months = %v, want two", months)
|
||||
}
|
||||
sameKeys(t, "month", months[0].(map[string]any), "year", "month", "plays")
|
||||
jan, dec := months[0].(map[string]any), months[1].(map[string]any)
|
||||
if jan["year"] != 2026.0 || jan["month"] != 1.0 || jan["plays"] != 2.0 || dec["year"] != 2025.0 || dec["month"] != 12.0 || dec["plays"] != 1.0 {
|
||||
t.Errorf("months = %v, want January 2026 with 2 and December 2025 with 1", months)
|
||||
}
|
||||
if r := do(t, f.h, "GET", "/api/v1/listens/months", "", nil); r.Code != http.StatusUnauthorized {
|
||||
t.Errorf("without a token: %d, want 401", r.Code)
|
||||
}
|
||||
empty := do(t, f.h, "GET", "/api/v1/listens/months", f.bob, nil)
|
||||
if got := empty.Body["months"].([]any); len(got) != 1 {
|
||||
t.Errorf("bob's months = %v, want his one", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListeningMonthsStartWhereTheTimeZoneSays(t *testing.T) {
|
||||
f := newListenFixture(t)
|
||||
f.listen(t, f.admin, ev(1, "complete", 1_000, "a", "2025-12-31T23:30:00Z")) // already January in Rome
|
||||
r := do(t, f.h, "GET", "/api/v1/listens/months?tz=Europe/Rome", f.admin, nil)
|
||||
months := r.Body["months"].([]any)
|
||||
if r.Code != http.StatusOK || len(months) != 1 || months[0].(map[string]any)["month"] != 1.0 || months[0].(map[string]any)["year"] != 2026.0 {
|
||||
t.Errorf("in Rome: %d %v, want January 2026", r.Code, r.Body)
|
||||
}
|
||||
if r := do(t, f.h, "GET", "/api/v1/listens/months?tz=Mars/Olympus", f.admin, nil); r.Code != http.StatusBadRequest || errCode(r) != "invalid_input" {
|
||||
t.Errorf("an unknown zone: %d %v, want 400 invalid_input", r.Code, r.Body)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ import (
|
|||
"net/http"
|
||||
"reflect"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.uber.org/zap"
|
||||
|
|
@ -60,6 +61,7 @@ type tokenParser interface {
|
|||
type listenService interface {
|
||||
Record(ctx context.Context, e listening.Event) (listening.Result, error)
|
||||
List(ctx context.Context, userID int64, f listening.Filter) (listening.Page, error)
|
||||
Months(ctx context.Context, userID int64, loc *time.Location) ([]listening.Month, error)
|
||||
}
|
||||
|
||||
type streamService interface {
|
||||
|
|
@ -307,6 +309,7 @@ func NewRouter(d Deps) *gin.Engine {
|
|||
l := &listenHandlers{svc: d.Listening, announce: d.Mastodon}
|
||||
protected.POST("/listens", l.record)
|
||||
protected.GET("/listens", l.list)
|
||||
protected.GET("/listens/months", l.months)
|
||||
|
||||
sg := &listeningSuggestionHandlers{svc: d.Suggestions}
|
||||
protected.GET("/me/suggestions", sg.list)
|
||||
|
|
|
|||
|
|
@ -3164,6 +3164,44 @@ paths:
|
|||
application/json:
|
||||
schema: {$ref: '#/components/schemas/Error'}
|
||||
|
||||
/listens/months:
|
||||
get:
|
||||
tags: [Playback]
|
||||
operationId: listListenMonths
|
||||
summary: 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.
|
||||
security: [{bearerAuth: []}]
|
||||
parameters:
|
||||
- name: tz
|
||||
in: query
|
||||
description: An IANA time zone name, like `Europe/Rome`. Anything else is `invalid_input`.
|
||||
schema: {type: string, default: UTC}
|
||||
responses:
|
||||
'200':
|
||||
description: The months.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
additionalProperties: false
|
||||
required: [months]
|
||||
properties:
|
||||
months:
|
||||
type: array
|
||||
items:
|
||||
type: object
|
||||
additionalProperties: false
|
||||
required: [year, month, plays]
|
||||
properties:
|
||||
year: {type: integer}
|
||||
month: {type: integer, minimum: 1, maximum: 12}
|
||||
plays: {type: integer}
|
||||
'401': {$ref: '#/components/responses/Unauthorized'}
|
||||
|
||||
/listens:
|
||||
get:
|
||||
tags: [Playback]
|
||||
|
|
@ -3180,6 +3218,14 @@ paths:
|
|||
in: query
|
||||
description: Send `true` to list only the events that count as a listen.
|
||||
schema: {type: boolean, enum: [true]}
|
||||
- name: from
|
||||
in: query
|
||||
description: Only the events from this moment (included), like `2025-03-01T00:00:00Z`.
|
||||
schema: {type: string, format: date-time}
|
||||
- name: until
|
||||
in: query
|
||||
description: Only the events before this moment (excluded). It must be after `from` when both are sent (`invalid_input`).
|
||||
schema: {type: string, format: date-time}
|
||||
responses:
|
||||
'200':
|
||||
description: A page of events.
|
||||
|
|
@ -4937,10 +4983,20 @@ components:
|
|||
track:
|
||||
type: object
|
||||
additionalProperties: false
|
||||
required: [id, title]
|
||||
required: [id, title, artists]
|
||||
properties:
|
||||
id: {type: integer, format: int64}
|
||||
title: {type: string}
|
||||
artists:
|
||||
type: array
|
||||
description: The artists credited on the track, the main ones first.
|
||||
items:
|
||||
type: object
|
||||
additionalProperties: false
|
||||
required: [id, name]
|
||||
properties:
|
||||
id: {type: integer, format: int64}
|
||||
name: {type: string}
|
||||
event_type: {type: string, enum: [play, complete, skip]}
|
||||
occurred_at: {type: string, format: date-time}
|
||||
duration_played_ms: {type: integer, format: int64}
|
||||
|
|
|
|||
|
|
@ -63,11 +63,18 @@ type Result struct {
|
|||
Counted bool // whether the event counts as a listen
|
||||
}
|
||||
|
||||
// Artist is an artist credited on a track.
|
||||
type Artist struct {
|
||||
ID int64
|
||||
Name string
|
||||
}
|
||||
|
||||
// Record is a stored event, as read back for the history.
|
||||
type Record struct {
|
||||
ID int64
|
||||
TrackID int64
|
||||
TrackTitle string
|
||||
Artists []Artist
|
||||
Type EventType
|
||||
OccurredAt time.Time
|
||||
DurationPlayedMs int64
|
||||
|
|
@ -79,11 +86,19 @@ type Item struct {
|
|||
Counted bool
|
||||
}
|
||||
|
||||
// Filter pages the history. Zero Limit means the default.
|
||||
// Filter pages the history. Zero Limit means the default. From and Until, when set, keep the events from From
|
||||
// (included) to Until (excluded).
|
||||
type Filter struct {
|
||||
Limit int
|
||||
Offset int
|
||||
OnlyCounted bool
|
||||
From, Until time.Time
|
||||
}
|
||||
|
||||
// Month is how many listens a person made in a month.
|
||||
type Month struct {
|
||||
Year, Month int
|
||||
Plays int
|
||||
}
|
||||
|
||||
// Page is one page of the history and the size of the whole result.
|
||||
|
|
@ -101,6 +116,7 @@ type ListQuery struct {
|
|||
Offset int
|
||||
OnlyCounted bool
|
||||
MinPlayedMs int64 // threshold for OnlyCounted
|
||||
From, Until time.Time
|
||||
}
|
||||
|
||||
// Store persists and reads events.
|
||||
|
|
@ -118,6 +134,9 @@ type Store interface {
|
|||
// total. With OnlyCounted it keeps `complete` events and those played for
|
||||
// at least MinPlayedMs.
|
||||
ListEvents(ctx context.Context, q ListQuery) ([]Record, int, error)
|
||||
// Months counts the listens of a user (complete events and those played for at least MinPlayedMs) in each
|
||||
// calendar month of loc, newest month first. A month without listens is not in the list.
|
||||
Months(ctx context.Context, userID int64, minPlayedMs int64, loc *time.Location) ([]Month, error)
|
||||
}
|
||||
|
||||
// Service validates and records events and reads the history.
|
||||
|
|
@ -196,10 +215,13 @@ func (s *Service) List(ctx context.Context, userID int64, f Filter) (Page, error
|
|||
case f.Limit > MaxLimit:
|
||||
f.Limit = MaxLimit
|
||||
}
|
||||
if !f.From.IsZero() && !f.Until.IsZero() && !f.Until.After(f.From) {
|
||||
return Page{}, fmt.Errorf("%w: until must be after from", ErrInvalidQuery)
|
||||
}
|
||||
|
||||
records, total, err := s.store.ListEvents(ctx, ListQuery{
|
||||
UserID: userID, Limit: f.Limit, Offset: f.Offset,
|
||||
OnlyCounted: f.OnlyCounted, MinPlayedMs: s.minListen.Milliseconds(),
|
||||
OnlyCounted: f.OnlyCounted, MinPlayedMs: s.minListen.Milliseconds(), From: f.From, Until: f.Until,
|
||||
})
|
||||
if err != nil {
|
||||
return Page{}, err
|
||||
|
|
@ -210,3 +232,11 @@ func (s *Service) List(ctx context.Context, userID int64, f Filter) (Page, error
|
|||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
// Months counts the listens of a user in each month of the time zone, newest first. A nil zone is UTC.
|
||||
func (s *Service) Months(ctx context.Context, userID int64, loc *time.Location) ([]Month, error) {
|
||||
if loc == nil {
|
||||
loc = time.UTC
|
||||
}
|
||||
return s.store.Months(ctx, userID, s.minListen.Milliseconds(), loc)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -19,9 +19,12 @@ type fakeStore struct {
|
|||
|
||||
userGone bool
|
||||
|
||||
records []Record
|
||||
total int
|
||||
lastQ ListQuery
|
||||
records []Record
|
||||
total int
|
||||
lastQ ListQuery
|
||||
months []Month
|
||||
monthsMin int64
|
||||
monthsLoc *time.Location
|
||||
}
|
||||
|
||||
func (f *fakeStore) Record(_ context.Context, e Event) (bool, error) {
|
||||
|
|
@ -41,6 +44,11 @@ func (f *fakeStore) ListEvents(_ context.Context, q ListQuery) ([]Record, int, e
|
|||
return f.records, f.total, f.err
|
||||
}
|
||||
|
||||
func (f *fakeStore) Months(_ context.Context, _ int64, minPlayedMs int64, loc *time.Location) ([]Month, error) {
|
||||
f.monthsMin, f.monthsLoc = minPlayedMs, loc
|
||||
return f.months, f.err
|
||||
}
|
||||
|
||||
const minListen = 20 * time.Second
|
||||
|
||||
func newSvc(store *fakeStore) *Service { return NewService(store, minListen) }
|
||||
|
|
@ -302,3 +310,44 @@ func TestADeletedAccountIsReportedBeforeAnythingElse(t *testing.T) {
|
|||
t.Fatalf("an implausible duration from a deleted account: err = %v, want ErrUserNotFound", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListPassesTheRangeAndRefusesOneThatIsBackwards(t *testing.T) {
|
||||
store := &fakeStore{}
|
||||
svc := newSvc(store)
|
||||
from := time.Date(2025, 3, 1, 0, 0, 0, 0, time.UTC)
|
||||
until := time.Date(2025, 4, 1, 0, 0, 0, 0, time.UTC)
|
||||
if _, err := svc.List(context.Background(), 1, Filter{From: from, Until: until}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !store.lastQ.From.Equal(from) || !store.lastQ.Until.Equal(until) {
|
||||
t.Errorf("query = %+v, want the range passed on", store.lastQ)
|
||||
}
|
||||
if _, err := svc.List(context.Background(), 1, Filter{From: until, Until: from}); !errors.Is(err, ErrInvalidQuery) {
|
||||
t.Errorf("a backwards range: %v, want ErrInvalidQuery", err)
|
||||
}
|
||||
if _, err := svc.List(context.Background(), 1, Filter{From: from, Until: from}); !errors.Is(err, ErrInvalidQuery) {
|
||||
t.Errorf("an empty range: %v, want ErrInvalidQuery", err)
|
||||
}
|
||||
if _, err := svc.List(context.Background(), 1, Filter{From: from}); err != nil {
|
||||
t.Errorf("only a start: %v, want it accepted", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMonthsUseTheMinimumListenOfTheRule(t *testing.T) {
|
||||
store := &fakeStore{months: []Month{{Year: 2025, Month: 3, Plays: 4}}}
|
||||
got, err := newSvc(store).Months(context.Background(), 1, nil)
|
||||
if err != nil || len(got) != 1 || got[0].Plays != 4 {
|
||||
t.Fatalf("Months = %+v, %v", got, err)
|
||||
}
|
||||
if store.monthsLoc != time.UTC {
|
||||
t.Errorf("zone = %v, want UTC when none is given", store.monthsLoc)
|
||||
}
|
||||
rome, _ := time.LoadLocation("Europe/Rome")
|
||||
_, _ = newSvc(store).Months(context.Background(), 1, rome)
|
||||
if store.monthsLoc != rome {
|
||||
t.Errorf("zone = %v, want Europe/Rome passed on", store.monthsLoc)
|
||||
}
|
||||
if store.monthsMin != minListen.Milliseconds() {
|
||||
t.Errorf("minimum = %d ms, want %d", store.monthsMin, minListen.Milliseconds())
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import (
|
|||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"github.com/uptrace/bun"
|
||||
|
|
@ -137,6 +138,14 @@ func (r *ListeningRepo) ListEvents(ctx context.Context, q listening.ListQuery) (
|
|||
where += " AND (e.event_type = 'complete' OR e.duration_played_ms >= ?)"
|
||||
args = append(args, q.MinPlayedMs)
|
||||
}
|
||||
if !q.From.IsZero() {
|
||||
where += " AND e.occurred_at >= ?"
|
||||
args = append(args, q.From.Unix())
|
||||
}
|
||||
if !q.Until.IsZero() {
|
||||
where += " AND e.occurred_at < ?"
|
||||
args = append(args, q.Until.Unix())
|
||||
}
|
||||
|
||||
var total int
|
||||
if err := r.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM listening_events e WHERE "+where, args...).Scan(&total); err != nil {
|
||||
|
|
@ -168,7 +177,84 @@ func (r *ListeningRepo) ListEvents(ctx context.Context, q listening.ListQuery) (
|
|||
rec.Type, rec.OccurredAt = listening.EventType(typ), time.Unix(at, 0)
|
||||
records = append(records, rec)
|
||||
}
|
||||
return records, total, rows.Err()
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
if err := r.addArtists(ctx, records); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
return records, total, nil
|
||||
}
|
||||
|
||||
// addArtists puts the credited artists on each record, in the order they were credited (the main ones first).
|
||||
func (r *ListeningRepo) addArtists(ctx context.Context, records []listening.Record) error {
|
||||
if len(records) == 0 {
|
||||
return nil
|
||||
}
|
||||
ids := make([]int64, 0, len(records))
|
||||
for _, rec := range records {
|
||||
ids = append(ids, rec.TrackID)
|
||||
}
|
||||
rows, err := r.db.QueryContext(ctx,
|
||||
`SELECT ta.track_id, a.id, a.name FROM track_artists ta JOIN artists a ON a.id = ta.artist_id
|
||||
WHERE ta.track_id IN (?) ORDER BY ta.track_id, CASE ta.role WHEN 'main' THEN 0 ELSE 1 END, a.id`, bun.In(ids))
|
||||
if err != nil {
|
||||
return fmt.Errorf("read artists of the listens: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
byTrack := map[int64][]listening.Artist{}
|
||||
for rows.Next() {
|
||||
var (
|
||||
track int64
|
||||
a listening.Artist
|
||||
)
|
||||
if err := rows.Scan(&track, &a.ID, &a.Name); err != nil {
|
||||
return err
|
||||
}
|
||||
byTrack[track] = append(byTrack[track], a)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
for i := range records {
|
||||
records[i].Artists = byTrack[records[i].TrackID]
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Months counts the listens of a user in each calendar month of loc, newest first: complete events and plays of at
|
||||
// least minPlayedMs. The moments are read and counted here, so that SQLite and PostgreSQL give the same months.
|
||||
func (r *ListeningRepo) Months(ctx context.Context, userID int64, minPlayedMs int64, loc *time.Location) ([]listening.Month, error) {
|
||||
rows, err := r.db.QueryContext(ctx,
|
||||
"SELECT e.occurred_at FROM listening_events e WHERE e.user_id = ? AND "+counted, userID, minPlayedMs)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read listens: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
type ym struct{ y, m int }
|
||||
plays := map[ym]int{}
|
||||
for rows.Next() {
|
||||
var at int64
|
||||
if err := rows.Scan(&at); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
t := time.Unix(at, 0).In(loc)
|
||||
plays[ym{t.Year(), int(t.Month())}]++
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]listening.Month, 0, len(plays))
|
||||
for k, n := range plays {
|
||||
out = append(out, listening.Month{Year: k.y, Month: k.m, Plays: n})
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool {
|
||||
if out[i].Year != out[j].Year {
|
||||
return out[i].Year > out[j].Year
|
||||
}
|
||||
return out[i].Month > out[j].Month
|
||||
})
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// UserExists reports whether the account is still there.
|
||||
|
|
|
|||
107
internal/storage/listening_history_test.go
Normal file
107
internal/storage/listening_history_test.go
Normal file
|
|
@ -0,0 +1,107 @@
|
|||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/uptrace/bun"
|
||||
|
||||
"codeberg.org/squidd/sonda/internal/listening"
|
||||
)
|
||||
|
||||
func TestTheHistoryCanBeReadForARangeAndNamesTheArtists(t *testing.T) {
|
||||
forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) {
|
||||
ctx := context.Background()
|
||||
u, err := NewUserRepo(db).CreateUser(ctx, "alice", "h", false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
lib, err := NewLibraryRepo(db).CreateLibrary(ctx, "music", "/music")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pixies := affinitySong(t, db, lib.ID, "a.flac", "Debaser", "Pixies")
|
||||
repo := NewListeningRepo(db)
|
||||
day := func(y int, m time.Month, d int) time.Time { return time.Date(y, m, d, 12, 0, 0, 0, time.UTC) }
|
||||
for i, at := range []time.Time{day(2024, 12, 31), day(2025, 1, 1), day(2025, 1, 31), day(2025, 2, 1)} {
|
||||
if _, err := repo.Record(ctx, listening.Event{UserID: u.ID, TrackID: pixies, Type: listening.Complete, OccurredAt: at, DurationPlayedMs: 1000, IdempotencyKey: string(rune('a' + i))}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
jan := listening.ListQuery{UserID: u.ID, Limit: 50, From: time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC), Until: time.Date(2025, 2, 1, 0, 0, 0, 0, time.UTC)}
|
||||
got, total, err := repo.ListEvents(ctx, jan)
|
||||
if err != nil || total != 2 || len(got) != 2 {
|
||||
t.Fatalf("January = %d events, total %d, %v, want 2: the 1st and the 31st, not the day before or after", len(got), total, err)
|
||||
}
|
||||
if !got[0].OccurredAt.Equal(day(2025, 1, 31)) || !got[1].OccurredAt.Equal(day(2025, 1, 1)) {
|
||||
t.Errorf("order = %v, %v, want newest first", got[0].OccurredAt, got[1].OccurredAt)
|
||||
}
|
||||
if len(got[0].Artists) != 1 || got[0].Artists[0].Name != "Pixies" || got[0].Artists[0].ID == 0 {
|
||||
t.Errorf("artists = %+v, want Pixies", got[0].Artists)
|
||||
}
|
||||
from := listening.ListQuery{UserID: u.ID, Limit: 50, From: time.Date(2025, 2, 1, 0, 0, 0, 0, time.UTC)}
|
||||
if _, total, _ := repo.ListEvents(ctx, from); total != 1 {
|
||||
t.Errorf("from February = %d, want 1", total)
|
||||
}
|
||||
until := listening.ListQuery{UserID: u.ID, Limit: 50, Until: time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC)}
|
||||
if _, total, _ := repo.ListEvents(ctx, until); total != 1 {
|
||||
t.Errorf("until January = %d, want 1", total)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestMonthsCountTheListensThatCountNewestFirst(t *testing.T) {
|
||||
forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) {
|
||||
ctx := context.Background()
|
||||
users := NewUserRepo(db)
|
||||
u, err := users.CreateUser(ctx, "alice", "h", false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
other, err := users.CreateUser(ctx, "bob", "h", false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
lib, err := NewLibraryRepo(db).CreateLibrary(ctx, "music", "/music")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
track := affinitySong(t, db, lib.ID, "a.flac", "Debaser", "Pixies")
|
||||
repo := NewListeningRepo(db)
|
||||
at := func(y int, m time.Month, d int) time.Time { return time.Date(y, m, d, 23, 30, 0, 0, time.UTC) }
|
||||
rec := func(user int64, typ listening.EventType, ms int64, when time.Time, key string) {
|
||||
if _, err := repo.Record(ctx, listening.Event{UserID: user, TrackID: track, Type: typ, OccurredAt: when, DurationPlayedMs: ms, IdempotencyKey: key}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
rec(u.ID, listening.Complete, 1000, at(2024, 12, 31), "1") // the last evening of the year, UTC
|
||||
rec(u.ID, listening.Complete, 1000, at(2025, 1, 1), "2")
|
||||
rec(u.ID, listening.Play, 30_000, at(2025, 1, 15), "3") // long enough
|
||||
rec(u.ID, listening.Play, 5_000, at(2025, 1, 16), "4") // too short
|
||||
rec(u.ID, listening.Skip, 1_000, at(2025, 1, 17), "5") // a skip
|
||||
rec(other.ID, listening.Complete, 1000, at(2025, 3, 1), "6")
|
||||
|
||||
got, err := repo.Months(ctx, u.ID, 20_000, time.UTC)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := []listening.Month{{Year: 2025, Month: 1, Plays: 2}, {Year: 2024, Month: 12, Plays: 1}}
|
||||
if len(got) != len(want) || got[0] != want[0] || got[1] != want[1] {
|
||||
t.Errorf("Months = %+v, want %+v", got, want)
|
||||
}
|
||||
// In Rome the last evening of the year, UTC, is already January.
|
||||
rome, err := time.LoadLocation("Europe/Rome")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
inRome, err := repo.Months(ctx, u.ID, 20_000, rome)
|
||||
if err != nil || len(inRome) != 1 || inRome[0] != (listening.Month{Year: 2025, Month: 1, Plays: 3}) {
|
||||
t.Errorf("Months in Rome = %+v, %v, want January 2025 with the three", inRome, err)
|
||||
}
|
||||
if none, err := repo.Months(ctx, 999999, 20_000, time.UTC); err != nil || len(none) != 0 {
|
||||
t.Errorf("a person with no listens: %+v, %v", none, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
31
web/src/api/history.ts
Normal file
31
web/src/api/history.ts
Normal 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 },
|
||||
)
|
||||
}
|
||||
63
web/src/api/schema.d.ts
vendored
63
web/src/api/schema.d.ts
vendored
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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')
|
||||
|
|
|
|||
|
|
@ -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 },
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
|
|||
151
web/src/pages/HistoryPage.test.tsx
Normal file
151
web/src/pages/HistoryPage.test.tsx
Normal 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()
|
||||
})
|
||||
168
web/src/pages/HistoryPage.tsx
Normal file
168
web/src/pages/HistoryPage.tsx
Normal 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>
|
||||
)
|
||||
}
|
||||
|
|
@ -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')) },
|
||||
{
|
||||
|
|
|
|||
Loading…
Reference in a new issue