sonda/internal/api/http/handlers_stats.go
tgiachi 08c83c948f feat: how the genres I listen to changed over time
- GET /stats/listening has genre_timeline: the share of the five biggest genres, of the smaller ones and of the songs with no genre, for each year, or for each month when all the listens are in one year, in the listener's time zone; years and months with no listen are empty
- web: a stacked column chart on the Statistics page, coloured in tints of the colour of this server so it follows every theme, with a legend; left out when there is only one column
- README: the new field
2026-11-15 18:17:33 +01:00

157 lines
5.1 KiB
Go

package httpapi
import (
"context"
"errors"
"net/http"
"time"
"github.com/gin-gonic/gin"
"git.kmalloc.org/squid/sonda/internal/stats"
)
type statsService interface {
Library(ctx context.Context) (stats.Library, error)
Listening(ctx context.Context, userID int64, r stats.Range, loc *time.Location) (stats.Listening, error)
}
type statsHandlers struct{ svc statsService }
type timelineBucketJSON struct {
Year int `json:"year"`
Month int `json:"month,omitempty"`
Listens int `json:"listens"`
Shares []float64 `json:"shares"`
Other float64 `json:"other"`
Untagged float64 `json:"untagged"`
}
type timelineJSON struct {
Unit string `json:"unit"`
Genres []string `json:"genres"`
Buckets []timelineBucketJSON `json:"buckets"`
}
func timelineBody(t stats.Timeline) timelineJSON {
out := timelineJSON{Unit: t.Unit, Genres: t.Genres, Buckets: make([]timelineBucketJSON, 0, len(t.Buckets))}
if out.Genres == nil {
out.Genres = []string{}
}
for _, b := range t.Buckets {
shares := b.Shares
if shares == nil {
shares = []float64{}
}
out.Buckets = append(out.Buckets, timelineBucketJSON{Year: b.Year, Month: b.Month, Listens: b.Listens, Shares: shares, Other: b.Other, Untagged: b.Untagged})
}
return out
}
type sharesJSON struct {
Top []shareJSON `json:"top"`
Other float64 `json:"other"`
Untagged int `json:"untagged"`
UntaggedShare float64 `json:"untagged_share"`
}
type shareJSON struct {
Name string `json:"name"`
Count int `json:"count"`
Share float64 `json:"share"`
}
func genresJSON(g stats.Genres) sharesJSON {
out := sharesJSON{Top: make([]shareJSON, 0, len(g.Top)), Other: g.Other, Untagged: g.Untagged, UntaggedShare: g.UntaggedShare}
for _, s := range g.Top {
out.Top = append(out.Top, shareJSON{Name: s.Name, Count: s.Count, Share: s.Share})
}
return out
}
// library says what the server holds: the songs that can be played, their length and size, formats, genres and decades.
func (h *statsHandlers) library(c *gin.Context) {
lib, err := h.svc.Library(c.Request.Context())
if err != nil {
_ = c.Error(err)
writeError(c, http.StatusInternalServerError, "internal", "internal error")
return
}
formats := make([]gin.H, 0, len(lib.Formats))
for _, f := range lib.Formats {
formats = append(formats, gin.H{"format": f.Format, "files": f.Files, "bytes": f.Bytes})
}
decades := make([]gin.H, 0, len(lib.Decades))
for _, d := range lib.Decades {
decades = append(decades, gin.H{"decade": d.Decade, "songs": d.Songs})
}
c.JSON(http.StatusOK, gin.H{
"artists": lib.Artists, "albums": lib.Albums, "songs": lib.Songs,
"duration_ms": lib.DurationMs, "size_bytes": lib.SizeBytes,
"formats": formats, "genres": genresJSON(lib.Genres), "decades": decades, "no_year": lib.NoYear,
})
}
// listening says what the signed-in person listened to, for all time or for from (included) to until (excluded). The
// hours, weekdays and years are those of tz.
func (h *statsHandlers) listening(c *gin.Context) {
var rng stats.Range
for name, into := range map[string]*time.Time{"from": &rng.From, "until": &rng.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
}
}
if !rng.From.IsZero() && !rng.Until.IsZero() && rng.Until.Before(rng.From) {
writeError(c, http.StatusBadRequest, "invalid_input", "until must not be before from")
return
}
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.Listening(c.Request.Context(), currentUserID(c), rng, loc)
if errors.Is(err, stats.ErrInvalidRange) {
writeError(c, http.StatusBadRequest, "invalid_input", "until must not be before from")
return
}
if err != nil {
_ = c.Error(err)
writeError(c, http.StatusInternalServerError, "internal", "internal error")
return
}
years := make([]gin.H, 0, len(got.Years))
for _, y := range got.Years {
years = append(years, gin.H{"year": y.Key, "listens": y.Count})
}
artists := make([]gin.H, 0, len(got.TopArtists))
for _, a := range got.TopArtists {
artists = append(artists, gin.H{"id": a.ID, "name": a.Name, "listens": a.Listens})
}
songs := make([]gin.H, 0, len(got.TopSongs))
for _, s := range got.TopSongs {
names := s.Artists
if names == nil {
names = []string{}
}
songs = append(songs, gin.H{"id": s.ID, "title": s.Name, "artists": names, "listens": s.Listens})
}
body := gin.H{
"listens": got.Listens, "songs": got.Songs, "artists": got.Artists, "played_ms": got.PlayedMs,
"years": years, "hours": got.Hours, "weekdays": got.Weekdays,
"top_artists": artists, "top_songs": songs, "genres": genresJSON(got.Genres),
"genre_timeline": timelineBody(got.GenreTimeline),
}
if !got.First.IsZero() {
body["first"] = got.First.UTC().Format(time.RFC3339)
}
c.JSON(http.StatusOK, body)
}