feat: the seek bar shows the waveform of a friend's track

A friend's server works out the peaks of a track in a shared library and gives
them to a signed friend (GET /peer/tracks/{id}/peaks). This server asks for them
and passes them on to the listener after checking them: 1 to 1000 levels from 0
to 255, as many as the count says (GET /friends/{friend}/tracks/{id}/peaks). The
player uses it for a friend's track, so its bar is no longer flat.
This commit is contained in:
tgiachi 2026-11-13 19:46:37 +01:00
commit 7243fe7a04
13 changed files with 862 additions and 33 deletions

View file

@ -113,6 +113,7 @@ func newTestEnvDB(t *testing.T, mutate func(*Deps, *bun.DB)) (http.Handler, *bun
libRepo := storage.NewLibraryRepo(db)
deps.PeerCatalog = catalog.NewService(storage.NewSharedCatalogRepo(db))
deps.PeerStreams = streaming.NewService(libRepo.Shared())
deps.PeerWaveform = waveform.NewService(storage.NewWaveformRepo(db), streaming.NewService(libRepo.Shared()))
deps.Waveform = waveform.NewService(storage.NewWaveformRepo(db), streaming.NewService(libRepo))
feedbackSvc := feedback.NewService(storage.NewFeedbackRepo(db))
deps.Feedback = feedbackSvc

View file

@ -1268,6 +1268,8 @@ func (c *contract) peer(t *testing.T, token, libID, albumID string) {
t.Fatalf("stream range: %d", rec.Code)
}
c.expect(signed("/peer/tracks/999999/stream"), 404, "the stream of a track that is not there", "track_not_found")
c.expect(signed("/peer/tracks/999999/peaks"), 404, "the shape of a track that is not there", "track_not_found")
c.expect(signed("/peer/tracks/"+trackID+"/peaks"), 404, "the shape of a file that is not audio", "waveform_unavailable")
// A friend gets a cover once a listener's request has built it, never before.
c.expect(signed("/peer/albums/"+albumID+"/cover?size=small"), 404, "a cover that was not asked for yet", "cover_not_found")
if rec := c.call("GET", "/albums/"+albumID+"/cover", token, nil); rec.Code != 200 {
@ -1339,6 +1341,10 @@ func (c *contract) friends(t *testing.T, token string) {
t.Fatalf("a friend's stream, a range: %d", rec.Code)
}
c.expect(c.call("GET", base+"/tracks/999999/stream", token, nil), 404, "the stream of a track the friend does not have", "track_not_found")
peaks := base + "/tracks/" + trackID + "/peaks"
c.expect(c.call("GET", peaks, "", nil), 401, "the shape of a friend's track without a login", "unauthorized")
c.expect(c.call("GET", base+"/tracks/999999/peaks", token, nil), 404, "the shape of a track the friend does not have", "track_not_found")
c.expect(c.call("GET", peaks, token, nil), 404, "the shape of a friend's file that is not audio", "waveform_unavailable")
cover := base + "/albums/" + albumID + "/cover"
c.expect(c.call("GET", cover, token, nil), 404, "a cover that is not built there yet", "cover_not_found")
var theirAlbum int64

View file

@ -0,0 +1,148 @@
package httpapi
import (
"net/http"
"os"
"path/filepath"
"strconv"
"testing"
"time"
"github.com/uptrace/bun"
"codeberg.org/squidd/sonda/internal/federation"
"codeberg.org/squidd/sonda/internal/storage"
)
// realAudio puts a real MP3 where the shared library of the fixture keeps its song, so that its shape can be worked out.
func (f *peerFixture) realAudio(t *testing.T) {
t.Helper()
data, err := os.ReadFile(filepath.Join("..", "..", "waveform", "testdata", "ramp.mp3"))
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(f.root, "shared", "song.mp3"), data, 0o644); err != nil {
t.Fatal(err)
}
}
// untilPeaks asks again, as the page does, until the answer is not "working", and gives back the last one.
func untilPeaks(t *testing.T, ask func() resp) resp {
t.Helper()
for range 40 {
r := ask()
if r.Code != http.StatusAccepted {
return r
}
time.Sleep(250 * time.Millisecond)
}
t.Fatal("the shape was never ready")
return resp{}
}
func TestAFriendReadsThePeaksOfASharedTrackOnly(t *testing.T) {
f := newPeerFixture(t)
f.befriend(t)
f.share(t, f.shared, true)
shared := strconv.FormatInt(f.track["Shared Song"], 10)
private := strconv.FormatInt(f.track["Private Song"], 10)
// The files of the fixture are not audio: the friend is told so, in words.
r := f.get(t, "/tracks/"+shared+"/peaks")
if r.Code != 202 && !(r.Code == 404 && errCode(r) == "waveform_unavailable") {
t.Fatalf("a file that is not audio: %d %v", r.Code, r.Body)
}
r = untilPeaks(t, func() resp { return f.get(t, "/tracks/"+shared+"/peaks") })
if r.Code != 404 || errCode(r) != "waveform_unavailable" {
t.Errorf("a file that is not audio: %d %v", r.Code, r.Body)
}
f.realAudio(t)
r = untilPeaks(t, func() resp { return f.get(t, "/tracks/"+shared+"/peaks") })
if r.Code != 200 {
t.Fatalf("a shared track: %d %v", r.Code, r.Body)
}
sameKeys(t, "peaks", r.Body, "count", "peaks")
if r.Body["count"] != float64(120) || len(r.Body["peaks"].([]any)) != 120 {
t.Errorf("count = %v", r.Body["count"])
}
if r := f.get(t, "/tracks/"+private+"/peaks"); r.Code != 404 || errCode(r) != "track_not_found" {
t.Errorf("a track that is not shared: %d %v", r.Code, r.Body)
}
if rec := f.serve(f.signed("GET", "/tracks/"+shared+"/peaks", func(r *http.Request) { r.Header.Del(federation.HeaderSignature) })); rec.Code != 401 {
t.Errorf("without a signature: %d", rec.Code)
}
}
func TestAListenerSeesThePeaksOfAFriendsTrackThroughThisServer(t *testing.T) {
f := newBrowseFixture(t)
track := f.sharedTrack(t)
path := "/friends/" + f.friendID + "/tracks/" + track + "/peaks"
if rec := f.listen(path, func(r *http.Request) { r.Header.Del("Authorization") }); rec.Code != 401 {
t.Errorf("without a login: %d", rec.Code)
}
r := untilPeaks(t, func() resp { return f.get(t, path) })
if r.Code != 404 || errCode(r) != "waveform_unavailable" {
t.Errorf("a file that is not audio: %d %v", r.Code, r.Body)
}
f.p.realAudio(t)
r = untilPeaks(t, func() resp { return f.get(t, path) })
if r.Code != 200 {
t.Fatalf("peaks: %d %v", r.Code, r.Body)
}
sameKeys(t, "peaks", r.Body, "count", "peaks")
if r.Body["count"] != float64(120) {
t.Errorf("count = %v", r.Body["count"])
}
if r := f.get(t, "/friends/"+f.friendID+"/tracks/999999/peaks"); r.Code != 404 || errCode(r) != "track_not_found" {
t.Errorf("a track the friend does not have: %d %v", r.Code, r.Body)
}
if r := f.get(t, "/friends/999/tracks/"+track+"/peaks"); r.Code != 404 || errCode(r) != "friend_not_found" {
t.Errorf("a friend that is not there: %d %v", r.Code, r.Body)
}
}
func TestWhatAFriendSendsAsPeaksIsCheckedBeforeItIsPassedOn(t *testing.T) {
for name, tc := range map[string]struct {
body string
ok bool
}{
"good, with something added": {`{"count":3,"peaks":[0,128,255],"path":"/srv/music/x"}`, true},
"the count is not the length": {`{"count":4,"peaks":[0,128,255]}`, false},
"a level over 255": {`{"count":1,"peaks":[256]}`, false},
"a level under 0": {`{"count":1,"peaks":[-1]}`, false},
"no levels": {`{"count":0,"peaks":[]}`, false},
"far too many": {`{"count":1,"peaks":[` + manyLevels(5000) + `]}`, false},
"html": {`<html>hello</html>`, false},
"empty": {``, false},
} {
h, _ := newTestEnvDB(t, func(d *Deps, db *bun.DB) {
d.Federation = crafted{federationService: federation.NewService(storage.NewFederationRepo(db), federation.NewClient()), body: tc.body}
})
tok := registerAndLogin(t, h)
r := do(t, h, "GET", "/api/v1/friends/1/tracks/1/peaks", tok, nil)
if tc.ok {
if r.Code != 200 {
t.Errorf("%s: %d %v", name, r.Code, r.Body)
continue
}
sameKeys(t, name, r.Body, "count", "peaks")
} else if r.Code != http.StatusBadGateway || errCode(r) != "friend_unreachable" {
t.Errorf("%s: %d %v", name, r.Code, r.Body)
}
}
}
func manyLevels(n int) string {
out := make([]byte, 0, n*2)
for i := range n {
if i > 0 {
out = append(out, ',')
}
out = append(out, '1')
}
return string(out)
}

View file

@ -235,6 +235,8 @@ func (c crafted) Browse(context.Context, int64, string, int64, url.Values) ([]by
return []byte(c.body), nil
}
func (c crafted) Peaks(context.Context, int64, int64) ([]byte, error) { return []byte(c.body), nil }
func TestWhatAFriendSendsIsCheckedBeforeItIsPassedOn(t *testing.T) {
h, _ := newTestEnvDB(t, func(d *Deps, db *bun.DB) {
d.Federation = crafted{

View file

@ -32,6 +32,7 @@ type federationService interface {
ActiveFriends(ctx context.Context) ([]federation.Friend, error)
Browse(ctx context.Context, friendID int64, resource string, id int64, query url.Values) ([]byte, error)
OpenMedia(ctx context.Context, friendID int64, kind string, id int64, query url.Values, in http.Header) (*federation.Media, error)
Peaks(ctx context.Context, friendID, trackID int64) ([]byte, error)
}
// federationHandlers are the admin routes that set up federation and its friends, and the one public route

View file

@ -81,6 +81,56 @@ func (h *friendsHandlers) fetch(c *gin.Context, resource string, withID bool) ([
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")

View file

@ -34,6 +34,7 @@ func registerPeer(v1 *gin.RouterGroup, d Deps) {
peer.GET("/tracks/:id", cat.getTrack)
peer.GET("/albums/:id/cover", (&peerCoverHandlers{fed: d.Federation, catalog: d.PeerCatalog, covers: &coverHandlers{svc: d.PeerCovers}}).album)
peer.GET("/tracks/:id/peaks", (&waveformHandlers{svc: d.PeerWaveform}).peaks)
peer.GET("/tracks/:id/stream", (&peerStreamHandlers{fed: d.Federation, inner: &streamHandlers{svc: d.PeerStreams}}).stream)
}

View file

@ -39,6 +39,7 @@ type peerFixture struct {
track map[string]int64
friendID string
bytes map[string][]byte // what each file holds
root string // the folder of the libraries: one folder for each, with song.mp3 in it
nonce atomic.Int64
}
@ -63,6 +64,7 @@ func newPeerFixture(t *testing.T) *peerFixture {
f.admin = registerAndLogin(t, h)
root := t.TempDir()
f.root = root
repo := storage.NewLibraryRepo(db)
for _, l := range []struct {
name, title, album, artist string

View file

@ -227,7 +227,9 @@ type Deps struct {
// that were already built.
PeerCatalog catalogService
PeerStreams streamService
PeerCovers coverService
// PeerWaveform works out the shape of the tracks of the shared libraries, for a friend.
PeerWaveform waveformService
PeerCovers coverService
// The shape of a track, for the seek bar.
Waveform waveformService
// Web is the built web app, served on / and for its own links. It is optional: with none (a build
@ -334,6 +336,7 @@ func NewRouter(d Deps) *gin.Engine {
protected.GET("/friends/:friend/albums/:id", relayOne[albumJSON](fr, "albums"))
protected.GET("/friends/:friend/tracks", relayPage[trackJSON](fr, "tracks"))
protected.GET("/friends/:friend/tracks/:id", relayOne[trackJSON](fr, "tracks"))
protected.GET("/friends/:friend/tracks/:id/peaks", fr.peaks)
protected.GET("/wishlist", fb.list(feedback.Wishlist))
protected.PUT("/wishlist/:id", fb.add(feedback.Wishlist))
protected.DELETE("/wishlist/:id", fb.remove(feedback.Wishlist))

View file

@ -3474,6 +3474,48 @@ paths:
application/json:
schema: {$ref: '#/components/schemas/Error'}
/peer/tracks/{id}/peaks:
parameters:
- {$ref: '#/components/parameters/Id'}
get:
tags: [Federation]
operationId: peerGetTrackPeaks
summary: The shape of a track of the shared libraries (called by a friend)
description: |
How loud the track is along its length, as `GET /tracks/{id}/peaks` gives it, for a track that lives in a shared
library, so that a friend's seek bar can draw it. The first request starts the work in the background and answers
`202` with `Retry-After`; ask again then. A track that is only in libraries that are not shared is `track_not_found`;
a file that cannot be decoded is `waveform_unavailable`.
security: [{friendSignature: []}]
responses:
'200':
description: The shape.
content:
application/json:
schema: {$ref: '#/components/schemas/Peaks'}
'202':
description: The shape is being worked out. Ask again after `Retry-After` seconds.
headers:
Retry-After:
description: Seconds to wait.
schema: {type: integer}
content:
application/json:
schema:
type: object
additionalProperties: false
required: [status]
properties:
status: {type: string, enum: [working]}
'400': {$ref: '#/components/responses/InvalidInput'}
'401': {$ref: '#/components/responses/FriendUnauthorized'}
'403': {$ref: '#/components/responses/FriendNotApproved'}
'404':
description: No such track among the shared libraries (`track_not_found`), its file is not available (`file_missing`), its shape cannot be worked out (`waveform_unavailable`), or federation is off (`not_found`).
content:
application/json:
schema: {$ref: '#/components/schemas/Error'}
/peer/tracks/{id}/stream:
parameters:
- {$ref: '#/components/parameters/Id'}
@ -3748,6 +3790,52 @@ paths:
application/json:
schema: {$ref: '#/components/schemas/Error'}
/friends/{friend}/tracks/{id}/peaks:
parameters:
- {name: friend, in: path, required: true, description: The id from `GET /friends`., schema: {type: integer, format: int64, minimum: 1}}
- {$ref: '#/components/parameters/Id'}
get:
tags: [Friends]
operationId: getFriendTrackPeaks
summary: The shape of a track of a friend, for the seek bar
description: |
How loud a track that a friend shares is along its length, as `GET /tracks/{id}/peaks` gives it for a local track.
This server asks the friend, signed, and passes the answer on once it has checked that it is a list of 1 to 1000
levels from 0 to 255; anything else is `502` (`friend_unreachable`). The friend works the shape out the first time and
answers `202` with `Retry-After`: ask again then. A file the friend cannot decode is `waveform_unavailable`. The track
id is the friend's own.
security: [{bearerAuth: []}]
responses:
'200':
description: The shape.
content:
application/json:
schema: {$ref: '#/components/schemas/Peaks'}
'202':
description: The friend is working the shape out. Ask again after `Retry-After` seconds.
headers:
Retry-After:
description: Seconds to wait.
schema: {type: integer}
content:
application/json:
schema:
type: object
additionalProperties: false
required: [status]
properties:
status: {type: string, enum: [working]}
'400': {$ref: '#/components/responses/InvalidInput'}
'401': {$ref: '#/components/responses/Unauthorized'}
'404':
description: No such friend, or it is not active (`friend_not_found`), the friend has no such track among what it shares (`track_not_found`), or its shape cannot be worked out (`waveform_unavailable`).
content:
application/json:
schema: {$ref: '#/components/schemas/Error'}
'409': {$ref: '#/components/responses/FriendGone'}
'429': {$ref: '#/components/responses/FriendBusy'}
'502': {$ref: '#/components/responses/FriendUnreachable'}
/friends/{friend}/tracks/{id}/stream:
parameters:
- {name: friend, in: path, required: true, description: The id from `GET /friends`., schema: {type: integer, format: int64, minimum: 1}}

View file

@ -155,3 +155,39 @@ func TestWhatAFriendAnswersIsToldInOurOwnTerms(t *testing.T) {
}
}
}
func TestThePeaksOfAFriendsTrackAreAskedForSignedAndTheAnswerIsToldInOurOwnTerms(t *testing.T) {
ctx := context.Background()
s, _, remote, id := browsing(t)
remote.body = `{"count":2,"peaks":[1,2]}`
body, err := s.Peaks(ctx, id, 7)
if err != nil || string(body) != remote.body {
t.Fatalf("Peaks = %q, %v", body, err)
}
if remote.uri != "/api/v1/peer/tracks/7/peaks" || remote.addr != "https://bruno.example.org" || remote.auth.KeyID == "" {
t.Errorf("asked %q at %q as %q", remote.uri, remote.addr, remote.auth.KeyID)
}
for _, tc := range []struct {
status int
body string
want error
}{
{202, `{"status":"working"}`, ErrWorking},
{404, `{"error":{"code":"waveform_unavailable"}}`, ErrNoWaveform},
{404, `{"error":{"code":"track_not_found"}}`, ErrNotFoundThere},
{404, `{"error":{"code":"file_missing"}}`, ErrNotFriend},
{429, ``, ErrTooMany},
{500, `oops`, ErrUnreachable},
} {
remote.status, remote.body = tc.status, tc.body
if _, err := s.Peaks(ctx, id, 7); !errors.Is(err, tc.want) {
t.Errorf("%d %q: err = %v, want %v", tc.status, tc.body, err, tc.want)
}
}
if _, err := s.Peaks(ctx, id, 0); !errors.Is(err, ErrInvalidInput) {
t.Errorf("track 0: %v, want ErrInvalidInput", err)
}
if _, err := s.Peaks(ctx, id+99, 7); !errors.Is(err, ErrFriendMissing) {
t.Errorf("a friend that is not there: %v, want ErrFriendMissing", err)
}
}

View file

@ -39,6 +39,10 @@ var (
ErrTooManyStreams = errors.New("this friend already has as many streams open as allowed")
// ErrNotFoundThere: the friend has no such artist, album or track among what it shares.
ErrNotFoundThere = errors.New("the friend has no such item")
// ErrWorking: the friend is working out the shape of the track; ask again in a moment.
ErrWorking = errors.New("the friend is working out the waveform")
// ErrNoWaveform: the friend cannot work out the shape of this track (a format it does not decode).
ErrNoWaveform = errors.New("the friend has no waveform for this track")
)
// Defaults of the limits a friend is held to, and what they may be set to.

View file

@ -668,17 +668,6 @@ func (s *Service) Browse(ctx context.Context, friendID int64, resource string, i
if !browseResources[resource] || id < 0 {
return nil, fmt.Errorf("%w: there is no such thing to browse", ErrInvalidInput)
}
set, err := s.load(ctx)
if err != nil {
return nil, err
}
if !set.Enabled || set.PublicKey == nil {
return nil, ErrFriendMissing
}
f, err := s.store.Friend(ctx, friendID)
if err != nil || f.State != Active {
return nil, ErrFriendMissing
}
uri := "/api/v1/peer/" + resource
if id > 0 {
uri += "/" + strconv.FormatInt(id, 10)
@ -693,7 +682,7 @@ func (s *Service) Browse(ctx context.Context, friendID int64, resource string, i
uri += "?" + keep.Encode()
}
}
status, body, err := s.remote.Get(ctx, f.Address, uri, Auth{KeyID: KeyID(set.PublicKey), Key: set.PrivateKey})
status, body, err := s.ask(ctx, friendID, uri)
if err != nil {
return nil, err
}
@ -703,6 +692,59 @@ func (s *Service) Browse(ctx context.Context, friendID int64, resource string, i
return nil, errorFor(status, body)
}
// ask sends an active friend a signed GET and gives back what it answered.
func (s *Service) ask(ctx context.Context, friendID int64, uri string) (int, []byte, error) {
set, err := s.load(ctx)
if err != nil {
return 0, nil, err
}
if !set.Enabled || set.PublicKey == nil {
return 0, nil, ErrFriendMissing
}
f, err := s.store.Friend(ctx, friendID)
if err != nil || f.State != Active {
return 0, nil, ErrFriendMissing
}
return s.remote.Get(ctx, f.Address, uri, Auth{KeyID: KeyID(set.PublicKey), Key: set.PrivateKey})
}
// Peaks asks an active friend for the shape of one of its tracks (how loud it is along its length, for the seek bar).
// The friend works it out the first time it is asked, and says so: ErrWorking, and the page asks again.
// ErrNoWaveform when the friend cannot read the file.
func (s *Service) Peaks(ctx context.Context, friendID, trackID int64) ([]byte, error) {
if trackID <= 0 {
return nil, fmt.Errorf("%w: there is no such track", ErrInvalidInput)
}
status, body, err := s.ask(ctx, friendID, "/api/v1/peer/tracks/"+strconv.FormatInt(trackID, 10)+"/peaks")
if err != nil {
return nil, err
}
switch status {
case http.StatusOK:
return body, nil
case http.StatusAccepted:
return nil, ErrWorking
case http.StatusNotFound:
if codeOf(body) == "waveform_unavailable" {
return nil, ErrNoWaveform
}
}
return nil, errorFor(status, body)
}
// codeOf is the error code in the body of a friend's answer, or nothing when it has none.
func codeOf(body []byte) string {
var e struct {
Error struct {
Code string `json:"code"`
} `json:"error"`
}
if json.Unmarshal(body, &e) != nil {
return ""
}
return e.Error.Code
}
// errorFor tells what a friend's answer other than a success means, in this server's own terms.
func errorFor(status int, body []byte) error {
switch status {
@ -713,12 +755,7 @@ func errorFor(status int, body []byte) error {
case http.StatusUnauthorized:
return ErrNotFriend
case http.StatusNotFound:
var e struct {
Error struct {
Code string `json:"code"`
} `json:"error"`
}
if json.Unmarshal(body, &e) == nil && strings.HasSuffix(e.Error.Code, "_not_found") {
if strings.HasSuffix(codeOf(body), "_not_found") {
return ErrNotFoundThere
}
return ErrNotFriend // federation is off there, or it is not a Sonda server that knows us