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

226 lines
7.6 KiB
Go

package httpapi
import (
"encoding/json"
"errors"
"io"
"net/http"
"strconv"
"github.com/gin-gonic/gin"
"git.kmalloc.org/squid/sonda/internal/federation"
)
// friendsHandlers let any signed-in listener browse the catalogue that a friend shares. This server asks the
// friend, with a request signed by its own key, and passes the answer on after checking its shape; nothing is
// kept. A listener learns a friend's name and nothing more: the address and the key are for the admin.
type friendsHandlers struct{ svc federationService }
// friendNotFound maps a kind of thing to the code of the answer when the friend does not have it.
var friendNotFound = map[string]string{"artists": "artist_not_found", "albums": "album_not_found", "tracks": "track_not_found", "covers": "cover_not_found"}
func (h *friendsHandlers) list(c *gin.Context) {
friends, err := h.svc.ActiveFriends(c.Request.Context())
if err != nil {
_ = c.Error(err)
writeError(c, http.StatusInternalServerError, "internal", "internal error")
return
}
out := make([]gin.H, len(friends))
for i, f := range friends {
out[i] = gin.H{"id": f.ID, "name": f.Name}
}
c.JSON(http.StatusOK, gin.H{"friends": out})
}
// writeFriendError tells a listener, in fixed words, what went wrong with a friend. The address of the friend and
// what the connection said never leave the server.
func writeFriendError(c *gin.Context, err error, resource string) {
switch {
case errors.Is(err, federation.ErrFriendMissing):
writeError(c, http.StatusNotFound, "friend_not_found", "no such friend")
case errors.Is(err, federation.ErrInvalidInput):
writeError(c, http.StatusBadRequest, "invalid_input", "the question was not valid")
case errors.Is(err, federation.ErrNotFoundThere):
writeError(c, http.StatusNotFound, friendNotFound[resource], "not found")
case errors.Is(err, federation.ErrNotFriend), errors.Is(err, federation.ErrNotApproved):
writeError(c, http.StatusConflict, "friend_gone", "this friend does not answer as a friend any more")
case errors.Is(err, federation.ErrTooMany):
c.Header("Retry-After", "5")
writeError(c, http.StatusTooManyRequests, "friend_busy", "this friend is busy: try again in a moment")
case errors.Is(err, federation.ErrUnreachable):
_ = c.Error(err) // the cause stays in the log
writeError(c, http.StatusBadGateway, "friend_unreachable", "this friend could not be reached")
default:
_ = c.Error(err)
writeError(c, http.StatusInternalServerError, "internal", "internal error")
}
}
// fetch asks the friend of the request for a list or an item, and returns what it said.
func (h *friendsHandlers) fetch(c *gin.Context, resource string, withID bool) ([]byte, bool) {
friend, err := strconv.ParseInt(c.Param("friend"), 10, 64)
if err != nil || friend <= 0 {
writeError(c, http.StatusBadRequest, "invalid_input", "friend must be a positive number")
return nil, false
}
var id int64
if withID {
v, ok := pathID(c)
if !ok {
return nil, false
}
id = v
}
body, err := h.svc.Browse(c.Request.Context(), friend, resource, id, c.Request.URL.Query())
if err != nil {
writeFriendError(c, err, resource)
return nil, false
}
return body, true
}
// peaksJSON is the shape of a track: a few levels from 0 to 255, as many as the count says.
type peaksJSON struct {
Count int `json:"count"`
Peaks []int `json:"peaks"`
}
// maxPeaks is far more than a server makes (120), and far less than would be a way to send a lot of data through.
const maxPeaks = 1000
// peaks passes on the shape of a friend's track, for the seek bar. The friend works it out the first time and says so
// (202); like the rest of what a friend sends, it is read into this server's own type, and an answer that is not a
// list of levels from 0 to 255 is not passed on.
func (h *friendsHandlers) peaks(c *gin.Context) {
friend, err := strconv.ParseInt(c.Param("friend"), 10, 64)
if err != nil || friend <= 0 {
writeError(c, http.StatusBadRequest, "invalid_input", "friend must be a positive number")
return
}
id, ok := pathID(c)
if !ok {
return
}
body, err := h.svc.Peaks(c.Request.Context(), friend, id)
switch {
case err == nil:
case errors.Is(err, federation.ErrWorking):
c.Header("Retry-After", "3")
c.JSON(http.StatusAccepted, gin.H{"status": "working"})
return
case errors.Is(err, federation.ErrNoWaveform):
writeError(c, http.StatusNotFound, "waveform_unavailable", "the waveform of this file cannot be worked out")
return
default:
writeFriendError(c, err, "tracks")
return
}
var shape peaksJSON
if json.Unmarshal(body, &shape) != nil || shape.Count != len(shape.Peaks) || shape.Count == 0 || shape.Count > maxPeaks {
badAnswer(c)
return
}
for _, v := range shape.Peaks {
if v < 0 || v > 255 {
badAnswer(c)
return
}
}
c.JSON(http.StatusOK, shape)
}
func badAnswer(c *gin.Context) {
_ = c.Error(errors.New("a friend sent an answer that is not a catalogue page"))
writeError(c, http.StatusBadGateway, "friend_unreachable", "this friend could not be reached")
}
// relayPage passes a page of the friend's catalogue on. It is read into the types of this server's own API first,
// so whatever else the friend added is dropped and the answer has the shape the spec promises.
func relayPage[T any](h *friendsHandlers, resource string) gin.HandlerFunc {
return func(c *gin.Context) {
body, ok := h.fetch(c, resource, false)
if !ok {
return
}
var page struct {
Items []T `json:"items"`
Total int `json:"total"`
Limit int `json:"limit"`
Offset int `json:"offset"`
}
if json.Unmarshal(body, &page) != nil || page.Total < 0 {
badAnswer(c)
return
}
if page.Items == nil {
page.Items = []T{}
}
c.JSON(http.StatusOK, page)
}
}
// relayOne passes one artist, album or track of the friend on, checked the same way.
func relayOne[T any](h *friendsHandlers, resource string) gin.HandlerFunc {
return func(c *gin.Context) {
body, ok := h.fetch(c, resource, true)
if !ok {
return
}
var item T
if json.Unmarshal(body, &item) != nil {
badAnswer(c)
return
}
c.JSON(http.StatusOK, item)
}
}
// friendMediaHandlers pass the audio and the covers of a friend on to a listener. The listener's browser talks to
// this server only: this one asks the friend, signed, so the friend sees this server and nothing of the listener.
type friendMediaHandlers struct{ svc federationService }
func (h *friendMediaHandlers) stream(c *gin.Context) {
h.serve(c, federation.MediaStream, "tracks", "private, no-cache")
}
func (h *friendMediaHandlers) cover(c *gin.Context) {
h.serve(c, federation.MediaCover, "covers", "private, max-age=3600")
}
func (h *friendMediaHandlers) serve(c *gin.Context, kind, resource, cache string) {
friend, err := strconv.ParseInt(c.Param("friend"), 10, 64)
if err != nil || friend <= 0 {
writeError(c, http.StatusBadRequest, "invalid_input", "friend must be a positive number")
return
}
id, ok := pathID(c)
if !ok {
return
}
media, err := h.svc.OpenMedia(c.Request.Context(), friend, kind, id, c.Request.URL.Query(), c.Request.Header)
if err != nil {
writeFriendError(c, err, resource)
return
}
defer media.Body.Close()
hdr := c.Writer.Header()
for k, vs := range media.Header {
for _, v := range vs {
hdr.Add(k, v)
}
}
hdr.Set("X-Content-Type-Options", "nosniff")
// The URL may carry the access token: never leak it through Referer.
hdr.Set("Referrer-Policy", "no-referrer")
hdr.Set("Cache-Control", cache)
c.Status(media.Status)
if media.Status == http.StatusNotModified || media.Status == http.StatusRequestedRangeNotSatisfiable {
c.Writer.WriteHeaderNow()
return
}
// The listener may leave at any time: the copy then ends, and so does the request to the friend.
_, _ = io.Copy(c.Writer, media.Body)
}