sonda/internal/api/http/handlers_mixes.go
tgiachi 407b20334a feat: radio stations that Sonda makes by itself
Stations made from the music, random and without end, with nothing to set up: the
mixes the listener has (genres, favourites, rediscover, new to you), everything,
one for each decade that has 30 songs by 4 artists, and the radio of an artist (their
songs, four times as likely, and the songs of the two genres most of theirs have).
Every time a station is asked for it picks other songs, with the same weights as the
mixes (taste, hearts, nothing skipped lately).

- mixes.Service.Radios and Radio; Filter has All and years, the store has Decades
- GET /radio and GET /radio/{id}, in the OpenAPI spec
- OpenSubsonic: each station is a playlist (rd-<id>, "Radio · Rock") that has other
  songs every time it is opened, for apps that cannot play a radio that never ends
2026-11-16 12:13:55 +01:00

205 lines
5.5 KiB
Go

package httpapi
import (
"errors"
"net/http"
"strings"
"github.com/gin-gonic/gin"
"git.kmalloc.org/squid/sonda/internal/catalog"
"git.kmalloc.org/squid/sonda/internal/mixes"
)
// mixHandlers serve the mixes made for the signed-in user. They are worked out from that user's
// own history and the genres of the music, and never stored.
type mixHandlers struct {
svc mixService
playlists playlistService
naming namingService
}
type mixJSON struct {
ID string `json:"id"`
Kind string `json:"kind"`
Title string `json:"title"`
Genre *string `json:"genre"`
Artists []string `json:"artists"`
AlbumIDs []int64 `json:"album_ids"`
}
type mixWithTracksJSON struct {
mixJSON
Variant int `json:"variant"`
Tracks []trackJSON `json:"tracks"`
}
func toMixJSON(m mixes.Mix) mixJSON {
out := mixJSON{ID: m.ID, Kind: string(m.Kind), Title: m.Title, Artists: m.Artists}
if out.Artists == nil {
out.Artists = []string{}
}
out.AlbumIDs = m.AlbumIDs
if out.AlbumIDs == nil {
out.AlbumIDs = []int64{}
}
if m.Genre != "" {
g := m.Genre
out.Genre = &g
}
return out
}
func toTracksJSON(tracks []catalog.Track) []trackJSON {
out := make([]trackJSON, len(tracks))
for i, t := range tracks {
out[i] = toTrackJSON(t)
}
return out
}
func writeMixError(c *gin.Context, err error) {
switch {
case errors.Is(err, mixes.ErrNotFound):
writeError(c, http.StatusNotFound, "mix_not_found", "no such mix")
case errors.Is(err, mixes.ErrInvalidInput):
writeError(c, http.StatusBadRequest, "invalid_input", err.Error())
default:
_ = c.Error(err)
writeError(c, http.StatusInternalServerError, "internal", "internal error")
}
}
// variantOf reads the variant of the query string: a whole number from 0 up, 0 when absent.
func variantOf(c *gin.Context) (int, bool) {
v, ok := queryInt(c, "variant")
if !ok {
return 0, false
}
if v < 0 || v > mixes.MaxVariant {
writeError(c, http.StatusBadRequest, "invalid_input", "variant must be a whole number from 0 up")
return 0, false
}
return int(v), true
}
func (h *mixHandlers) list(c *gin.Context) {
list, err := h.svc.List(c.Request.Context(), currentUserID(c))
if err != nil {
writeMixError(c, err)
return
}
out := make([]mixJSON, len(list))
for i, m := range list {
out[i] = toMixJSON(m)
}
c.JSON(http.StatusOK, gin.H{"items": out})
}
func (h *mixHandlers) get(c *gin.Context) {
variant, ok := variantOf(c)
if !ok {
return
}
m, tracks, err := h.svc.Get(c.Request.Context(), currentUserID(c), c.Param("id"), variant)
if err != nil {
writeMixError(c, err)
return
}
c.JSON(http.StatusOK, mixWithTracksJSON{mixJSON: toMixJSON(m), Variant: variant, Tracks: toTracksJSON(tracks)})
}
type saveMixRequest struct {
Name string `json:"name"` // blank: the title of the mix
Variant *int `json:"variant"` // absent: the mix of the day
AutoName bool `json:"auto_name"` // Claude names the playlist when it is on, and name is only the fallback
Lang string `json:"lang"`
}
// save makes a playlist of the songs of a mix, the ones that variant shows. A save that fails
// half way leaves no playlist behind.
func (h *mixHandlers) save(c *gin.Context) {
var req saveMixRequest
if c.Request.ContentLength != 0 && !bindJSON(c, &req) {
return
}
variant := 0
if req.Variant != nil {
variant = *req.Variant
}
ctx, user := c.Request.Context(), currentUserID(c)
m, tracks, err := h.svc.Get(ctx, user, c.Param("id"), variant)
if err != nil {
writeMixError(c, err)
return
}
if len(tracks) == 0 {
writeError(c, http.StatusUnprocessableEntity, "mix_empty", "the mix has no songs to save")
return
}
name := req.Name
if strings.TrimSpace(name) == "" {
name = m.Title
}
name, description := automaticName(c, h.naming, req.AutoName, req.Lang, "mix", tracks, "", name)
keepAsPlaylist(c, h.playlists, user, name, description, tracks)
}
// radioJSON is a station of the radio: a mix that is not for a day, and has decades, everything and artists.
type radioJSON struct {
ID string `json:"id"`
Kind string `json:"kind"`
Title string `json:"title"`
Genre *string `json:"genre"`
Decade *int `json:"decade"`
Artists []string `json:"artists"`
AlbumIDs []int64 `json:"album_ids"`
}
type radioWithTracksJSON struct {
radioJSON
Tracks []trackJSON `json:"tracks"`
}
func toRadioJSON(m mixes.Mix) radioJSON {
base := toMixJSON(m)
out := radioJSON{ID: base.ID, Kind: base.Kind, Title: base.Title, Genre: base.Genre, Artists: base.Artists, AlbumIDs: base.AlbumIDs}
if m.Decade > 0 {
d := m.Decade
out.Decade = &d
}
return out
}
func writeRadioError(c *gin.Context, err error) {
if errors.Is(err, mixes.ErrNotFound) {
writeError(c, http.StatusNotFound, "station_not_found", "no such station")
return
}
writeMixError(c, err)
}
// radioList is every station of the radio of the signed-in user.
func (h *mixHandlers) radioList(c *gin.Context) {
list, err := h.svc.Radios(c.Request.Context(), currentUserID(c))
if err != nil {
writeRadioError(c, err)
return
}
out := make([]radioJSON, len(list))
for i, m := range list {
out[i] = toRadioJSON(m)
}
c.JSON(http.StatusOK, gin.H{"items": out})
}
// radioGet is songs of a station: other ones every time it is asked.
func (h *mixHandlers) radioGet(c *gin.Context) {
m, tracks, err := h.svc.Radio(c.Request.Context(), currentUserID(c), c.Param("id"))
if err != nil {
writeRadioError(c, err)
return
}
c.Header("Cache-Control", "no-store")
c.JSON(http.StatusOK, radioWithTracksJSON{radioJSON: toRadioJSON(m), Tracks: toTracksJSON(tracks)})
}