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
20 changed files with 862 additions and 33 deletions

View file

@ -320,6 +320,7 @@ func run() error {
Federation: federation.NewService(storage.NewFederationRepo(db), federation.NewClient()), Federation: federation.NewService(storage.NewFederationRepo(db), federation.NewClient()),
PeerCatalog: catalog.NewService(storage.NewSharedCatalogRepo(db)), PeerCatalog: catalog.NewService(storage.NewSharedCatalogRepo(db)),
PeerStreams: streaming.NewService(libraryRepo.Shared()), PeerStreams: streaming.NewService(libraryRepo.Shared()),
PeerWaveform: waveform.NewService(storage.NewWaveformRepo(db), streaming.NewService(libraryRepo.Shared())),
PeerCovers: images.StoredOnly{Service: pictures}, PeerCovers: images.StoredOnly{Service: pictures},
Waveform: waveform.NewService(storage.NewWaveformRepo(db), streaming.NewService(libraryRepo)), Waveform: waveform.NewService(storage.NewWaveformRepo(db), streaming.NewService(libraryRepo)),
Web: webui.FS(), Web: webui.FS(),

View file

@ -113,6 +113,7 @@ func newTestEnvDB(t *testing.T, mutate func(*Deps, *bun.DB)) (http.Handler, *bun
libRepo := storage.NewLibraryRepo(db) libRepo := storage.NewLibraryRepo(db)
deps.PeerCatalog = catalog.NewService(storage.NewSharedCatalogRepo(db)) deps.PeerCatalog = catalog.NewService(storage.NewSharedCatalogRepo(db))
deps.PeerStreams = streaming.NewService(libRepo.Shared()) 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)) deps.Waveform = waveform.NewService(storage.NewWaveformRepo(db), streaming.NewService(libRepo))
feedbackSvc := feedback.NewService(storage.NewFeedbackRepo(db)) feedbackSvc := feedback.NewService(storage.NewFeedbackRepo(db))
deps.Feedback = feedbackSvc 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) 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/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. // 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") 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 { 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) 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") 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" 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") c.expect(c.call("GET", cover, token, nil), 404, "a cover that is not built there yet", "cover_not_found")
var theirAlbum int64 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 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) { func TestWhatAFriendSendsIsCheckedBeforeItIsPassedOn(t *testing.T) {
h, _ := newTestEnvDB(t, func(d *Deps, db *bun.DB) { h, _ := newTestEnvDB(t, func(d *Deps, db *bun.DB) {
d.Federation = crafted{ d.Federation = crafted{

View file

@ -32,6 +32,7 @@ type federationService interface {
ActiveFriends(ctx context.Context) ([]federation.Friend, error) ActiveFriends(ctx context.Context) ([]federation.Friend, error)
Browse(ctx context.Context, friendID int64, resource string, id int64, query url.Values) ([]byte, 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) 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 // 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 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) { func badAnswer(c *gin.Context) {
_ = c.Error(errors.New("a friend sent an answer that is not a catalogue page")) _ = 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") 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("/tracks/:id", cat.getTrack)
peer.GET("/albums/:id/cover", (&peerCoverHandlers{fed: d.Federation, catalog: d.PeerCatalog, covers: &coverHandlers{svc: d.PeerCovers}}).album) 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) 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 track map[string]int64
friendID string friendID string
bytes map[string][]byte // what each file holds 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 nonce atomic.Int64
} }
@ -63,6 +64,7 @@ func newPeerFixture(t *testing.T) *peerFixture {
f.admin = registerAndLogin(t, h) f.admin = registerAndLogin(t, h)
root := t.TempDir() root := t.TempDir()
f.root = root
repo := storage.NewLibraryRepo(db) repo := storage.NewLibraryRepo(db)
for _, l := range []struct { for _, l := range []struct {
name, title, album, artist string name, title, album, artist string

View file

@ -227,7 +227,9 @@ type Deps struct {
// that were already built. // that were already built.
PeerCatalog catalogService PeerCatalog catalogService
PeerStreams streamService 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. // The shape of a track, for the seek bar.
Waveform waveformService Waveform waveformService
// Web is the built web app, served on / and for its own links. It is optional: with none (a build // 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/albums/:id", relayOne[albumJSON](fr, "albums"))
protected.GET("/friends/:friend/tracks", relayPage[trackJSON](fr, "tracks")) 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", relayOne[trackJSON](fr, "tracks"))
protected.GET("/friends/:friend/tracks/:id/peaks", fr.peaks)
protected.GET("/wishlist", fb.list(feedback.Wishlist)) protected.GET("/wishlist", fb.list(feedback.Wishlist))
protected.PUT("/wishlist/:id", fb.add(feedback.Wishlist)) protected.PUT("/wishlist/:id", fb.add(feedback.Wishlist))
protected.DELETE("/wishlist/:id", fb.remove(feedback.Wishlist)) protected.DELETE("/wishlist/:id", fb.remove(feedback.Wishlist))

View file

@ -3474,6 +3474,48 @@ paths:
application/json: application/json:
schema: {$ref: '#/components/schemas/Error'} 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: /peer/tracks/{id}/stream:
parameters: parameters:
- {$ref: '#/components/parameters/Id'} - {$ref: '#/components/parameters/Id'}
@ -3748,6 +3790,52 @@ paths:
application/json: application/json:
schema: {$ref: '#/components/schemas/Error'} 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: /friends/{friend}/tracks/{id}/stream:
parameters: parameters:
- {name: friend, in: path, required: true, description: The id from `GET /friends`., schema: {type: integer, format: int64, minimum: 1}} - {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") 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: the friend has no such artist, album or track among what it shares.
ErrNotFoundThere = errors.New("the friend has no such item") 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. // 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 { if !browseResources[resource] || id < 0 {
return nil, fmt.Errorf("%w: there is no such thing to browse", ErrInvalidInput) 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 uri := "/api/v1/peer/" + resource
if id > 0 { if id > 0 {
uri += "/" + strconv.FormatInt(id, 10) uri += "/" + strconv.FormatInt(id, 10)
@ -693,7 +682,7 @@ func (s *Service) Browse(ctx context.Context, friendID int64, resource string, i
uri += "?" + keep.Encode() 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 { if err != nil {
return nil, err return nil, err
} }
@ -703,6 +692,59 @@ func (s *Service) Browse(ctx context.Context, friendID int64, resource string, i
return nil, errorFor(status, body) 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. // 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 { func errorFor(status int, body []byte) error {
switch status { switch status {
@ -713,12 +755,7 @@ func errorFor(status int, body []byte) error {
case http.StatusUnauthorized: case http.StatusUnauthorized:
return ErrNotFriend return ErrNotFriend
case http.StatusNotFound: case http.StatusNotFound:
var e struct { if strings.HasSuffix(codeOf(body), "_not_found") {
Error struct {
Code string `json:"code"`
} `json:"error"`
}
if json.Unmarshal(body, &e) == nil && strings.HasSuffix(e.Error.Code, "_not_found") {
return ErrNotFoundThere return ErrNotFoundThere
} }
return ErrNotFriend // federation is off there, or it is not a Sonda server that knows us return ErrNotFriend // federation is off there, or it is not a Sonda server that knows us

View file

@ -41,10 +41,37 @@ test('a track whose shape cannot be had is left alone: no shape, and no asking a
expect(calls).toHaveLength(1) expect(calls).toHaveLength(1)
}) })
test('it asks nothing when it is told not to (a friend’s track, or nothing playing)', async () => { test('it asks nothing when it is told not to (nothing playing)', async () => {
const { calls } = mockFetch({ 'GET /api/v1/tracks/7/peaks': () => shape }) const { calls } = mockFetch({ 'GET /api/v1/tracks/7/peaks': () => shape })
const { result } = renderHook(() => usePeaks(7, { enabled: false }), { wrapper }) const { result } = renderHook(() => usePeaks(7, { enabled: false }), { wrapper })
await new Promise((r) => setTimeout(r, 40)) await new Promise((r) => setTimeout(r, 40))
expect(result.current).toBeUndefined() expect(result.current).toBeUndefined()
expect(calls).toHaveLength(0) expect(calls).toHaveLength(0)
}) })
test('the shape of a friend’s track is asked of the friend, and is not the shape of the local track with the same id', async () => {
const theirs = { count: 2, peaks: [255, 0] }
const { calls } = mockFetch({
'GET /api/v1/friends/3/tracks/7/peaks': () => theirs,
'GET /api/v1/tracks/7/peaks': () => shape,
})
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
const shared = ({ children }: { children: ReactNode }) => <QueryClientProvider client={client}>{children}</QueryClientProvider>
const friend = renderHook(() => usePeaks(7, { friend: 3 }), { wrapper: shared })
const local = renderHook(() => usePeaks(7), { wrapper: shared })
await waitFor(() => expect(friend.result.current).toEqual([255, 0]))
await waitFor(() => expect(local.result.current).toEqual([10, 200, 50]))
expect(calls.map((c) => c.key).sort()).toEqual(['GET /api/v1/friends/3/tracks/7/peaks', 'GET /api/v1/tracks/7/peaks'])
})
test('a friend’s track is worked out by the friend: it is asked again until it is there', async () => {
let asked = 0
mockFetch({
'GET /api/v1/friends/3/tracks/7/peaks': () => {
asked++
return asked < 2 ? new Response(JSON.stringify({ status: 'working' }), { status: 202, headers: { 'Content-Type': 'application/json' } }) : shape
},
})
const { result } = renderHook(() => usePeaks(7, { friend: 3, pollMs: 10 }), { wrapper })
await waitFor(() => expect(result.current).toEqual([10, 200, 50]))
})

View file

@ -14,19 +14,20 @@ interface Shape {
const POLL_MS = 3000 const POLL_MS = 3000
/** /**
* The shape of a local track, from 0 to 255 for each of its bars: how loud it is along its length. The server works it out * The shape of a track, from 0 to 255 for each of its bars: how loud it is along its length. The server works it out
* the first time it is asked for, so until then this is `undefined` and the question is asked again every few seconds. * the first time it is asked for, so until then this is `undefined` and the question is asked again every few seconds.
* A track whose shape cannot be had stays without one. A friend's track has none: pass `enabled: false`. * A track whose shape cannot be had stays without one. For a friend's track pass the `friend`: this server asks the
* friend's, and the track id is the friend's own.
*/ */
export function usePeaks(trackId: number | null, opts: { enabled?: boolean; pollMs?: number } = {}): number[] | undefined { export function usePeaks(trackId: number | null, opts: { friend?: number; enabled?: boolean; pollMs?: number } = {}): number[] | undefined {
const { enabled = true, pollMs = POLL_MS } = opts const { friend, enabled = true, pollMs = POLL_MS } = opts
const query = useQuery({ const query = useQuery({
queryKey: ['peaks', trackId], queryKey: ['peaks', friend ?? null, trackId],
enabled: enabled && trackId !== null, enabled: enabled && trackId !== null,
retry: false, retry: false,
// A shape does not change while the file does not: keep it for as long as the page lives. // A shape does not change while the file does not: keep it for as long as the page lives.
staleTime: Infinity, staleTime: Infinity,
queryFn: () => api.get<Shape | Working>(`/tracks/${trackId}/peaks`), queryFn: () => api.get<Shape | Working>(friend === undefined ? `/tracks/${trackId}/peaks` : `/friends/${friend}/tracks/${trackId}/peaks`),
refetchInterval: (q) => ('status' in (q.state.data ?? {}) ? pollMs : false), refetchInterval: (q) => ('status' in (q.state.data ?? {}) ? pollMs : false),
}) })
if (query.error instanceof ApiError || query.data === undefined || 'status' in query.data) return undefined if (query.error instanceof ApiError || query.data === undefined || 'status' in query.data) return undefined

View file

@ -1792,6 +1792,33 @@ export interface paths {
patch?: never; patch?: never;
trace?: never; trace?: never;
}; };
"/tracks/{id}/peaks": {
parameters: {
query?: never;
header?: never;
path: {
id: components["parameters"]["Id"];
};
cookie?: never;
};
/**
* The shape of a track, for the seek bar
* @description How loud the track is along its length, as 120 levels from 0 to 255: the loudest part is 255 whatever the volume of
* the track. The server finds it by decoding the file (MP3 and FLAC, no extra program needed), which takes a few
* seconds, so the first request for a track starts the work in the background and answers `202` with `Retry-After`;
* ask again then. It is done once for each file and worked out again if the size or the date of the file change. One
* track is worked out at a time. A file that cannot be decoded (another format, or damaged) is `waveform_unavailable`,
* and that is kept too, so it is not tried at every request.
*/
get: operations["getTrackPeaks"];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/tracks/{id}/stream": { "/tracks/{id}/stream": {
parameters: { parameters: {
query?: never; query?: never;
@ -2373,6 +2400,31 @@ export interface paths {
patch?: never; patch?: never;
trace?: never; trace?: never;
}; };
"/peer/tracks/{id}/peaks": {
parameters: {
query?: never;
header?: never;
path: {
id: components["parameters"]["Id"];
};
cookie?: never;
};
/**
* 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`.
*/
get: operations["peerGetTrackPeaks"];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/peer/tracks/{id}/stream": { "/peer/tracks/{id}/stream": {
parameters: { parameters: {
query?: never; query?: never;
@ -2555,6 +2607,94 @@ export interface paths {
patch?: never; patch?: never;
trace?: never; trace?: never;
}; };
"/friends/{friend}/tracks/{id}/peaks": {
parameters: {
query?: never;
header?: never;
path: {
/** @description The id from `GET /friends`. */
friend: number;
id: components["parameters"]["Id"];
};
cookie?: never;
};
/**
* 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.
*/
get: operations["getFriendTrackPeaks"];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/friends/{friend}/tracks/{id}/stream": {
parameters: {
query?: never;
header?: never;
path: {
/** @description The id from `GET /friends`. */
friend: number;
id: components["parameters"]["Id"];
};
cookie?: never;
};
/**
* Stream a track of a friend
* @description The audio of a track that a friend shares, passed on by this server: it asks the friend with a request signed by its
* own key and sends the bytes on, so the listener's browser talks to this server only, and the friend sees this server
* and nothing of the listener. `Range` and the conditional headers are passed to the friend, so a player can seek.
* Only audio is passed on, with `Content-Type`, `Content-Length`, `Content-Range`, `Accept-Ranges` and `Last-Modified`
* and nothing else of what the friend sends. Streaming never records a listen here, and a friend's track never counts
* for taste. The track id is the friend's own.
*
* Like the stream of a local track, this accepts the access token as the `access_token` query parameter. A header, when
* present, always wins. A friend that already has as many streams open as its admin allows is a `429`
* (`friend_busy`).
*/
get: operations["streamFriendTrack"];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/friends/{friend}/albums/{id}/cover": {
parameters: {
query?: never;
header?: never;
path: {
/** @description The id from `GET /friends`. */
friend: number;
id: components["parameters"]["Id"];
};
cookie?: never;
};
/**
* The cover of an album of a friend
* @description The cover of an album that a friend shares, passed on like the stream. Only a JPEG is passed on. The friend gives a
* cover only once it was built on its server from the audio files of the album, so an album may have none yet
* (`cover_not_found`): the listener then sees the usual placeholder. Accepts the access token as the `access_token`
* query parameter, like the cover of a local album.
*/
get: operations["getFriendAlbumCover"];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
} }
export type webhooks = Record<string, never>; export type webhooks = Record<string, never>;
export interface components { export interface components {
@ -3632,6 +3772,12 @@ export interface components {
*/ */
bytes: number; bytes: number;
}; };
Peaks: {
/** @description How many levels there are (120). */
count: number;
/** @description From the start of the track to its end. */
peaks: number[];
};
FriendRef: { FriendRef: {
/** /**
* Format: int64 * Format: int64
@ -6826,6 +6972,53 @@ export interface operations {
}; };
}; };
}; };
getTrackPeaks: {
parameters: {
query?: never;
header?: never;
path: {
id: components["parameters"]["Id"];
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description The shape. */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Peaks"];
};
};
/** @description The shape is being worked out. Ask again after `Retry-After` seconds. */
202: {
headers: {
/** @description Seconds to wait. */
"Retry-After"?: number;
[name: string]: unknown;
};
content: {
"application/json": {
/** @enum {string} */
status: "working";
};
};
};
400: components["responses"]["InvalidInput"];
401: components["responses"]["Unauthorized"];
/** @description No such track (`track_not_found`), its file is not available (`file_missing`), or its shape cannot be worked out (`waveform_unavailable`). */
404: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
streamTrack: { streamTrack: {
parameters: { parameters: {
query?: never; query?: never;
@ -7882,6 +8075,54 @@ export interface operations {
}; };
}; };
}; };
peerGetTrackPeaks: {
parameters: {
query?: never;
header?: never;
path: {
id: components["parameters"]["Id"];
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description The shape. */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Peaks"];
};
};
/** @description The shape is being worked out. Ask again after `Retry-After` seconds. */
202: {
headers: {
/** @description Seconds to wait. */
"Retry-After"?: number;
[name: string]: unknown;
};
content: {
"application/json": {
/** @enum {string} */
status: "working";
};
};
};
400: components["responses"]["InvalidInput"];
401: components["responses"]["FriendUnauthorized"];
403: components["responses"]["FriendNotApproved"];
/** @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`). */
404: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
peerStreamTrack: { peerStreamTrack: {
parameters: { parameters: {
query?: never; query?: never;
@ -8242,4 +8483,183 @@ export interface operations {
502: components["responses"]["FriendUnreachable"]; 502: components["responses"]["FriendUnreachable"];
}; };
}; };
getFriendTrackPeaks: {
parameters: {
query?: never;
header?: never;
path: {
/** @description The id from `GET /friends`. */
friend: number;
id: components["parameters"]["Id"];
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description The shape. */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Peaks"];
};
};
/** @description The friend is working the shape out. Ask again after `Retry-After` seconds. */
202: {
headers: {
/** @description Seconds to wait. */
"Retry-After"?: number;
[name: string]: unknown;
};
content: {
"application/json": {
/** @enum {string} */
status: "working";
};
};
};
400: components["responses"]["InvalidInput"];
401: components["responses"]["Unauthorized"];
/** @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`). */
404: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
409: components["responses"]["FriendGone"];
429: components["responses"]["FriendBusy"];
502: components["responses"]["FriendUnreachable"];
};
};
streamFriendTrack: {
parameters: {
query?: never;
header?: {
/** @description A byte range, for example `bytes=0-99`. */
Range?: string;
"If-Modified-Since"?: string;
};
path: {
/** @description The id from `GET /friends`. */
friend: number;
id: components["parameters"]["Id"];
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description The whole file. */
200: {
headers: {
"Accept-Ranges": components["headers"]["AcceptRanges"];
"Content-Length": components["headers"]["ContentLength"];
"Last-Modified": components["headers"]["LastModified"];
[name: string]: unknown;
};
content: {
"audio/mpeg": string;
"audio/flac": string;
};
};
/** @description The requested byte range. */
206: {
headers: {
/** @description The range sent and the size of the file, for example `bytes 0-99/40635`. */
"Content-Range"?: string;
[name: string]: unknown;
};
content: {
"audio/mpeg": string;
"audio/flac": string;
};
};
/** @description Not modified since `If-Modified-Since`. */
304: {
headers: {
[name: string]: unknown;
};
content?: never;
};
400: components["responses"]["InvalidInput"];
401: components["responses"]["Unauthorized"];
/** @description No such friend, or it is not active (`friend_not_found`), or the friend has no such track among what it shares (`track_not_found`). */
404: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
409: components["responses"]["FriendGone"];
/** @description The range cannot be satisfied. */
416: {
headers: {
/** @description `bytes *\/<size of the file>`. */
"Content-Range"?: string;
[name: string]: unknown;
};
content?: never;
};
429: components["responses"]["FriendBusy"];
502: components["responses"]["FriendUnreachable"];
};
};
getFriendAlbumCover: {
parameters: {
query?: {
/** @description `small` or `large`. Large when absent. */
size?: "small" | "large";
};
header?: {
"If-None-Match"?: string;
};
path: {
/** @description The id from `GET /friends`. */
friend: number;
id: components["parameters"]["Id"];
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description The cover. */
200: {
headers: {
ETag: components["headers"]["ETag"];
"Cache-Control": components["headers"]["CacheControl"];
"Content-Length": components["headers"]["ContentLength"];
[name: string]: unknown;
};
content: {
"image/jpeg": string;
};
};
/** @description Not modified since `If-None-Match`. */
304: {
headers: {
[name: string]: unknown;
};
content?: never;
};
400: components["responses"]["InvalidInput"];
401: components["responses"]["Unauthorized"];
/** @description No such friend, or it is not active (`friend_not_found`), or no such album or no cover built there yet (`cover_not_found`). */
404: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
409: components["responses"]["FriendGone"];
429: components["responses"]["FriendBusy"];
502: components["responses"]["FriendUnreachable"];
};
};
} }

View file

@ -26,7 +26,7 @@ function NowPlayingSeek({ track }: { track: QueuedTrack }) {
const durationMs = track.duration_ms const durationMs = track.duration_ms
const positionMs = usePlayer((s) => s.positionMs) const positionMs = usePlayer((s) => s.positionMs)
const seek = usePlayer((s) => s.seek) const seek = usePlayer((s) => s.seek)
const peaks = usePeaks(track.id, { enabled: track.friend === undefined }) const peaks = usePeaks(track.id, { friend: track.friend })
return ( return (
<div className="flex flex-col gap-1"> <div className="flex flex-col gap-1">
<Scrubber positionMs={positionMs} durationMs={durationMs} onSeek={seek} size="big" peaks={peaks} friend={track.friend !== undefined} /> <Scrubber positionMs={positionMs} durationMs={durationMs} onSeek={seek} size="big" peaks={peaks} friend={track.friend !== undefined} />

View file

@ -58,6 +58,7 @@ function renderBar(extra?: React.ReactNode) {
calls = mockFetch({ calls = mockFetch({
'GET /api/v1/friends': () => ({ friends: [{ id: 3, name: 'Anna' }] }), 'GET /api/v1/friends': () => ({ friends: [{ id: 3, name: 'Anna' }] }),
...Object.fromEntries([1, 2, 3, 4, 5].map((n) => [`GET /api/v1/tracks/${n}/peaks`, () => ({ count: 120, peaks: new Array(120).fill(100) })])), ...Object.fromEntries([1, 2, 3, 4, 5].map((n) => [`GET /api/v1/tracks/${n}/peaks`, () => ({ count: 120, peaks: new Array(120).fill(100) })])),
...Object.fromEntries([1, 2, 3, 4, 5].map((n) => [`GET /api/v1/friends/3/tracks/${n}/peaks`, () => ({ count: 120, peaks: new Array(120).fill(100) })])),
}).calls }).calls
return render( return render(
<QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}> <QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>
@ -439,10 +440,10 @@ test('the seek bar of a track of this server is the shape of the track', async (
expect(calls.some((c) => c.key === 'GET /api/v1/tracks/1/peaks')).toBe(true) expect(calls.some((c) => c.key === 'GET /api/v1/tracks/1/peaks')).toBe(true)
}) })
test('a friend’s track has a plain bar, and its shape is not asked for', async () => { test('the seek bar of a friend’s track is its shape too, asked of the friend', async () => {
act(() => usePlayer.getState().playTracks([theirs(1)])) act(() => usePlayer.getState().playTracks([theirs(1)]))
const { container } = renderBar() const { container } = renderBar()
await screen.findByLabelText('From Anna’s server') await waitFor(() => expect(container.querySelectorAll('footer [data-bar]').length).toBe(120))
expect(container.querySelectorAll('footer [data-bar]').length).toBe(64) expect(calls.some((c) => c.key === 'GET /api/v1/friends/3/tracks/1/peaks')).toBe(true)
expect(calls.some((c) => c.key.includes('/peaks'))).toBe(false) expect(calls.some((c) => c.key === 'GET /api/v1/tracks/1/peaks')).toBe(false)
}) })

View file

@ -36,8 +36,8 @@ function usePlayPauseKey() {
function PlayerSeek({ track }: { track: QueuedTrack | null }) { function PlayerSeek({ track }: { track: QueuedTrack | null }) {
const positionMs = usePlayer((s) => s.positionMs) const positionMs = usePlayer((s) => s.positionMs)
const seek = usePlayer((s) => s.seek) const seek = usePlayer((s) => s.seek)
// A friend's track has no shape here (the friend's server would have to work it out): its bar is flat. // A friend's track has its shape from the friend's server, which works it out the first time.
const peaks = usePeaks(track?.id ?? null, { enabled: track !== null && track.friend === undefined }) const peaks = usePeaks(track?.id ?? null, { friend: track?.friend })
return ( return (
<div className="player-seek flex w-full max-w-xl items-center gap-3 justify-self-center text-[13px] text-muted-foreground tabular-nums"> <div className="player-seek flex w-full max-w-xl items-center gap-3 justify-self-center text-[13px] text-muted-foreground tabular-nums">
<span>{formatTime(track ? positionMs : 0)}</span> <span>{formatTime(track ? positionMs : 0)}</span>