diff --git a/cmd/sondad/main.go b/cmd/sondad/main.go index 27df376..503628d 100644 --- a/cmd/sondad/main.go +++ b/cmd/sondad/main.go @@ -320,6 +320,7 @@ func run() error { Federation: federation.NewService(storage.NewFederationRepo(db), federation.NewClient()), PeerCatalog: catalog.NewService(storage.NewSharedCatalogRepo(db)), PeerStreams: streaming.NewService(libraryRepo.Shared()), + PeerWaveform: waveform.NewService(storage.NewWaveformRepo(db), streaming.NewService(libraryRepo.Shared())), PeerCovers: images.StoredOnly{Service: pictures}, Waveform: waveform.NewService(storage.NewWaveformRepo(db), streaming.NewService(libraryRepo)), Web: webui.FS(), diff --git a/internal/api/http/api_test.go b/internal/api/http/api_test.go index c0e8e60..89af5e5 100644 --- a/internal/api/http/api_test.go +++ b/internal/api/http/api_test.go @@ -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 diff --git a/internal/api/http/contract_test.go b/internal/api/http/contract_test.go index 837108b..51c4319 100644 --- a/internal/api/http/contract_test.go +++ b/internal/api/http/contract_test.go @@ -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 diff --git a/internal/api/http/friend_waveform_test.go b/internal/api/http/friend_waveform_test.go new file mode 100644 index 0000000..65f0ca8 --- /dev/null +++ b/internal/api/http/friend_waveform_test.go @@ -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": {`hello`, 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) +} diff --git a/internal/api/http/friends_test.go b/internal/api/http/friends_test.go index a44a10c..e6b1aa3 100644 --- a/internal/api/http/friends_test.go +++ b/internal/api/http/friends_test.go @@ -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{ diff --git a/internal/api/http/handlers_federation.go b/internal/api/http/handlers_federation.go index 2025d53..db10364 100644 --- a/internal/api/http/handlers_federation.go +++ b/internal/api/http/handlers_federation.go @@ -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 diff --git a/internal/api/http/handlers_friends.go b/internal/api/http/handlers_friends.go index 4538484..e686b7b 100644 --- a/internal/api/http/handlers_friends.go +++ b/internal/api/http/handlers_friends.go @@ -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") diff --git a/internal/api/http/handlers_peer.go b/internal/api/http/handlers_peer.go index efd18a0..838d2e1 100644 --- a/internal/api/http/handlers_peer.go +++ b/internal/api/http/handlers_peer.go @@ -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) } diff --git a/internal/api/http/peer_test.go b/internal/api/http/peer_test.go index 372a72b..5e1bba8 100644 --- a/internal/api/http/peer_test.go +++ b/internal/api/http/peer_test.go @@ -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 diff --git a/internal/api/http/router.go b/internal/api/http/router.go index 9ede41b..b0b86bd 100644 --- a/internal/api/http/router.go +++ b/internal/api/http/router.go @@ -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)) diff --git a/internal/api/openapi/openapi.yaml b/internal/api/openapi/openapi.yaml index f7c4820..7d015a3 100644 --- a/internal/api/openapi/openapi.yaml +++ b/internal/api/openapi/openapi.yaml @@ -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}} diff --git a/internal/federation/browse_test.go b/internal/federation/browse_test.go index f9be6ce..0d0a073 100644 --- a/internal/federation/browse_test.go +++ b/internal/federation/browse_test.go @@ -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) + } +} diff --git a/internal/federation/federation.go b/internal/federation/federation.go index f93080c..0510af7 100644 --- a/internal/federation/federation.go +++ b/internal/federation/federation.go @@ -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. diff --git a/internal/federation/service.go b/internal/federation/service.go index c40edf1..a14c41f 100644 --- a/internal/federation/service.go +++ b/internal/federation/service.go @@ -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 diff --git a/web/src/api/peaks.test.tsx b/web/src/api/peaks.test.tsx index 70998e0..2ee8a00 100644 --- a/web/src/api/peaks.test.tsx +++ b/web/src/api/peaks.test.tsx @@ -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) }) -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 { result } = renderHook(() => usePeaks(7, { enabled: false }), { wrapper }) await new Promise((r) => setTimeout(r, 40)) expect(result.current).toBeUndefined() 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 }) => {children} + 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])) +}) diff --git a/web/src/api/peaks.ts b/web/src/api/peaks.ts index c5775da..69f3510 100644 --- a/web/src/api/peaks.ts +++ b/web/src/api/peaks.ts @@ -14,19 +14,20 @@ interface Shape { 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. - * 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 { - const { enabled = true, pollMs = POLL_MS } = opts +export function usePeaks(trackId: number | null, opts: { friend?: number; enabled?: boolean; pollMs?: number } = {}): number[] | undefined { + const { friend, enabled = true, pollMs = POLL_MS } = opts const query = useQuery({ - queryKey: ['peaks', trackId], + queryKey: ['peaks', friend ?? null, trackId], enabled: enabled && trackId !== null, retry: false, // A shape does not change while the file does not: keep it for as long as the page lives. staleTime: Infinity, - queryFn: () => api.get(`/tracks/${trackId}/peaks`), + queryFn: () => api.get(friend === undefined ? `/tracks/${trackId}/peaks` : `/friends/${friend}/tracks/${trackId}/peaks`), refetchInterval: (q) => ('status' in (q.state.data ?? {}) ? pollMs : false), }) if (query.error instanceof ApiError || query.data === undefined || 'status' in query.data) return undefined diff --git a/web/src/api/schema.d.ts b/web/src/api/schema.d.ts index 6bd4771..e69727f 100644 --- a/web/src/api/schema.d.ts +++ b/web/src/api/schema.d.ts @@ -1792,6 +1792,33 @@ export interface paths { patch?: 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": { parameters: { query?: never; @@ -2373,6 +2400,31 @@ export interface paths { patch?: 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": { parameters: { query?: never; @@ -2555,6 +2607,94 @@ export interface paths { patch?: 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; export interface components { @@ -3632,6 +3772,12 @@ export interface components { */ 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: { /** * 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: { parameters: { 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: { parameters: { query?: never; @@ -8242,4 +8483,183 @@ export interface operations { 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 *\/`. */ + "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"]; + }; + }; } diff --git a/web/src/components/layout/NowPlaying.tsx b/web/src/components/layout/NowPlaying.tsx index 40b1cd1..ec2026b 100644 --- a/web/src/components/layout/NowPlaying.tsx +++ b/web/src/components/layout/NowPlaying.tsx @@ -26,7 +26,7 @@ function NowPlayingSeek({ track }: { track: QueuedTrack }) { const durationMs = track.duration_ms const positionMs = usePlayer((s) => s.positionMs) const seek = usePlayer((s) => s.seek) - const peaks = usePeaks(track.id, { enabled: track.friend === undefined }) + const peaks = usePeaks(track.id, { friend: track.friend }) return (
diff --git a/web/src/components/layout/Player.test.tsx b/web/src/components/layout/Player.test.tsx index 5801b28..a7c8092 100644 --- a/web/src/components/layout/Player.test.tsx +++ b/web/src/components/layout/Player.test.tsx @@ -58,6 +58,7 @@ function renderBar(extra?: React.ReactNode) { calls = mockFetch({ '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/friends/3/tracks/${n}/peaks`, () => ({ count: 120, peaks: new Array(120).fill(100) })])), }).calls return render( @@ -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) }) -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)])) const { container } = renderBar() - await screen.findByLabelText('From Anna’s server') - expect(container.querySelectorAll('footer [data-bar]').length).toBe(64) - expect(calls.some((c) => c.key.includes('/peaks'))).toBe(false) + await waitFor(() => expect(container.querySelectorAll('footer [data-bar]').length).toBe(120)) + expect(calls.some((c) => c.key === 'GET /api/v1/friends/3/tracks/1/peaks')).toBe(true) + expect(calls.some((c) => c.key === 'GET /api/v1/tracks/1/peaks')).toBe(false) }) diff --git a/web/src/components/layout/PlayerBar.tsx b/web/src/components/layout/PlayerBar.tsx index bd75699..4ec43f1 100644 --- a/web/src/components/layout/PlayerBar.tsx +++ b/web/src/components/layout/PlayerBar.tsx @@ -36,8 +36,8 @@ function usePlayPauseKey() { function PlayerSeek({ track }: { track: QueuedTrack | null }) { const positionMs = usePlayer((s) => s.positionMs) 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. - const peaks = usePeaks(track?.id ?? null, { enabled: track !== null && track.friend === undefined }) + // 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, { friend: track?.friend }) return (
{formatTime(track ? positionMs : 0)}