sonda/internal/api/http/handlers_playlists.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

296 lines
7.7 KiB
Go

package httpapi
import (
"errors"
"net/http"
"strconv"
"github.com/gin-gonic/gin"
"git.kmalloc.org/squid/sonda/internal/catalog"
"git.kmalloc.org/squid/sonda/internal/playlists"
)
// playlistHandlers serve the signed-in user's playlists. They are theirs alone: a playlist of
// somebody else answers playlist_not_found, as one that does not exist.
type playlistHandlers struct{ svc playlistService }
type playlistJSON struct {
ID int64 `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
TrackCount int `json:"track_count"`
DurationMs int64 `json:"duration_ms"`
CreatedAt *string `json:"created_at"`
UpdatedAt *string `json:"updated_at"`
AlbumIDs []int64 `json:"album_ids"`
}
type playlistPageJSON struct {
Items []playlistJSON `json:"items"`
Total int `json:"total"`
Limit int `json:"limit"`
Offset int `json:"offset"`
}
type playlistItemJSON struct {
ID int64 `json:"id"`
Position int `json:"position"`
Available bool `json:"available"`
AddedAt *string `json:"added_at"`
Track trackJSON `json:"track"`
}
type playlistItemsJSON struct {
Items []playlistItemJSON `json:"items"`
Total int `json:"total"`
Limit int `json:"limit"`
Offset int `json:"offset"`
}
func toPlaylistJSON(p playlists.Playlist) playlistJSON {
albums := p.AlbumIDs
if albums == nil {
albums = []int64{}
}
return playlistJSON{
ID: p.ID, Name: p.Name, Description: p.Description, TrackCount: p.TrackCount, DurationMs: p.DurationMs,
CreatedAt: rfc3339(p.CreatedAt), UpdatedAt: rfc3339(p.UpdatedAt), AlbumIDs: albums,
}
}
func writePlaylistError(c *gin.Context, err error) {
switch {
case errors.Is(err, playlists.ErrInvalidInput):
writeError(c, http.StatusBadRequest, "invalid_input", err.Error())
case errors.Is(err, playlists.ErrNotFound):
writeError(c, http.StatusNotFound, "playlist_not_found", "no such playlist")
case errors.Is(err, playlists.ErrItemNotFound):
writeError(c, http.StatusNotFound, "item_not_found", "the playlist has no such item")
case errors.Is(err, playlists.ErrTrackNotFound):
writeError(c, http.StatusUnprocessableEntity, "track_not_found", "one of the tracks does not exist")
case errors.Is(err, playlists.ErrPosition):
writeError(c, http.StatusBadRequest, "invalid_position", err.Error())
case errors.Is(err, playlists.ErrTooMany):
writeError(c, http.StatusConflict, "limit_reached", err.Error())
default:
_ = c.Error(err)
writeError(c, http.StatusInternalServerError, "internal", "internal error")
}
}
// itemID reads the item of the path.
func itemID(c *gin.Context) (int64, bool) {
id, err := strconv.ParseInt(c.Param("item"), 10, 64)
if err != nil || id <= 0 {
writeError(c, http.StatusBadRequest, "invalid_input", "item must be a positive number")
return 0, false
}
return id, true
}
// pageOf reads limit and offset from the query string.
func pageOf(c *gin.Context) (playlists.Page, bool) {
limit, ok := queryInt(c, "limit")
if !ok {
return playlists.Page{}, false
}
offset, ok := queryInt(c, "offset")
if !ok {
return playlists.Page{}, false
}
return playlists.Page{Limit: clampInt(limit), Offset: clampInt(offset)}, true
}
type createPlaylistRequest struct {
Name string `json:"name"`
Description string `json:"description"`
}
func (h *playlistHandlers) create(c *gin.Context) {
var req createPlaylistRequest
if !bindJSON(c, &req) {
return
}
p, err := h.svc.Create(c.Request.Context(), currentUserID(c), req.Name, req.Description)
if err != nil {
writePlaylistError(c, err)
return
}
c.JSON(http.StatusCreated, toPlaylistJSON(p))
}
func (h *playlistHandlers) list(c *gin.Context) {
page, ok := pageOf(c)
if !ok {
return
}
l, err := h.svc.List(c.Request.Context(), currentUserID(c), page)
if err != nil {
writePlaylistError(c, err)
return
}
out := playlistPageJSON{Items: make([]playlistJSON, len(l.Items)), Total: l.Total, Limit: l.Limit, Offset: l.Offset}
for i, p := range l.Items {
out.Items[i] = toPlaylistJSON(p)
}
c.JSON(http.StatusOK, out)
}
func (h *playlistHandlers) 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 {
writePlaylistError(c, err)
return
}
c.JSON(http.StatusOK, toPlaylistJSON(p))
}
type updatePlaylistRequest struct {
Name *string `json:"name"` // pointers: absent must not mean empty
Description *string `json:"description"` // an empty one clears it
}
func (h *playlistHandlers) update(c *gin.Context) {
id, ok := pathID(c)
if !ok {
return
}
var req updatePlaylistRequest
if !bindJSON(c, &req) {
return
}
p, err := h.svc.Update(c.Request.Context(), currentUserID(c), id, req.Name, req.Description)
if err != nil {
writePlaylistError(c, err)
return
}
c.JSON(http.StatusOK, toPlaylistJSON(p))
}
func (h *playlistHandlers) remove(c *gin.Context) {
id, ok := pathID(c)
if !ok {
return
}
if err := h.svc.Delete(c.Request.Context(), currentUserID(c), id); err != nil {
writePlaylistError(c, err)
return
}
c.Status(http.StatusNoContent)
}
func (h *playlistHandlers) items(c *gin.Context) {
id, ok := pathID(c)
if !ok {
return
}
page, ok := pageOf(c)
if !ok {
return
}
l, err := h.svc.Items(c.Request.Context(), currentUserID(c), id, page)
if err != nil {
writePlaylistError(c, err)
return
}
out := playlistItemsJSON{Items: make([]playlistItemJSON, len(l.Items)), Total: l.Total, Limit: l.Limit, Offset: l.Offset}
for i, it := range l.Items {
out.Items[i] = playlistItemJSON{
ID: it.ID, Position: it.Position, Available: it.Available, AddedAt: rfc3339(it.AddedAt), Track: toTrackJSON(it.Track),
}
}
c.JSON(http.StatusOK, out)
}
type addTracksRequest struct {
TrackIDs []int64 `json:"track_ids"`
Position *int `json:"position"` // absent: at the end
}
func (h *playlistHandlers) addTracks(c *gin.Context) {
id, ok := pathID(c)
if !ok {
return
}
var req addTracksRequest
if !bindJSON(c, &req) {
return
}
p, err := h.svc.AddTracks(c.Request.Context(), currentUserID(c), id, req.TrackIDs, req.Position)
if err != nil {
writePlaylistError(c, err)
return
}
c.JSON(http.StatusOK, toPlaylistJSON(p))
}
func (h *playlistHandlers) removeItem(c *gin.Context) {
id, ok := pathID(c)
if !ok {
return
}
item, ok := itemID(c)
if !ok {
return
}
if err := h.svc.RemoveItem(c.Request.Context(), currentUserID(c), id, item); err != nil {
writePlaylistError(c, err)
return
}
c.Status(http.StatusNoContent)
}
type moveItemRequest struct {
Position *int `json:"position"`
}
func (h *playlistHandlers) moveItem(c *gin.Context) {
id, ok := pathID(c)
if !ok {
return
}
item, ok := itemID(c)
if !ok {
return
}
var req moveItemRequest
if !bindJSON(c, &req) {
return
}
if req.Position == nil {
writeError(c, http.StatusBadRequest, "invalid_input", "position is required")
return
}
if err := h.svc.MoveItem(c.Request.Context(), currentUserID(c), id, item, *req.Position); err != nil {
writePlaylistError(c, err)
return
}
c.Status(http.StatusNoContent)
}
// keepAsPlaylist makes a playlist of the user with the songs, in order, and answers with it. A save that
// fails half way leaves no playlist behind.
func keepAsPlaylist(c *gin.Context, svc playlistService, user int64, name, description string, tracks []catalog.Track) {
ctx := c.Request.Context()
pl, err := svc.Create(ctx, user, name, description)
if err != nil {
writePlaylistError(c, err)
return
}
ids := make([]int64, len(tracks))
for i, t := range tracks {
ids[i] = t.ID
}
filled, err := svc.AddTracks(ctx, user, pl.ID, ids, nil)
if err != nil {
_ = svc.Delete(ctx, user, pl.ID)
writePlaylistError(c, err)
return
}
c.JSON(http.StatusCreated, toPlaylistJSON(filled))
}