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

View file

@ -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")

View file

@ -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})
}

View file

@ -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)
}
}

View file

@ -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)

View file

@ -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}

View file

@ -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)
}

View file

@ -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())
}
}

View file

@ -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.

View 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)
}
})
}