sonda/internal/api/http/handlers_libraries.go
tgiachi 89826fcd07 feat(federation): shared libraries and the signed read API for friends
A friend's server can now read what an admin chose to share.

- A library has a shared flag, off by default (migration 0024), set with
  PATCH /libraries/{id}. Changing it never waits for a scan.
- Requests between friends are signed with each server's Ed25519 key: the
  method, the path and query from /api/v1/peer on, a date, a nonce and the
  hash of the empty body. A date more than two minutes off, a nonce used
  before, an unknown or removed key and a bad signature all get the same
  401. A friend still waiting for approval gets 403, and while federation is
  off the routes are missing.
- Routes under /api/v1/peer: info, artists, albums, tracks, covers and
  streaming with Range. The catalogue, the counts and the format come from
  the shared libraries only, and the file served is the one in a shared
  library. No path, library id, listen, taste, user or provider data is part
  of an answer.
- A friend never makes this server build a cover, read an audio file or ask
  a provider: only covers already built from the audio files are served.
- Per-friend limits, set by the admin: parallel streams (default 3) and KiB
  a second (default 4096, 0 for none), shared by all the streams of a friend.
- A log of the last requests friends made (route, status, bytes; never the
  query), kept for 7 days, in GET /federation/requests.
- POST /federation/friends/{id}/check lets the side that pasted an invite
  find out that the other admin approved; a signed call from a friend this
  server is waiting for makes it active too.
- Admin: a Shared with friends switch on each library, which asks first, and
  limits, recent requests and a Check button in the Federation section, in
  English and Italian.
- OpenAPI paths and schemas, contract test, two real servers checked end to
  end with tagged audio files.
2026-11-13 15:04:07 +01:00

120 lines
3.1 KiB
Go

package httpapi
import (
"errors"
"net/http"
"time"
"github.com/gin-gonic/gin"
"codeberg.org/squidd/sonda/internal/library"
)
// librariesHandlers are the admin-only routes that manage libraries.
type librariesHandlers struct{ svc libraryService }
type libraryJSON struct {
ID int64 `json:"id"`
Name string `json:"name"`
Path string `json:"path"`
Shared bool `json:"shared"`
CreatedAt string `json:"created_at"`
}
func toLibraryJSON(l library.Library) libraryJSON {
return libraryJSON{ID: l.ID, Name: l.Name, Path: l.Path, Shared: l.Shared, CreatedAt: l.CreatedAt.UTC().Format(time.RFC3339)}
}
func writeLibraryError(c *gin.Context, err error) {
switch {
case errors.Is(err, library.ErrInvalidLibrary):
writeError(c, http.StatusBadRequest, "invalid_input", err.Error())
case errors.Is(err, library.ErrLibraryExists):
writeError(c, http.StatusConflict, "library_exists", err.Error())
case errors.Is(err, library.ErrLibraryNotFound):
writeError(c, http.StatusNotFound, "library_not_found", err.Error())
case errors.Is(err, library.ErrScanRunning):
writeError(c, http.StatusConflict, "scan_running", "wait for the running scan to finish")
default:
_ = c.Error(err)
writeError(c, http.StatusInternalServerError, "internal", "internal error")
}
}
func (h *librariesHandlers) list(c *gin.Context) {
libs, err := h.svc.List(c.Request.Context())
if err != nil {
writeLibraryError(c, err)
return
}
out := make([]libraryJSON, len(libs))
for i, l := range libs {
out[i] = toLibraryJSON(l)
}
c.JSON(http.StatusOK, gin.H{"libraries": out})
}
type createLibraryRequest struct {
Name string `json:"name"`
Path string `json:"path"`
}
func (h *librariesHandlers) create(c *gin.Context) {
var req createLibraryRequest
if !bindJSON(c, &req) {
return
}
lib, err := h.svc.Create(c.Request.Context(), req.Name, req.Path)
if err != nil {
writeLibraryError(c, err)
return
}
c.JSON(http.StatusCreated, toLibraryJSON(lib))
}
type updateLibraryRequest struct {
Name *string `json:"name"` // pointers: an absent field keeps the current value
Path *string `json:"path"`
// Shared says whether friends (federation) may read the library.
Shared *bool `json:"shared"`
}
func (h *librariesHandlers) update(c *gin.Context) {
id, ok := pathID(c)
if !ok {
return
}
var req updateLibraryRequest
if !bindJSON(c, &req) {
return
}
if req.Name == nil && req.Path == nil && req.Shared == nil {
writeError(c, http.StatusBadRequest, "invalid_input", "send name, path, shared or any of them")
return
}
var lib library.Library
var err error
if req.Name != nil || req.Path != nil {
lib, err = h.svc.Update(c.Request.Context(), id, req.Name, req.Path)
}
if err == nil && req.Shared != nil {
lib, err = h.svc.SetShared(c.Request.Context(), id, *req.Shared)
}
if err != nil {
writeLibraryError(c, err)
return
}
c.JSON(http.StatusOK, toLibraryJSON(lib))
}
func (h *librariesHandlers) remove(c *gin.Context) {
id, ok := pathID(c)
if !ok {
return
}
if err := h.svc.Delete(c.Request.Context(), id); err != nil {
writeLibraryError(c, err)
return
}
c.Status(http.StatusNoContent)
}