sonda/internal/api/http/handlers_smart.go
tgiachi a880b87a9e chore: move the module path to git.kmalloc.org/squid/sonda
Migrating hosting from Codeberg to git.kmalloc.org. Renames the
module path in go.mod, every internal import, and the OCI image
source label in the Dockerfile. Build and full test suite verified
green after the rename.
2026-11-15 17:30:29 +01:00

372 lines
11 KiB
Go

package httpapi
import (
"errors"
"net/http"
"strings"
"github.com/gin-gonic/gin"
"git.kmalloc.org/squid/sonda/internal/smart"
)
// smartHandlers serve the signed-in user's smart playlists: playlists that are a set of rules, worked out
// every time they are opened. They are theirs alone: one of somebody else answers
// smart_playlist_not_found, as one that does not exist.
type smartHandlers struct {
svc smartService
playlists playlistService
naming namingService
}
type smartJSON struct {
ID int64 `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Rules smart.Rules `json:"rules"`
Sort string `json:"sort"`
Limit int `json:"limit"`
CreatedAt *string `json:"created_at"`
UpdatedAt *string `json:"updated_at"`
}
type smartPageJSON struct {
Items []smartJSON `json:"items"`
Total int `json:"total"`
Limit int `json:"limit"`
Offset int `json:"offset"`
}
type smartTracksJSON struct {
Variant int `json:"variant"`
Tracks []trackJSON `json:"tracks"`
}
func toSmartJSON(p smart.SmartPlaylist) smartJSON {
return smartJSON{
ID: p.ID, Name: p.Name, Description: p.Description, Rules: p.Rules, Sort: string(p.Sort), Limit: p.Limit,
CreatedAt: rfc3339(p.CreatedAt), UpdatedAt: rfc3339(p.UpdatedAt),
}
}
func writeSmartError(c *gin.Context, err error) {
switch {
case errors.Is(err, smart.ErrInvalidInput):
writeError(c, http.StatusBadRequest, "invalid_input", err.Error())
case errors.Is(err, smart.ErrNotFound):
writeError(c, http.StatusNotFound, "smart_playlist_not_found", "no such smart playlist")
case errors.Is(err, smart.ErrTooMany):
writeError(c, http.StatusConflict, "limit_reached", err.Error())
default:
_ = c.Error(err)
writeError(c, http.StatusInternalServerError, "internal", "internal error")
}
}
type createSmartRequest struct {
Lang string `json:"lang"` // for a name that Claude makes
Name string `json:"name"`
Description string `json:"description"`
Rules smart.Rules `json:"rules"`
Sort string `json:"sort"` // absent: random
Limit int `json:"limit"` // absent: 50
}
func (h *smartHandlers) create(c *gin.Context) {
var req createSmartRequest
if !bindJSON(c, &req) {
return
}
in := smart.Input{Name: req.Name, Description: req.Description, Rules: req.Rules, Sort: smart.Sort(req.Sort), Limit: req.Limit}
if strings.TrimSpace(in.Name) == "" && h.naming.Auto(c.Request.Context()) {
// No name, and Claude is on: it names the playlist from the songs the rules give.
if tracks, err := h.svc.Preview(c.Request.Context(), currentUserID(c), in, 0); err == nil {
if name, desc := automaticName(c, h.naming, true, req.Lang, "smart", tracks, in.Rules.Summary(), ""); name != "" {
in.Name = name
if strings.TrimSpace(in.Description) == "" {
in.Description = desc
}
}
}
}
p, err := h.svc.Create(c.Request.Context(), currentUserID(c), in)
if err != nil {
writeSmartError(c, err)
return
}
c.JSON(http.StatusCreated, toSmartJSON(p))
}
func (h *smartHandlers) list(c *gin.Context) {
page, ok := pageOf(c)
if !ok {
return
}
l, err := h.svc.List(c.Request.Context(), currentUserID(c), page.Limit, page.Offset)
if err != nil {
writeSmartError(c, err)
return
}
out := smartPageJSON{Items: make([]smartJSON, len(l.Items)), Total: l.Total, Limit: l.Limit, Offset: l.Offset}
for i, p := range l.Items {
out.Items[i] = toSmartJSON(p)
}
c.JSON(http.StatusOK, out)
}
func (h *smartHandlers) get(c *gin.Context) {
id, ok := pathID(c)
if !ok {
return
}
p, err := h.svc.Get(c.Request.Context(), currentUserID(c), id)
if err != nil {
writeSmartError(c, err)
return
}
c.JSON(http.StatusOK, toSmartJSON(p))
}
type updateSmartRequest struct {
Name *string `json:"name"` // pointers: absent must not mean empty
Description *string `json:"description"`
Rules *smart.Rules `json:"rules"` // replace the old ones whole
Sort *string `json:"sort"`
Limit *int `json:"limit"`
}
func (h *smartHandlers) update(c *gin.Context) {
id, ok := pathID(c)
if !ok {
return
}
var req updateSmartRequest
if !bindJSON(c, &req) {
return
}
patch := smart.Patch{Name: req.Name, Description: req.Description, Rules: req.Rules, Limit: req.Limit}
if req.Sort != nil {
s := smart.Sort(*req.Sort)
patch.Sort = &s
}
p, err := h.svc.Update(c.Request.Context(), currentUserID(c), id, patch)
if err != nil {
writeSmartError(c, err)
return
}
c.JSON(http.StatusOK, toSmartJSON(p))
}
func (h *smartHandlers) remove(c *gin.Context) {
id, ok := pathID(c)
if !ok {
return
}
if err := h.svc.Delete(c.Request.Context(), currentUserID(c), id); err != nil {
writeSmartError(c, err)
return
}
c.Status(http.StatusNoContent)
}
// tracks works the songs out now: the same all day, and other ones for another variant.
func (h *smartHandlers) tracks(c *gin.Context) {
id, ok := pathID(c)
if !ok {
return
}
variant, ok := variantOf(c)
if !ok {
return
}
_, tracks, err := h.svc.Tracks(c.Request.Context(), currentUserID(c), id, variant)
if err != nil {
writeSmartError(c, err)
return
}
c.JSON(http.StatusOK, smartTracksJSON{Variant: variant, Tracks: toTracksJSON(tracks)})
}
type previewSmartRequest struct {
Rules smart.Rules `json:"rules"`
Sort string `json:"sort"`
Limit int `json:"limit"`
Variant int `json:"variant"`
}
// preview works the songs out for rules that are not kept, so they can be tried before saving.
func (h *smartHandlers) preview(c *gin.Context) {
var req previewSmartRequest
if !bindJSON(c, &req) {
return
}
tracks, err := h.svc.Preview(c.Request.Context(), currentUserID(c), smart.Input{
Rules: req.Rules, Sort: smart.Sort(req.Sort), Limit: req.Limit,
}, req.Variant)
if err != nil {
writeSmartError(c, err)
return
}
c.JSON(http.StatusOK, smartTracksJSON{Variant: req.Variant, Tracks: toTracksJSON(tracks)})
}
type saveSmartRequest struct {
Name string `json:"name"` // blank: the name of the smart playlist
Variant *int `json:"variant"` // absent: the songs 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 normal playlist of the songs the smart playlist gives now (the ones that variant shows).
func (h *smartHandlers) save(c *gin.Context) {
id, ok := pathID(c)
if !ok {
return
}
var req saveSmartRequest
if c.Request.ContentLength != 0 && !bindJSON(c, &req) {
return
}
variant := 0
if req.Variant != nil {
variant = *req.Variant
}
user := currentUserID(c)
p, tracks, err := h.svc.Tracks(c.Request.Context(), user, id, variant)
if err != nil {
writeSmartError(c, err)
return
}
if len(tracks) == 0 {
writeError(c, http.StatusUnprocessableEntity, "smart_playlist_empty", "the rules give no songs to save")
return
}
name := req.Name
if strings.TrimSpace(name) == "" {
name = p.Name
}
name, description := automaticName(c, h.naming, req.AutoName, req.Lang, "smart", tracks, p.Rules.Summary(), name)
keepAsPlaylist(c, h.playlists, user, name, description, tracks)
}
// genres lists the genres of the library, to choose from in a rule: each with the number of songs, the
// biggest first, spellings merged the way the rules compare them.
func (h *smartHandlers) genres(c *gin.Context) {
list, err := h.svc.Genres(c.Request.Context())
if err != nil {
writeSmartError(c, err)
return
}
items := make([]gin.H, len(list))
for i, g := range list {
items[i] = gin.H{"name": g.Name, "tracks": g.Tracks}
}
c.JSON(http.StatusOK, gin.H{"items": items})
}
type suggestedJSON struct {
Key string `json:"key"`
Rules smart.Rules `json:"rules"`
Sort string `json:"sort"`
Limit int `json:"limit"`
}
func toSuggestedJSON(s smart.SuggestedPlaylist) suggestedJSON {
return suggestedJSON{Key: s.Key, Rules: s.Rules, Sort: string(s.Sort), Limit: s.Limit}
}
// suggestedList gives the smart playlists that Sonda makes for everybody: a fixed set, with no songs in it.
func (h *smartHandlers) suggestedList(c *gin.Context) {
list := smart.Suggested()
out := make([]suggestedJSON, len(list))
for i, s := range list {
out[i] = toSuggestedJSON(s)
}
c.JSON(http.StatusOK, gin.H{"items": out})
}
func writeSuggestedError(c *gin.Context, err error) {
if errors.Is(err, smart.ErrNotFound) {
writeError(c, http.StatusNotFound, "suggested_not_found", "no such suggested smart playlist")
return
}
writeSmartError(c, err)
}
// suggestedTracks works the songs of a suggested smart playlist out for the signed-in user.
func (h *smartHandlers) suggestedTracks(c *gin.Context) {
variant, ok := variantOf(c)
if !ok {
return
}
_, tracks, err := h.svc.SuggestedTracks(c.Request.Context(), currentUserID(c), c.Param("key"), variant)
if err != nil {
writeSuggestedError(c, err)
return
}
c.JSON(http.StatusOK, smartTracksJSON{Variant: variant, Tracks: toTracksJSON(tracks)})
}
// suggestedSave makes a normal playlist of the songs a suggested smart playlist gives now.
func (h *smartHandlers) suggestedSave(c *gin.Context) {
var req saveSmartRequest
if c.Request.ContentLength != 0 && !bindJSON(c, &req) {
return
}
variant := 0
if req.Variant != nil {
variant = *req.Variant
}
user := currentUserID(c)
key := c.Param("key")
sg, tracks, err := h.svc.SuggestedTracks(c.Request.Context(), user, key, variant)
if err != nil {
writeSuggestedError(c, err)
return
}
if len(tracks) == 0 {
writeError(c, http.StatusUnprocessableEntity, "smart_playlist_empty", "the rules give no songs to save")
return
}
name := strings.TrimSpace(req.Name)
if name == "" {
name = key // a client says the name in its language; this is only for one that does not
}
name, description := automaticName(c, h.naming, req.AutoName, req.Lang, "smart", tracks, sg.Rules.Summary(), name)
keepAsPlaylist(c, h.playlists, user, name, description, tracks)
}
// covers says which albums stand for a smart playlist, for its picture: up to 4 albums that have a cover, in the order of
// the songs it gives now. It is apart from the songs so that a list of smart playlists need not wait for all of them.
func (h *smartHandlers) covers(c *gin.Context) {
id, ok := pathID(c)
if !ok {
return
}
variant, ok := variantOf(c)
if !ok {
return
}
albums, err := h.svc.Covers(c.Request.Context(), currentUserID(c), id, variant)
if err != nil {
writeSmartError(c, err)
return
}
c.Header("Cache-Control", "private, max-age=300")
c.JSON(http.StatusOK, gin.H{"album_ids": albums})
}
// suggestedCovers is covers for a suggested smart playlist.
func (h *smartHandlers) suggestedCovers(c *gin.Context) {
variant, ok := variantOf(c)
if !ok {
return
}
albums, err := h.svc.SuggestedCovers(c.Request.Context(), currentUserID(c), c.Param("key"), variant)
if err != nil {
writeSuggestedError(c, err)
return
}
c.Header("Cache-Control", "private, max-age=300")
c.JSON(http.StatusOK, gin.H{"album_ids": albums})
}