Merge pull request 'Federation: play a friend's music and show its covers through this server' (#141) from feat/federation-play into main
This commit is contained in:
commit
9b81b6385a
32 changed files with 1093 additions and 62 deletions
|
|
@ -28,11 +28,11 @@ It is a single executable, one database (SQLite by default, PostgreSQL if you pr
|
|||
- **Your own settings.** `GET` and `PATCH /me/settings` hold choices that belong to you, not to the server. Everyone starts private: `discover_from_listening` is off, so this setting never sends your listening to a provider. When you turn it on, Discover may start from the artists you listen to most, and their names are sent to Last.fm (only if an admin switched it on). What Last.fm answers is kept in the shared database like any other lookup, so another local user can see, from `retrieved_at` of `GET /artists/{id}/similar`, that someone looked up an artist, but not who.
|
||||
- **Tags.** `GET /artists/{id}/tags` shows what Last.fm and MusicBrainz say kind of music an artist plays, each with its own weights, and the genres of the artist's own files, read offline. See [External providers](#external-providers).
|
||||
- **Similar artists.** With Last.fm switched on, `GET /artists/{id}/similar` lists artists similar to an artist, and says which of them you already have. See [External providers](#external-providers). Without it, Sonda makes no outbound network requests at all.
|
||||
- **Friends (federation).** Two Sonda servers can become friends, and the listeners of one can read what the other chose to share. `PUT /federation` (admin) turns federation on, which is off by default, and gives this server a name and a public address (`https`; plain `http` only on a network of your own); the server then makes its own Ed25519 key, kept in the database and never returned. `POST /federation/invites` makes an invite that works once and expires in 24 hours (only a hash of its code is kept). The other admin uses it with `POST /federation/friends`: that server is asked to accept this one, the key it answers with must be the one named in the invite, and the friend waits as `outgoing` until the first admin approves it with `POST /federation/friends/{id}/approve` (`POST /federation/friends/{id}/check` lets the waiting side find out). Either side can remove a friend with `DELETE /federation/friends/{id}`. Nothing is shared until an admin turns on `shared` for a library (`PATCH /libraries/{id}`). A friend's server then reads, with requests signed by its key (the method, the path and query, a date, a nonce and the hash of the body), the routes under `/peer`: the artists, albums and tracks that have a file in a shared library, their covers once they are built, and the audio itself with `Range`. A friend never sees a path, a library id, a listen, a taste or a user, never makes this server build a cover or ask a provider, and has a few streams at a time and a number of KiB a second to share (`max_streams`, `max_kib_per_sec`); the admin sees the last requests it made (`GET /federation/requests`, the route and the size, never what was searched for). Sharing a library lets friends play it and, in practice, copy its files. A listener browses the music of a friend with `GET /friends` (the names of the friends whose friendship both admins agreed to, never an address or a key) and `GET /friends/{friend}/artists`, `albums` and `tracks` with `q`, `limit` and `offset`, and one item at a time: this server asks the friend with a signed request, checks the shape of the answer and passes it on, and nothing is kept; the ids are the friend's own. A friend that cannot be reached or no longer takes this server for a friend is told in words. The web app has a Friends section for it, shown only when there is a friend to browse. Playing a friend's music and showing its covers is not there yet. The admin area has a Federation section for all of it.
|
||||
- **Friends (federation).** Two Sonda servers can become friends, and the listeners of one can read what the other chose to share. `PUT /federation` (admin) turns federation on, which is off by default, and gives this server a name and a public address (`https`; plain `http` only on a network of your own); the server then makes its own Ed25519 key, kept in the database and never returned. `POST /federation/invites` makes an invite that works once and expires in 24 hours (only a hash of its code is kept). The other admin uses it with `POST /federation/friends`: that server is asked to accept this one, the key it answers with must be the one named in the invite, and the friend waits as `outgoing` until the first admin approves it with `POST /federation/friends/{id}/approve` (`POST /federation/friends/{id}/check` lets the waiting side find out). Either side can remove a friend with `DELETE /federation/friends/{id}`. Nothing is shared until an admin turns on `shared` for a library (`PATCH /libraries/{id}`). A friend's server then reads, with requests signed by its key (the method, the path and query, a date, a nonce and the hash of the body), the routes under `/peer`: the artists, albums and tracks that have a file in a shared library, their covers once they are built, and the audio itself with `Range`. A friend never sees a path, a library id, a listen, a taste or a user, never makes this server build a cover or ask a provider, and has a few streams at a time and a number of KiB a second to share (`max_streams`, `max_kib_per_sec`); the admin sees the last requests it made (`GET /federation/requests`, the route and the size, never what was searched for). Sharing a library lets friends play it and, in practice, copy its files. A listener browses the music of a friend with `GET /friends` (the names of the friends whose friendship both admins agreed to, never an address or a key) and `GET /friends/{friend}/artists`, `albums` and `tracks` with `q`, `limit` and `offset`, and one item at a time: this server asks the friend with a signed request, checks the shape of the answer and passes it on, and nothing is kept; the ids are the friend's own. A friend that cannot be reached or no longer takes this server for a friend is told in words. The web app has a Friends section for it, shown only when there is a friend to browse. A listener plays it with `GET /friends/{friend}/tracks/{id}/stream` and sees its covers with `GET /friends/{friend}/albums/{id}/cover`, which accept the access token in the query like the local ones: this server asks the friend with a signed request, forwards `Range` and the conditional headers, and passes on only audio (or a JPEG for a cover) with `Content-Type`, `Content-Length`, `Content-Range`, `Accept-Ranges`, `Last-Modified` and `ETag`, so the friend sees this server and never the listener, and a friend cannot make this server serve anything else. A friend's track plays in the same player as the others but is never reported as a listen and does not feed taste. The admin area has a Federation section for all of it.
|
||||
|
||||
## What is not there yet
|
||||
|
||||
Playing a friend's music and showing its covers (federation), radio queues, OpenSubsonic compatibility, transcoding, and the ListenBrainz integration. The web client is built into the binary (see [Web app](#web-app)), and its admin area covers everything the API can do for an admin: libraries and scanning, users, the external providers and the bulk jobs.
|
||||
Radio queues, OpenSubsonic compatibility, transcoding, and the ListenBrainz integration. The web client is built into the binary (see [Web app](#web-app)), and its admin area covers everything the API can do for an admin: libraries and scanning, users, the external providers and the bulk jobs.
|
||||
|
||||
## Requirements
|
||||
|
||||
|
|
|
|||
|
|
@ -245,8 +245,8 @@ func (c *contract) validate(req *http.Request, payload []byte, rec *httptest.Res
|
|||
// The library skips HEAD and redirects, and cannot read audio or YAML.
|
||||
// Those are checked by hand: the status above, and the content type here.
|
||||
skipBody := req.Method == http.MethodHead || route.Path == "/openapi.yaml" ||
|
||||
(rec.Code >= 300 && rec.Code < 400) || ((route.Path == "/tracks/{id}/stream" || route.Path == "/peer/tracks/{id}/stream") && rec.Code/100 == 2)
|
||||
if skipBody && documented != nil && documented.Value != nil && rec.Code/100 == 2 && req.Method != http.MethodHead && (route.Path == "/tracks/{id}/stream" || route.Path == "/peer/tracks/{id}/stream") {
|
||||
(rec.Code >= 300 && rec.Code < 400) || ((route.Path == "/tracks/{id}/stream" || route.Path == "/peer/tracks/{id}/stream" || route.Path == "/friends/{friend}/tracks/{id}/stream") && rec.Code/100 == 2)
|
||||
if skipBody && documented != nil && documented.Value != nil && rec.Code/100 == 2 && req.Method != http.MethodHead && (route.Path == "/tracks/{id}/stream" || route.Path == "/peer/tracks/{id}/stream" || route.Path == "/friends/{friend}/tracks/{id}/stream") {
|
||||
mediaType, _, err := mime.ParseMediaType(rec.Header().Get("Content-Type"))
|
||||
if err != nil || documented.Value.Content.Get(mediaType) == nil {
|
||||
c.t.Errorf("%s -> %d: Content-Type %q is not one the spec lists", where, rec.Code, rec.Header().Get("Content-Type"))
|
||||
|
|
@ -1328,6 +1328,28 @@ func (c *contract) friends(t *testing.T, token string) {
|
|||
c.expect(c.call("GET", "/friends/999999/tracks", token, nil), 404, "a friend that is not there", "friend_not_found")
|
||||
c.expect(c.call("GET", base+"/tracks?limit=abc", token, nil), 400, "a limit that is no number", "invalid_input")
|
||||
|
||||
// Playing it and seeing its cover, through this server.
|
||||
stream := base + "/tracks/" + trackID + "/stream"
|
||||
c.expect(c.call("GET", stream, "", nil), 401, "a friend's stream without a login", "unauthorized")
|
||||
if rec := c.call("GET", stream, token, nil); rec.Code != 200 {
|
||||
t.Fatalf("a friend's stream: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if rec := c.call("GET", stream, token, nil, "Range", "bytes=0-9"); rec.Code != 206 {
|
||||
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")
|
||||
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
|
||||
_ = p.db.QueryRow("SELECT id FROM albums WHERE title = 'Shared Album'").Scan(&theirAlbum)
|
||||
if rec := p.serveAs(t, "GET", "/api/v1/albums/"+strconv.FormatInt(theirAlbum, 10)+"/cover"); rec.Code != 200 {
|
||||
t.Fatalf("the cover on the friend's server: %d", rec.Code)
|
||||
}
|
||||
if rec := c.call("GET", cover, token, nil); rec.Code != 200 || rec.Header().Get("Content-Type") != "image/jpeg" {
|
||||
t.Fatalf("a friend's cover: %d %q", rec.Code, rec.Header().Get("Content-Type"))
|
||||
}
|
||||
c.expect(c.call("GET", cover+"?size=huge", token, nil), 400, "a cover of a size that does not exist", "invalid_input")
|
||||
|
||||
// The friend removes this server: the listener is told, and nothing is kept.
|
||||
p.admin1(t, "DELETE", "/federation/friends/"+idOf(theirs[0].(map[string]any)), nil)
|
||||
c.expect(c.call("GET", base+"/tracks", token, nil), 409, "a friend that removed this server", "friend_gone")
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
package httpapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
|
|
@ -8,6 +9,7 @@ import (
|
|||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/uptrace/bun"
|
||||
|
||||
|
|
@ -265,3 +267,174 @@ func TestAnAnswerThatIsNotACataloguePageIsNotPassedOn(t *testing.T) {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
// listen asks this server (C) for something as its listener would: with a header, or with the token in the
|
||||
// query, as an <audio> or <img> element has to.
|
||||
func (f *browseFixture) listen(path string, mutate ...func(*http.Request)) *httptest.ResponseRecorder {
|
||||
req := httptest.NewRequest("GET", "/api/v1"+path, nil)
|
||||
req.Header.Set("Authorization", "Bearer "+f.listener)
|
||||
for _, m := range mutate {
|
||||
m(req)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
f.c.h.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
|
||||
func (f *browseFixture) sharedTrack(t *testing.T) string {
|
||||
t.Helper()
|
||||
items := f.get(t, "/friends/"+f.friendID+"/tracks").Body["items"].([]any)
|
||||
return idOf(items[0].(map[string]any))
|
||||
}
|
||||
|
||||
func TestAListenerPlaysTheMusicOfAFriendThroughThisServer(t *testing.T) {
|
||||
f := newBrowseFixture(t)
|
||||
track := f.sharedTrack(t)
|
||||
path := "/friends/" + f.friendID + "/tracks/" + track + "/stream"
|
||||
want := f.p.bytes["Shared Song"]
|
||||
|
||||
rec := f.listen(path)
|
||||
if rec.Code != 200 || !bytes.Equal(rec.Body.Bytes(), want) {
|
||||
t.Fatalf("stream: %d, %d bytes of %d", rec.Code, rec.Body.Len(), len(want))
|
||||
}
|
||||
if ct := rec.Header().Get("Content-Type"); !strings.HasPrefix(ct, "audio/") {
|
||||
t.Errorf("Content-Type = %q", ct)
|
||||
}
|
||||
h := rec.Header()
|
||||
if h.Get("Accept-Ranges") != "bytes" || h.Get("X-Content-Type-Options") != "nosniff" || h.Get("Referrer-Policy") != "no-referrer" || h.Get("Cache-Control") != "private, no-cache" {
|
||||
t.Errorf("headers = %v", h)
|
||||
}
|
||||
if h.Get("Set-Cookie") != "" || h.Get("Content-Disposition") != "" {
|
||||
t.Errorf("headers a friend must not decide: %v", h)
|
||||
}
|
||||
|
||||
// An <audio> element cannot send a header: the token goes in the address.
|
||||
rec = f.listen(path+"?access_token="+f.listener, func(r *http.Request) { r.Header.Del("Authorization") })
|
||||
if rec.Code != 200 || !bytes.Equal(rec.Body.Bytes(), want) {
|
||||
t.Errorf("with the token in the address: %d", rec.Code)
|
||||
}
|
||||
if rec := f.listen(path, func(r *http.Request) { r.Header.Del("Authorization") }); rec.Code != 401 {
|
||||
t.Errorf("without a login: %d", rec.Code)
|
||||
}
|
||||
|
||||
// Seeking.
|
||||
rec = f.listen(path, func(r *http.Request) { r.Header.Set("Range", "bytes=100-199") })
|
||||
if rec.Code != 206 || !bytes.Equal(rec.Body.Bytes(), want[100:200]) || rec.Header().Get("Content-Range") != "bytes 100-199/400" {
|
||||
t.Errorf("range: %d %q %d bytes", rec.Code, rec.Header().Get("Content-Range"), rec.Body.Len())
|
||||
}
|
||||
rec = f.listen(path, func(r *http.Request) { r.Header.Set("Range", "bytes=9999-") })
|
||||
if rec.Code != 416 || rec.Body.Len() != 0 {
|
||||
t.Errorf("a range past the end: %d with %d bytes", rec.Code, rec.Body.Len())
|
||||
}
|
||||
if rec := f.listen(path, func(r *http.Request) {
|
||||
r.Header.Set("If-Modified-Since", time.Now().Add(time.Hour).UTC().Format(http.TimeFormat))
|
||||
}); rec.Code != 304 {
|
||||
t.Errorf("asking again: %d, want 304", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheFriendSeesThisServerAndNeverTheListener(t *testing.T) {
|
||||
f := newBrowseFixture(t)
|
||||
track := f.sharedTrack(t)
|
||||
f.listen("/friends/" + f.friendID + "/tracks/" + track + "/stream")
|
||||
|
||||
log := f.p.admin1(t, "GET", "/federation/requests", nil)
|
||||
var stream map[string]any
|
||||
for _, r := range log.Body["requests"].([]any) {
|
||||
if r.(map[string]any)["route"] == "/api/v1/peer/tracks/:id/stream" {
|
||||
stream = r.(map[string]any)
|
||||
}
|
||||
}
|
||||
if stream == nil || stream["friend"] != "Bruno" || stream["bytes"] != float64(400) {
|
||||
t.Fatalf("the friend's log = %v", log.Body)
|
||||
}
|
||||
if body := jsonOf(t, log.Body); strings.Contains(body, "lia") || strings.Contains(body, f.listener) {
|
||||
t.Errorf("the friend's log names the listener: %s", body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAStreamThatCannotBePlayedIsToldInWords(t *testing.T) {
|
||||
f := newBrowseFixture(t)
|
||||
track := f.sharedTrack(t)
|
||||
base := "/friends/" + f.friendID
|
||||
private := strconv.FormatInt(f.p.track["Private Song"], 10)
|
||||
|
||||
if r := f.get(t, base+"/tracks/"+private+"/stream"); r.Code != 404 || errCode(r) != "track_not_found" {
|
||||
t.Errorf("a track that is not shared: %d %v", r.Code, r.Body)
|
||||
}
|
||||
if r := f.get(t, "/friends/99999/tracks/"+track+"/stream"); r.Code != 404 || errCode(r) != "friend_not_found" {
|
||||
t.Errorf("a friend that is not there: %d %v", r.Code, r.Body)
|
||||
}
|
||||
if r := f.get(t, "/friends/abc/tracks/"+track+"/stream"); r.Code != 400 {
|
||||
t.Errorf("a friend that is no number: %d", r.Code)
|
||||
}
|
||||
if r := f.get(t, base+"/tracks/0/stream"); r.Code != 400 {
|
||||
t.Errorf("track 0: %d", r.Code)
|
||||
}
|
||||
|
||||
// The friend allows no more streams for this server.
|
||||
one := 1
|
||||
if _, err := f.p.fed.Update(t.Context(), federation.Patch{MaxStreams: &one}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fid, _ := strconv.ParseInt(f.pFriend, 10, 64)
|
||||
open, err := f.p.fed.StartStream(t.Context(), fid)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec := f.listen(base + "/tracks/" + track + "/stream")
|
||||
if rec.Code != 429 || !strings.Contains(rec.Body.String(), `"friend_busy"`) || rec.Header().Get("Retry-After") == "" {
|
||||
t.Errorf("a friend that is busy: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
open.Close()
|
||||
|
||||
// The friend removes this server, then goes away.
|
||||
f.p.admin1(t, "DELETE", "/federation/friends/"+f.pFriend, nil)
|
||||
if rec := f.listen(base + "/tracks/" + track + "/stream"); rec.Code != 409 || !strings.Contains(rec.Body.String(), `"friend_gone"`) {
|
||||
t.Errorf("after being removed: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
f.ts.Close()
|
||||
rec = f.listen(base + "/tracks/" + track + "/stream")
|
||||
if rec.Code != 502 || !strings.Contains(rec.Body.String(), `"friend_unreachable"`) || strings.Contains(rec.Body.String(), "127.0.0.1") {
|
||||
t.Errorf("a friend that is down: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestACoverOfAFriendIsPassedOnOnceItIsBuilt(t *testing.T) {
|
||||
f := newBrowseFixture(t)
|
||||
album := idOf(f.get(t, "/friends/"+f.friendID+"/albums").Body["items"].([]any)[0].(map[string]any))
|
||||
path := "/friends/" + f.friendID + "/albums/" + album + "/cover"
|
||||
|
||||
rec := f.listen(path)
|
||||
if rec.Code != 404 || !strings.Contains(rec.Body.String(), `"cover_not_found"`) {
|
||||
t.Fatalf("a cover that was not built: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
// Somebody on the friend's server opens it: it is built, and from then on it is passed on.
|
||||
var pAlbum int64
|
||||
_ = f.p.db.QueryRow("SELECT id FROM albums WHERE title = 'Shared Album'").Scan(&pAlbum)
|
||||
local := f.p.serveAs(t, "GET", "/api/v1/albums/"+strconv.FormatInt(pAlbum, 10)+"/cover")
|
||||
if local.Code != 200 {
|
||||
t.Fatalf("the cover on the friend's server: %d %s", local.Code, local.Body.String())
|
||||
}
|
||||
rec = f.listen(path)
|
||||
if rec.Code != 200 || rec.Header().Get("Content-Type") != "image/jpeg" || !bytes.Equal(rec.Body.Bytes(), local.Body.Bytes()) {
|
||||
t.Fatalf("the cover: %d %q, %d bytes of %d", rec.Code, rec.Header().Get("Content-Type"), rec.Body.Len(), local.Body.Len())
|
||||
}
|
||||
if rec.Header().Get("Cache-Control") != "private, max-age=3600" || rec.Header().Get("ETag") == "" {
|
||||
t.Errorf("headers = %v", rec.Header())
|
||||
}
|
||||
etag := rec.Header().Get("ETag")
|
||||
if rec := f.listen(path, func(r *http.Request) { r.Header.Set("If-None-Match", etag) }); rec.Code != 304 {
|
||||
t.Errorf("asking again: %d, want 304", rec.Code)
|
||||
}
|
||||
if rec := f.listen(path + "?size=small&access_token=" + f.listener); rec.Code != 200 {
|
||||
t.Errorf("the small one: %d", rec.Code)
|
||||
}
|
||||
if rec := f.listen(path + "?size=huge"); rec.Code != 400 {
|
||||
t.Errorf("a size that does not exist: %d", rec.Code)
|
||||
}
|
||||
private := idOf(map[string]any{"id": float64(f.p.track["Private Song"])}) // an id the friend does not share as an album
|
||||
if rec := f.listen("/friends/" + f.friendID + "/albums/" + private + "/cover"); rec.Code != 404 {
|
||||
t.Errorf("an album that is not shared: %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -31,6 +31,7 @@ type federationService interface {
|
|||
// What a listener may ask about friends.
|
||||
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)
|
||||
}
|
||||
|
||||
// federationHandlers are the admin routes that set up federation and its friends, and the one public route
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ package httpapi
|
|||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
|
|
@ -17,7 +18,7 @@ import (
|
|||
type friendsHandlers struct{ svc federationService }
|
||||
|
||||
// friendNotFound maps a kind of thing to the code of the answer when the friend does not have it.
|
||||
var friendNotFound = map[string]string{"artists": "artist_not_found", "albums": "album_not_found", "tracks": "track_not_found"}
|
||||
var friendNotFound = map[string]string{"artists": "artist_not_found", "albums": "album_not_found", "tracks": "track_not_found", "covers": "cover_not_found"}
|
||||
|
||||
func (h *friendsHandlers) list(c *gin.Context) {
|
||||
friends, err := h.svc.ActiveFriends(c.Request.Context())
|
||||
|
|
@ -125,3 +126,51 @@ func relayOne[T any](h *friendsHandlers, resource string) gin.HandlerFunc {
|
|||
c.JSON(http.StatusOK, item)
|
||||
}
|
||||
}
|
||||
|
||||
// friendMediaHandlers pass the audio and the covers of a friend on to a listener. The listener's browser talks to
|
||||
// this server only: this one asks the friend, signed, so the friend sees this server and nothing of the listener.
|
||||
type friendMediaHandlers struct{ svc federationService }
|
||||
|
||||
func (h *friendMediaHandlers) stream(c *gin.Context) {
|
||||
h.serve(c, federation.MediaStream, "tracks", "private, no-cache")
|
||||
}
|
||||
|
||||
func (h *friendMediaHandlers) cover(c *gin.Context) {
|
||||
h.serve(c, federation.MediaCover, "covers", "private, max-age=3600")
|
||||
}
|
||||
|
||||
func (h *friendMediaHandlers) serve(c *gin.Context, kind, resource, cache string) {
|
||||
friend, err := strconv.ParseInt(c.Param("friend"), 10, 64)
|
||||
if err != nil || friend <= 0 {
|
||||
writeError(c, http.StatusBadRequest, "invalid_input", "friend must be a positive number")
|
||||
return
|
||||
}
|
||||
id, ok := pathID(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
media, err := h.svc.OpenMedia(c.Request.Context(), friend, kind, id, c.Request.URL.Query(), c.Request.Header)
|
||||
if err != nil {
|
||||
writeFriendError(c, err, resource)
|
||||
return
|
||||
}
|
||||
defer media.Body.Close()
|
||||
|
||||
hdr := c.Writer.Header()
|
||||
for k, vs := range media.Header {
|
||||
for _, v := range vs {
|
||||
hdr.Add(k, v)
|
||||
}
|
||||
}
|
||||
hdr.Set("X-Content-Type-Options", "nosniff")
|
||||
// The URL may carry the access token: never leak it through Referer.
|
||||
hdr.Set("Referrer-Policy", "no-referrer")
|
||||
hdr.Set("Cache-Control", cache)
|
||||
c.Status(media.Status)
|
||||
if media.Status == http.StatusNotModified || media.Status == http.StatusRequestedRangeNotSatisfiable {
|
||||
c.Writer.WriteHeaderNow()
|
||||
return
|
||||
}
|
||||
// The listener may leave at any time: the copy then ends, and so does the request to the friend.
|
||||
_, _ = io.Copy(c.Writer, media.Body)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,6 +6,8 @@ import (
|
|||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"image"
|
||||
"image/png"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
|
|
@ -82,6 +84,14 @@ func newPeerFixture(t *testing.T) *peerFixture {
|
|||
if err := os.WriteFile(filepath.Join(dir, "song.mp3"), data, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// A picture next to the audio: the cover of the album, once somebody asks for it.
|
||||
var pic bytes.Buffer
|
||||
if err := png.Encode(&pic, image.NewRGBA(image.Rect(0, 0, 40, 30))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, "cover.png"), pic.Bytes(), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
lib, err := repo.CreateLibrary(t.Context(), l.name, dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
|
|
@ -524,3 +534,13 @@ func TestAServerChecksWhetherTheOtherApproved(t *testing.T) {
|
|||
t.Errorf("unknown friend: %d", r.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// serveAs asks the server as its admin and returns the whole answer.
|
||||
func (f *peerFixture) serveAs(t *testing.T, method, path string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(method, path, nil)
|
||||
req.Header.Set("Authorization", "Bearer "+f.admin)
|
||||
rec := httptest.NewRecorder()
|
||||
f.h.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
|
|
|
|||
|
|
@ -366,6 +366,9 @@ func NewRouter(d Deps) *gin.Engine {
|
|||
st := &streamHandlers{svc: d.Streams}
|
||||
audio := v1.Group("", requireAuth(d.Tokens, d.Auth, true))
|
||||
audio.GET("/tracks/:id/stream", st.stream)
|
||||
fm := &friendMediaHandlers{svc: d.Federation}
|
||||
audio.GET("/friends/:friend/tracks/:id/stream", fm.stream)
|
||||
audio.GET("/friends/:friend/albums/:id/cover", fm.cover)
|
||||
audio.HEAD("/tracks/:id/stream", st.stream)
|
||||
// An <img> element cannot send headers either, so covers take the token the same way.
|
||||
cv := &coverHandlers{svc: d.Images}
|
||||
|
|
|
|||
|
|
@ -3705,6 +3705,126 @@ paths:
|
|||
application/json:
|
||||
schema: {$ref: '#/components/schemas/Error'}
|
||||
|
||||
/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}}
|
||||
- {$ref: '#/components/parameters/Id'}
|
||||
get:
|
||||
tags: [Friends]
|
||||
operationId: streamFriendTrack
|
||||
summary: 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`).
|
||||
security:
|
||||
- bearerAuth: []
|
||||
- streamQueryToken: []
|
||||
parameters:
|
||||
- name: Range
|
||||
in: header
|
||||
required: false
|
||||
description: A byte range, for example `bytes=0-99`.
|
||||
schema: {type: string}
|
||||
- name: If-Modified-Since
|
||||
in: header
|
||||
required: false
|
||||
schema: {type: string}
|
||||
responses:
|
||||
'200':
|
||||
description: The whole file.
|
||||
headers:
|
||||
Accept-Ranges: {$ref: '#/components/headers/AcceptRanges'}
|
||||
Content-Length: {$ref: '#/components/headers/ContentLength'}
|
||||
Last-Modified: {$ref: '#/components/headers/LastModified'}
|
||||
content:
|
||||
audio/mpeg:
|
||||
schema: {type: string, format: binary}
|
||||
audio/flac:
|
||||
schema: {type: string, format: binary}
|
||||
'206':
|
||||
description: The requested byte range.
|
||||
headers:
|
||||
Content-Range:
|
||||
description: The range sent and the size of the file, for example `bytes 0-99/40635`.
|
||||
schema: {type: string}
|
||||
content:
|
||||
audio/mpeg:
|
||||
schema: {type: string, format: binary}
|
||||
audio/flac:
|
||||
schema: {type: string, format: binary}
|
||||
'304': {description: Not modified since `If-Modified-Since`.}
|
||||
'400': {$ref: '#/components/responses/InvalidInput'}
|
||||
'401': {$ref: '#/components/responses/Unauthorized'}
|
||||
'404':
|
||||
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`).
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/Error'}
|
||||
'409': {$ref: '#/components/responses/FriendGone'}
|
||||
'416':
|
||||
description: The range cannot be satisfied.
|
||||
headers:
|
||||
Content-Range:
|
||||
description: '`bytes */<size of the file>`.'
|
||||
schema: {type: string}
|
||||
'429': {$ref: '#/components/responses/FriendBusy'}
|
||||
'502': {$ref: '#/components/responses/FriendUnreachable'}
|
||||
|
||||
/friends/{friend}/albums/{id}/cover:
|
||||
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: getFriendAlbumCover
|
||||
summary: 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.
|
||||
security:
|
||||
- bearerAuth: []
|
||||
- streamQueryToken: []
|
||||
parameters:
|
||||
- name: size
|
||||
in: query
|
||||
description: "`small` or `large`. Large when absent."
|
||||
schema: {type: string, enum: [small, large], default: large}
|
||||
- name: If-None-Match
|
||||
in: header
|
||||
required: false
|
||||
schema: {type: string}
|
||||
responses:
|
||||
'200':
|
||||
description: The cover.
|
||||
headers:
|
||||
ETag: {$ref: '#/components/headers/ETag'}
|
||||
Cache-Control: {$ref: '#/components/headers/CacheControl'}
|
||||
Content-Length: {$ref: '#/components/headers/ContentLength'}
|
||||
content:
|
||||
image/jpeg:
|
||||
schema: {type: string, format: binary}
|
||||
'304': {description: Not modified since `If-None-Match`.}
|
||||
'400': {$ref: '#/components/responses/InvalidInput'}
|
||||
'401': {$ref: '#/components/responses/Unauthorized'}
|
||||
'404':
|
||||
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`).
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/Error'}
|
||||
'409': {$ref: '#/components/responses/FriendGone'}
|
||||
'429': {$ref: '#/components/responses/FriendBusy'}
|
||||
'502': {$ref: '#/components/responses/FriendUnreachable'}
|
||||
|
||||
components:
|
||||
securitySchemes:
|
||||
bearerAuth:
|
||||
|
|
@ -3716,7 +3836,7 @@ components:
|
|||
type: apiKey
|
||||
in: query
|
||||
name: access_token
|
||||
description: The same access token, for stream URLs used by an `<audio>` element. Accepted only on `/tracks/{id}/stream`, `/albums/{id}/cover` and `/artists/{id}/image`.
|
||||
description: The same access token, for stream URLs used by an `<audio>` element. Accepted only on `/tracks/{id}/stream`, `/albums/{id}/cover`, `/artists/{id}/image` and the same two of a friend under `/friends/{friend}`.
|
||||
|
||||
friendSignature:
|
||||
type: apiKey
|
||||
|
|
|
|||
|
|
@ -26,11 +26,23 @@ const (
|
|||
// Client talks to other Sonda servers. It is not the outbound client of the providers, which by design never sends a
|
||||
// header that identifies anything: this one is for a friend, and it has the same bounds otherwise: no redirect is
|
||||
// followed, no proxy of the environment is used, the answer has a size limit and every attempt has a time limit.
|
||||
type Client struct{ http *http.Client }
|
||||
type Client struct {
|
||||
http *http.Client
|
||||
// stream is for what is too big to read whole: no limit on the whole answer, only on its beginning.
|
||||
stream *http.Client
|
||||
}
|
||||
|
||||
// NewClient builds a Client.
|
||||
func NewClient() *Client {
|
||||
return &Client{http: &http.Client{
|
||||
return &Client{stream: &http.Client{
|
||||
Transport: &http.Transport{
|
||||
Proxy: nil,
|
||||
DialContext: (&net.Dialer{Timeout: 5 * time.Second}).DialContext,
|
||||
TLSHandshakeTimeout: 5 * time.Second,
|
||||
ResponseHeaderTimeout: 15 * time.Second,
|
||||
},
|
||||
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
|
||||
}, http: &http.Client{
|
||||
Timeout: 10 * time.Second,
|
||||
Transport: &http.Transport{
|
||||
Proxy: nil,
|
||||
|
|
@ -164,3 +176,33 @@ func (c *Client) Info(ctx context.Context, address string, auth Auth) (Info, err
|
|||
return Info{}, fmt.Errorf("%w: it answered %d", ErrUnreachable, status)
|
||||
}
|
||||
}
|
||||
|
||||
// Open sends a signed GET with these request headers and returns the answer with its body open: the caller reads it
|
||||
// (as far as the listener wants) and closes it, and it ends when ctx does.
|
||||
func (c *Client) Open(ctx context.Context, address, uri string, auth Auth, header http.Header) (*http.Response, error) {
|
||||
raw := make([]byte, 18)
|
||||
if _, err := rand.Read(raw); err != nil {
|
||||
return nil, fmt.Errorf("make a nonce: %w", err)
|
||||
}
|
||||
// What is signed is the path from /api/v1/peer on and the query, as in get.
|
||||
h := Sign(auth.Key, http.MethodGet, uri, time.Now(), base64.RawURLEncoding.EncodeToString(raw))
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimRight(address, "/")+uri, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: %v", ErrUnreachable, err)
|
||||
}
|
||||
for k, vs := range header {
|
||||
for _, v := range vs {
|
||||
req.Header.Add(k, v)
|
||||
}
|
||||
}
|
||||
req.Header.Set("User-Agent", "Sonda (federation)")
|
||||
req.Header.Set(HeaderKeyID, auth.KeyID)
|
||||
req.Header.Set(HeaderDate, h.Date)
|
||||
req.Header.Set(HeaderNonce, h.Nonce)
|
||||
req.Header.Set(HeaderSignature, h.Signature)
|
||||
resp, err := c.stream.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: %v", ErrUnreachable, err)
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -254,3 +254,81 @@ func TestClientRefusesAnAnswerThatIsTooBigForACatalogue(t *testing.T) {
|
|||
t.Errorf("a 3 MiB answer: err = %v, want ErrUnreachable", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientOpensAStreamSignedAndReadsAsMuchAsItIsGiven(t *testing.T) {
|
||||
pub, priv, _ := ed25519.GenerateKey(nil)
|
||||
big := bytes.Repeat([]byte("a"), 5<<20) // far more than a page of the catalogue may be
|
||||
var got Signed
|
||||
var rangeHeader, cookie string
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
rangeHeader, cookie = r.Header.Get("Range"), r.Header.Get("Cookie")
|
||||
got = Signed{
|
||||
KeyID: r.Header.Get(HeaderKeyID), Date: r.Header.Get(HeaderDate), Nonce: r.Header.Get(HeaderNonce),
|
||||
Signature: r.Header.Get(HeaderSignature), Method: r.Method, URI: "/api/v1/peer/tracks/1/stream",
|
||||
}
|
||||
w.Header().Set("Content-Type", "audio/mpeg")
|
||||
_, _ = w.Write(big)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
resp, err := NewClient().Open(context.Background(), srv.URL+"/", "/api/v1/peer/tracks/1/stream", Auth{KeyID: KeyID(pub), Key: priv}, http.Header{"Range": {"bytes=0-"}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
if len(body) != len(big) || resp.Header.Get("Content-Type") != "audio/mpeg" {
|
||||
t.Errorf("read %d of %d bytes, type %q", len(body), len(big), resp.Header.Get("Content-Type"))
|
||||
}
|
||||
if rangeHeader != "bytes=0-" || cookie != "" {
|
||||
t.Errorf("Range = %q, Cookie = %q", rangeHeader, cookie)
|
||||
}
|
||||
if !verify(pub, got.Method, got.URI, got.Date, got.Nonce, got.Signature) {
|
||||
t.Errorf("not properly signed: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientOpenNeverFollowsARedirectAndStopsWhenAskedTo(t *testing.T) {
|
||||
_, priv, _ := ed25519.GenerateKey(nil)
|
||||
elsewhere := 0
|
||||
other := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { elsewhere++ }))
|
||||
defer other.Close()
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, other.URL, http.StatusTemporaryRedirect)
|
||||
}))
|
||||
defer srv.Close()
|
||||
resp, err := NewClient().Open(context.Background(), srv.URL, "/api/v1/peer/tracks/1/stream", Auth{KeyID: "0123456789abcdef", Key: priv}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusTemporaryRedirect || elsewhere != 0 {
|
||||
t.Errorf("status %d, redirected requests %d: the redirect must be handed back, not followed", resp.StatusCode, elsewhere)
|
||||
}
|
||||
|
||||
// A listener that goes away ends the request to the friend.
|
||||
started := make(chan struct{})
|
||||
ended := make(chan struct{})
|
||||
slow := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "audio/mpeg")
|
||||
_, _ = w.Write([]byte("start"))
|
||||
w.(http.Flusher).Flush()
|
||||
close(started)
|
||||
<-r.Context().Done()
|
||||
close(ended)
|
||||
}))
|
||||
defer slow.Close()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
resp, err = NewClient().Open(ctx, slow.URL, "/api/v1/peer/tracks/1/stream", Auth{KeyID: "0123456789abcdef", Key: priv}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
<-started
|
||||
cancel()
|
||||
select {
|
||||
case <-ended:
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Error("the request to the friend went on after the listener left")
|
||||
}
|
||||
_ = resp.Body.Close()
|
||||
}
|
||||
|
|
|
|||
212
internal/federation/media_test.go
Normal file
212
internal/federation/media_test.go
Normal file
|
|
@ -0,0 +1,212 @@
|
|||
package federation
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type closeTracker struct {
|
||||
io.Reader
|
||||
closed bool
|
||||
}
|
||||
|
||||
func (c *closeTracker) Close() error { c.closed = true; return nil }
|
||||
|
||||
// mediaRemote is a Remote whose signed streaming GET answers as a script says.
|
||||
type mediaRemote struct {
|
||||
getRemote
|
||||
resp *http.Response
|
||||
body *closeTracker
|
||||
err error
|
||||
sent http.Header
|
||||
opened int
|
||||
}
|
||||
|
||||
func (m *mediaRemote) Open(_ context.Context, addr, uri string, auth Auth, header http.Header) (*http.Response, error) {
|
||||
m.opened++
|
||||
m.addr, m.uri, m.auth, m.sent = addr, uri, auth, header
|
||||
if m.err != nil {
|
||||
return nil, m.err
|
||||
}
|
||||
m.resp.Body = m.body
|
||||
return m.resp, nil
|
||||
}
|
||||
|
||||
func answer(status int, body string, kv ...string) (*http.Response, *closeTracker) {
|
||||
h := http.Header{}
|
||||
for i := 0; i+1 < len(kv); i += 2 {
|
||||
h.Add(kv[i], kv[i+1])
|
||||
}
|
||||
return &http.Response{StatusCode: status, Header: h}, &closeTracker{Reader: strings.NewReader(body)}
|
||||
}
|
||||
|
||||
func media(t *testing.T) (*Service, *mediaRemote, int64) {
|
||||
t.Helper()
|
||||
s, _, _, _, _, id := pairedServers(t)
|
||||
m := &mediaRemote{}
|
||||
s.remote = m
|
||||
return s, m, id
|
||||
}
|
||||
|
||||
func TestAStreamIsPassedOnWithAFixedSetOfHeaders(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
s, m, id := media(t)
|
||||
m.resp, m.body = answer(206, "0123456789",
|
||||
"Content-Type", "audio/mpeg", "Content-Range", "bytes 0-9/100", "Content-Length", "10", "Accept-Ranges", "bytes",
|
||||
"Last-Modified", "Mon, 02 Jan 2006 15:04:05 GMT", "Set-Cookie", "session=1", "Content-Disposition", "attachment; filename=x.exe",
|
||||
"Location", "https://evil.example.org/", "X-Anything", "x")
|
||||
|
||||
got, err := s.OpenMedia(ctx, id, MediaStream, 9, nil, http.Header{
|
||||
"Range": {"bytes=0-9"}, "Authorization": {"Bearer secret"}, "Cookie": {"a=b"}, "If-Modified-Since": {"Mon, 02 Jan 2006 15:04:05 GMT"}, "X-Evil": {"1"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer got.Body.Close()
|
||||
if body, _ := io.ReadAll(got.Body); string(body) != "0123456789" || got.Status != 206 {
|
||||
t.Errorf("status %d, body %q", got.Status, body)
|
||||
}
|
||||
for _, k := range []string{"Content-Type", "Content-Range", "Content-Length", "Accept-Ranges", "Last-Modified"} {
|
||||
if got.Header.Get(k) == "" {
|
||||
t.Errorf("%s was not passed on", k)
|
||||
}
|
||||
}
|
||||
for _, k := range []string{"Set-Cookie", "Content-Disposition", "Location", "X-Anything"} {
|
||||
if got.Header.Get(k) != "" {
|
||||
t.Errorf("%s was passed on: a friend decides nothing about the answer a listener gets", k)
|
||||
}
|
||||
}
|
||||
if m.uri != "/api/v1/peer/tracks/9/stream" || m.addr != "https://bruno.example.org" || len(m.auth.Key) == 0 {
|
||||
t.Errorf("asked %q at %q", m.uri, m.addr)
|
||||
}
|
||||
// Only what a player sends to seek and to ask again goes to the friend.
|
||||
if m.sent.Get("Range") != "bytes=0-9" || m.sent.Get("If-Modified-Since") == "" {
|
||||
t.Errorf("sent %v", m.sent)
|
||||
}
|
||||
for _, k := range []string{"Authorization", "Cookie", "X-Evil"} {
|
||||
if m.sent.Get(k) != "" {
|
||||
t.Errorf("%s was sent to the friend: it is the listener's, not the friend's", k)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestACoverAsksForOneOfTwoSizes(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
s, m, id := media(t)
|
||||
m.resp, m.body = answer(200, "jpeg", "Content-Type", "image/jpeg", "ETag", `"abc"`)
|
||||
got, err := s.OpenMedia(ctx, id, MediaCover, 4, url.Values{"size": {"small"}, "evil": {"1"}}, http.Header{"If-None-Match": {`"abc"`}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got.Body.Close()
|
||||
if m.uri != "/api/v1/peer/albums/4/cover?size=small" || m.sent.Get("If-None-Match") != `"abc"` {
|
||||
t.Errorf("asked %q with %v", m.uri, m.sent)
|
||||
}
|
||||
if _, err := s.OpenMedia(ctx, id, MediaCover, 4, url.Values{"size": {"huge"}}, nil); !errors.Is(err, ErrInvalidInput) {
|
||||
t.Errorf("a size that does not exist: %v", err)
|
||||
}
|
||||
m.resp, m.body = answer(304, "")
|
||||
got, err = s.OpenMedia(ctx, id, MediaCover, 4, nil, nil)
|
||||
if err != nil || got.Status != 304 {
|
||||
t.Errorf("not modified: %+v, %v", got, err)
|
||||
}
|
||||
if got != nil {
|
||||
got.Body.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func TestOnlyAudioAndPicturesArePassedOn(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
s, m, id := media(t)
|
||||
for _, tc := range []struct {
|
||||
kind, ctype string
|
||||
}{
|
||||
{MediaStream, "text/html"}, {MediaStream, "application/javascript"}, {MediaStream, "image/jpeg"}, {MediaStream, ""},
|
||||
{MediaStream, "multipart/byteranges; boundary=x"}, {MediaCover, "text/html"}, {MediaCover, "image/svg+xml"}, {MediaCover, "audio/mpeg"},
|
||||
} {
|
||||
m.resp, m.body = answer(200, "<script>alert(1)</script>", "Content-Type", tc.ctype)
|
||||
_, err := s.OpenMedia(ctx, id, tc.kind, 1, nil, nil)
|
||||
if !errors.Is(err, ErrUnreachable) {
|
||||
t.Errorf("%s as %q: err = %v, want ErrUnreachable", tc.kind, tc.ctype, err)
|
||||
}
|
||||
if !m.body.closed {
|
||||
t.Errorf("%s as %q: the friend's answer was left open", tc.kind, tc.ctype)
|
||||
}
|
||||
}
|
||||
for _, ctype := range []string{"audio/mpeg", "audio/flac", "audio/mpeg; charset=binary"} {
|
||||
m.resp, m.body = answer(200, "x", "Content-Type", ctype)
|
||||
got, err := s.OpenMedia(ctx, id, MediaStream, 1, nil, nil)
|
||||
if err != nil {
|
||||
t.Errorf("%q: %v", ctype, err)
|
||||
continue
|
||||
}
|
||||
got.Body.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func TestWhatAFriendAnswersToAStreamIsToldInOurOwnTerms(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
s, m, id := media(t)
|
||||
for _, tc := range []struct {
|
||||
status int
|
||||
body string
|
||||
want error
|
||||
}{
|
||||
{404, `{"error":{"code":"track_not_found"}}`, ErrNotFoundThere},
|
||||
{404, `{"error":{"code":"cover_not_found"}}`, ErrNotFoundThere},
|
||||
{404, `{"error":{"code":"not_found"}}`, ErrNotFriend},
|
||||
{401, `{"error":{"code":"unauthorized"}}`, ErrNotFriend},
|
||||
{403, `{"error":{"code":"not_approved"}}`, ErrNotApproved},
|
||||
{429, `{"error":{"code":"too_many_streams"}}`, ErrTooMany},
|
||||
{400, `{"error":{"code":"invalid_input"}}`, ErrInvalidInput},
|
||||
{502, `oops`, ErrUnreachable},
|
||||
} {
|
||||
m.resp, m.body = answer(tc.status, tc.body, "Content-Type", "application/json")
|
||||
_, err := s.OpenMedia(ctx, id, MediaStream, 1, nil, nil)
|
||||
if !errors.Is(err, tc.want) {
|
||||
t.Errorf("%d %q: err = %v, want %v", tc.status, tc.body, err, tc.want)
|
||||
}
|
||||
if !m.body.closed {
|
||||
t.Errorf("%d: the answer was left open", tc.status)
|
||||
}
|
||||
}
|
||||
m.err = ErrUnreachable
|
||||
if _, err := s.OpenMedia(ctx, id, MediaStream, 1, nil, nil); !errors.Is(err, ErrUnreachable) {
|
||||
t.Errorf("no answer: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOnlyAnActiveFriendCanBeStreamedFrom(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
s, m, id := media(t)
|
||||
m.resp, m.body = answer(200, "x", "Content-Type", "audio/mpeg")
|
||||
for name, call := range map[string]func() error{
|
||||
"an unknown friend": func() error { _, err := s.OpenMedia(ctx, 999, MediaStream, 1, nil, nil); return err },
|
||||
} {
|
||||
if err := call(); !errors.Is(err, ErrFriendMissing) {
|
||||
t.Errorf("%s: %v", name, err)
|
||||
}
|
||||
}
|
||||
for name, call := range map[string]func() error{
|
||||
"another kind": func() error { _, err := s.OpenMedia(ctx, id, "info", 1, nil, nil); return err },
|
||||
"no id": func() error { _, err := s.OpenMedia(ctx, id, MediaStream, 0, nil, nil); return err },
|
||||
"a negative id": func() error { _, err := s.OpenMedia(ctx, id, MediaStream, -3, nil, nil); return err },
|
||||
} {
|
||||
if err := call(); !errors.Is(err, ErrInvalidInput) {
|
||||
t.Errorf("%s: %v", name, err)
|
||||
}
|
||||
}
|
||||
off := false
|
||||
_, _ = s.Update(ctx, Patch{Enabled: &off})
|
||||
if _, err := s.OpenMedia(ctx, id, MediaStream, 1, nil, nil); !errors.Is(err, ErrFriendMissing) {
|
||||
t.Errorf("while off: %v", err)
|
||||
}
|
||||
if m.opened != 0 {
|
||||
t.Errorf("the friend was asked %d times", m.opened)
|
||||
}
|
||||
}
|
||||
|
|
@ -4,6 +4,7 @@ import (
|
|||
"context"
|
||||
"crypto/ed25519"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
|
@ -326,6 +327,10 @@ func (f *fakeRemote) Get(context.Context, string, string, Auth) (int, []byte, er
|
|||
return 0, nil, errors.New("not used")
|
||||
}
|
||||
|
||||
func (f *fakeRemote) Open(context.Context, string, string, Auth, http.Header) (*http.Response, error) {
|
||||
return nil, errors.New("not used")
|
||||
}
|
||||
|
||||
func (f *fakeRemote) Info(_ context.Context, addr string, auth Auth) (Info, error) {
|
||||
f.got, f.addr = auth, addr
|
||||
return f.info, f.err
|
||||
|
|
|
|||
|
|
@ -10,6 +10,8 @@ import (
|
|||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
|
|
@ -73,6 +75,10 @@ type Remote interface {
|
|||
// Get sends a signed GET of uri (the path from /api/v1/peer on, and the query) to the server at address and
|
||||
// returns its status and body, whatever the status. An error means no answer was had.
|
||||
Get(ctx context.Context, address, uri string, auth Auth) (status int, body []byte, err error)
|
||||
// Open sends a signed GET like Get, with these request headers, and returns the answer with its body still open
|
||||
// for the caller to read and close: it is for audio and pictures, which are too big to read whole. There is no
|
||||
// overall time limit (a song takes as long as it takes), only one for the friend to start answering.
|
||||
Open(ctx context.Context, address, uri string, auth Auth, header http.Header) (*http.Response, error)
|
||||
}
|
||||
|
||||
// Auth is what signs a request to a friend: this server's key.
|
||||
|
|
@ -691,15 +697,21 @@ func (s *Service) Browse(ctx context.Context, friendID int64, resource string, i
|
|||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch status {
|
||||
case http.StatusOK:
|
||||
if status == http.StatusOK {
|
||||
return body, nil
|
||||
}
|
||||
return nil, errorFor(status, body)
|
||||
}
|
||||
|
||||
// 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 {
|
||||
case http.StatusBadRequest:
|
||||
return nil, fmt.Errorf("%w: the friend did not take the question", ErrInvalidInput)
|
||||
return fmt.Errorf("%w: the friend did not take the question", ErrInvalidInput)
|
||||
case http.StatusForbidden:
|
||||
return nil, ErrNotApproved
|
||||
return ErrNotApproved
|
||||
case http.StatusUnauthorized:
|
||||
return nil, ErrNotFriend
|
||||
return ErrNotFriend
|
||||
case http.StatusNotFound:
|
||||
var e struct {
|
||||
Error struct {
|
||||
|
|
@ -707,12 +719,114 @@ func (s *Service) Browse(ctx context.Context, friendID int64, resource string, i
|
|||
} `json:"error"`
|
||||
}
|
||||
if json.Unmarshal(body, &e) == nil && strings.HasSuffix(e.Error.Code, "_not_found") {
|
||||
return nil, ErrNotFoundThere
|
||||
return ErrNotFoundThere
|
||||
}
|
||||
return nil, 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
|
||||
case http.StatusTooManyRequests:
|
||||
return nil, ErrTooMany
|
||||
return ErrTooMany
|
||||
default:
|
||||
return nil, fmt.Errorf("%w: it answered %d", ErrUnreachable, status)
|
||||
return fmt.Errorf("%w: it answered %d", ErrUnreachable, status)
|
||||
}
|
||||
}
|
||||
|
||||
// The two things that are passed on whole.
|
||||
const (
|
||||
MediaStream = "stream" // the audio of a track
|
||||
MediaCover = "cover" // the cover of an album
|
||||
)
|
||||
|
||||
// What goes to a friend from the request of a listener, and what comes back to the listener from the friend's
|
||||
// answer: a short list each way, so that nothing a listener or a friend sends decides anything on the other side.
|
||||
var (
|
||||
mediaRequestHeaders = []string{"Range", "If-Range", "If-Modified-Since", "If-Unmodified-Since", "If-None-Match"}
|
||||
mediaResponseHeaders = []string{"Content-Type", "Content-Length", "Content-Range", "Accept-Ranges", "Last-Modified", "ETag"}
|
||||
)
|
||||
|
||||
// Media is a friend's answer to a request for a stream or a cover, ready to be passed on. Close the Body.
|
||||
type Media struct {
|
||||
Status int
|
||||
Header http.Header
|
||||
Body io.ReadCloser
|
||||
}
|
||||
|
||||
// OpenMedia asks an active friend, signed, for the audio of a track or the cover of an album, forwarding the headers
|
||||
// a player uses to seek and to ask again. Only audio (for a stream) and a JPEG (for a cover) are passed on, with
|
||||
// a fixed set of headers, so a friend cannot make this server serve anything else. The friend sees this server's
|
||||
// request and nothing of the listener.
|
||||
func (s *Service) OpenMedia(ctx context.Context, friendID int64, kind string, id int64, query url.Values, in http.Header) (*Media, error) {
|
||||
if id <= 0 || (kind != MediaStream && kind != MediaCover) {
|
||||
return nil, fmt.Errorf("%w: there is no such thing to open", ErrInvalidInput)
|
||||
}
|
||||
uri := "/api/v1/peer/tracks/" + strconv.FormatInt(id, 10) + "/stream"
|
||||
if kind == MediaCover {
|
||||
uri = "/api/v1/peer/albums/" + strconv.FormatInt(id, 10) + "/cover"
|
||||
switch size := query.Get("size"); size {
|
||||
case "":
|
||||
case "small", "large":
|
||||
uri += "?size=" + size
|
||||
default:
|
||||
return nil, fmt.Errorf("%w: size is small or large", 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
|
||||
}
|
||||
out := http.Header{}
|
||||
for _, k := range mediaRequestHeaders {
|
||||
if v := in.Get(k); v != "" {
|
||||
out.Set(k, v)
|
||||
}
|
||||
}
|
||||
resp, err := s.remote.Open(ctx, f.Address, uri, Auth{KeyID: KeyID(set.PublicKey), Key: set.PrivateKey}, out)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
switch resp.StatusCode {
|
||||
case http.StatusOK, http.StatusPartialContent:
|
||||
if !mediaTypeOK(kind, resp.Header.Get("Content-Type")) {
|
||||
_ = resp.Body.Close()
|
||||
return nil, fmt.Errorf("%w: the answer is not what was asked for", ErrUnreachable)
|
||||
}
|
||||
return &Media{Status: resp.StatusCode, Header: passed(resp.Header, true), Body: resp.Body}, nil
|
||||
case http.StatusNotModified, http.StatusRequestedRangeNotSatisfiable:
|
||||
_ = resp.Body.Close()
|
||||
return &Media{Status: resp.StatusCode, Header: passed(resp.Header, false), Body: http.NoBody}, nil
|
||||
}
|
||||
body, _ := io.ReadAll(io.LimitReader(resp.Body, maxReplyBytes))
|
||||
_ = resp.Body.Close()
|
||||
return nil, errorFor(resp.StatusCode, body)
|
||||
}
|
||||
|
||||
func mediaTypeOK(kind, contentType string) bool {
|
||||
mt, _, err := mime.ParseMediaType(contentType)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if kind == MediaStream {
|
||||
return strings.HasPrefix(mt, "audio/")
|
||||
}
|
||||
return mt == "image/jpeg"
|
||||
}
|
||||
|
||||
// passed copies the headers of a friend's answer that go on to the listener.
|
||||
func passed(from http.Header, withType bool) http.Header {
|
||||
out := http.Header{}
|
||||
for _, k := range mediaResponseHeaders {
|
||||
if !withType && (k == "Content-Type" || k == "Content-Length") {
|
||||
continue
|
||||
}
|
||||
if v := from.Get(k); v != "" {
|
||||
out.Set(k, v)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import (
|
|||
"context"
|
||||
"crypto/ed25519"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
|
@ -175,6 +176,10 @@ func (d *direct) Get(context.Context, string, string, Auth) (int, []byte, error)
|
|||
return 0, nil, errors.New("not used")
|
||||
}
|
||||
|
||||
func (d *direct) Open(context.Context, string, string, Auth, http.Header) (*http.Response, error) {
|
||||
return nil, errors.New("not used")
|
||||
}
|
||||
|
||||
type clock struct{ t time.Time }
|
||||
|
||||
func (c *clock) now() time.Time { return c.t }
|
||||
|
|
@ -403,6 +408,10 @@ func (s swapKey) Get(ctx context.Context, addr, uri string, a Auth) (int, []byte
|
|||
return s.real.Get(ctx, addr, uri, a)
|
||||
}
|
||||
|
||||
func (s swapKey) Open(ctx context.Context, addr, uri string, a Auth, h http.Header) (*http.Response, error) {
|
||||
return s.real.Open(ctx, addr, uri, a, h)
|
||||
}
|
||||
|
||||
func (s swapKey) Pair(ctx context.Context, addr string, req PairRequest) (PairReply, error) {
|
||||
r, err := s.real.Pair(ctx, addr, req)
|
||||
if err != nil {
|
||||
|
|
|
|||
|
|
@ -81,3 +81,8 @@ test('a very long or empty artist name does not break the photo', () => {
|
|||
fireEvent.error(container.querySelector('img')!)
|
||||
expect(screen.getByText('?')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('the cover of a friend’s album comes through this server, from the friend’s route', () => {
|
||||
const { container } = render(<Cover albumId={12} friend={3} size={64} />)
|
||||
expect(container.querySelector('img')!.getAttribute('src')).toBe('/api/v1/friends/3/albums/12/cover')
|
||||
})
|
||||
|
|
|
|||
|
|
@ -1,17 +1,20 @@
|
|||
import { useState } from 'react'
|
||||
import { mediaUrl, useAccessToken } from '@/auth/session'
|
||||
import { coverPath } from '@/player/media'
|
||||
|
||||
interface CoverProps {
|
||||
albumId: number | null
|
||||
/** The friend whose album it is, when it is not one of this server's. */
|
||||
friend?: number
|
||||
/** Pixels. With `fluid` it is the largest size: the cover shrinks to fit a narrow screen. */
|
||||
size: number
|
||||
fluid?: boolean
|
||||
}
|
||||
|
||||
/** The cover of an album, or concentric rings when there is none (or it cannot be loaded). */
|
||||
export default function Cover({ albumId, size, fluid = false }: CoverProps) {
|
||||
export default function Cover({ albumId, friend, size, fluid = false }: CoverProps) {
|
||||
useAccessToken() // the URL carries the token, so it has to follow a renewal
|
||||
const src = albumId === null ? null : mediaUrl(`/albums/${albumId}/cover`)
|
||||
const src = albumId === null ? null : mediaUrl(coverPath(friend, albumId))
|
||||
// A failure is remembered for this URL only: a renewed token makes a new URL, which is tried again.
|
||||
const [failed, setFailed] = useState<string | null>(null)
|
||||
const showImage = src !== null && failed !== src
|
||||
|
|
|
|||
|
|
@ -6,7 +6,11 @@ import TrackRow from './TrackRow'
|
|||
/** The songs of a list. Clicking one plays the whole list from that song. */
|
||||
export default function TrackList({ tracks }: { tracks: Track[] }) {
|
||||
const playTracks = usePlayer((s) => s.playTracks)
|
||||
const playingId = usePlayer((s) => currentTrack(s)?.id)
|
||||
// Only a track of this server: a friend's may share the id.
|
||||
const playingId = usePlayer((s) => {
|
||||
const now = currentTrack(s)
|
||||
return now && !now.friend ? now.id : undefined
|
||||
})
|
||||
return (
|
||||
<div className="flex flex-col">
|
||||
{tracks.map((track, i) => (
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ import VolumeControl from '@/components/VolumeControl'
|
|||
import { Button } from '@/components/ui/button'
|
||||
import { Dialog, DialogContent, DialogDescription, DialogTitle } from '@/components/ui/dialog'
|
||||
import { formatTime } from '@/lib/time'
|
||||
import { albumHref, artistHref } from '@/player/media'
|
||||
import { currentTrack, usePlayer } from '@/player/store'
|
||||
import { useNowPlayingUi } from '@/player/ui'
|
||||
import PlayerControls from './PlayerControls'
|
||||
|
|
@ -65,7 +66,7 @@ export default function NowPlaying() {
|
|||
|
||||
<div className="mx-auto flex w-full max-w-5xl flex-wrap items-center justify-center gap-x-16 gap-y-8 pt-10">
|
||||
<div className="flex min-w-0 flex-[1_1_320px] justify-center">
|
||||
<Cover albumId={track.album?.id ?? null} size={520} fluid />
|
||||
<Cover albumId={track.album?.id ?? null} friend={track.friend} size={520} fluid />
|
||||
</div>
|
||||
|
||||
<div className="flex min-w-0 flex-[1_1_380px] flex-col gap-7">
|
||||
|
|
@ -79,7 +80,7 @@ export default function NowPlaying() {
|
|||
: track.artists.map((a, i) => (
|
||||
<span key={a.id}>
|
||||
{i > 0 && ', '}
|
||||
<Link to={`/artists/${a.id}`} onClick={() => setOpen(false)} className="hover:underline">
|
||||
<Link to={artistHref(track, a)} onClick={() => setOpen(false)} className="hover:underline">
|
||||
{a.name}
|
||||
</Link>
|
||||
</span>
|
||||
|
|
@ -87,7 +88,7 @@ export default function NowPlaying() {
|
|||
</p>
|
||||
{track.album && (
|
||||
<Link
|
||||
to={`/albums/${track.album.id}`}
|
||||
to={albumHref(track, track.album)}
|
||||
onClick={() => setOpen(false)}
|
||||
className="text-muted-foreground hover:underline"
|
||||
>
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ import { beforeEach, expect, test, vi } from 'vitest'
|
|||
import type { Track } from '@/api/catalog'
|
||||
import { sessionStore } from '@/auth/session'
|
||||
import Scrubber from '@/components/Scrubber'
|
||||
import TrackList from '@/components/TrackList'
|
||||
import TrackRow from '@/components/TrackRow'
|
||||
import { initI18n } from '@/i18n'
|
||||
import { usePlayer } from '@/player/store'
|
||||
|
|
@ -326,3 +327,31 @@ test('the seek bar of the player bar is 44 pixels high to take a thumb', () => {
|
|||
render(<Scrubber positionMs={0} durationMs={1000} onSeek={() => {}} variant="line" />)
|
||||
expect(screen.getByRole('slider')).toHaveClass('h-11')
|
||||
})
|
||||
|
||||
const theirs = (n: number) => ({ ...track(n), friend: 3, album: { id: 10, title: 'Their Album' }, artists: [{ id: 5, name: 'Their Band' }] })
|
||||
|
||||
test('the bar shows a friend’s track with its cover and links to the music of the friend, not to a local page', () => {
|
||||
act(() => usePlayer.getState().playTracks([theirs(1)]))
|
||||
const { container } = renderBar()
|
||||
expect(container.querySelector('img')!.getAttribute('src')).toContain('/api/v1/friends/3/albums/10/cover')
|
||||
expect(screen.getByRole('link', { name: 'Their Band' })).toHaveAttribute('href', '/friends/3?tab=albums&artist=5&of=Their+Band')
|
||||
})
|
||||
|
||||
test('the full-screen player links a friend’s track to the music of the friend', async () => {
|
||||
act(() => usePlayer.getState().playTracks([theirs(1)]))
|
||||
renderBar()
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Open the full-screen player' }))
|
||||
const dialog = screen.getByRole('dialog')
|
||||
expect(within(dialog).getByRole('link', { name: 'Their Album' })).toHaveAttribute('href', '/friends/3?tab=songs&album=10&of=Their+Album')
|
||||
expect(within(dialog).getByRole('link', { name: 'Their Band' })).toHaveAttribute('href', '/friends/3?tab=albums&artist=5&of=Their+Band')
|
||||
})
|
||||
|
||||
test('a local list does not mark a row because a friend’s track with the same id is playing', () => {
|
||||
act(() => usePlayer.getState().playTracks([theirs(1)]))
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<TrackList tracks={[a]} />
|
||||
</MemoryRouter>,
|
||||
)
|
||||
expect(screen.getByRole('button', { name: /Song 1/ })).not.toHaveAttribute('aria-current')
|
||||
})
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ import Scrubber from '@/components/Scrubber'
|
|||
import VolumeControl from '@/components/VolumeControl'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { formatTime } from '@/lib/time'
|
||||
import { artistHref } from '@/player/media'
|
||||
import { currentTrack, usePlayer } from '@/player/store'
|
||||
import { useNowPlayingUi } from '@/player/ui'
|
||||
import NowPlaying from './NowPlaying'
|
||||
|
|
@ -60,7 +61,7 @@ export default function PlayerBar() {
|
|||
{track ? (
|
||||
<>
|
||||
<button type="button" aria-label={t('player.open')} onClick={() => setOpen(true)} className="rounded-md">
|
||||
<Cover albumId={track.album?.id ?? null} size={56} />
|
||||
<Cover albumId={track.album?.id ?? null} friend={track.friend} size={56} />
|
||||
</button>
|
||||
<div className="flex min-w-0 flex-col">
|
||||
<button type="button" onClick={() => setOpen(true)} className="truncate text-left font-bold">
|
||||
|
|
@ -72,7 +73,7 @@ export default function PlayerBar() {
|
|||
: track.artists.map((a, i) => (
|
||||
<span key={a.id}>
|
||||
{i > 0 && ', '}
|
||||
<Link to={`/artists/${a.id}`} className="hover:underline">
|
||||
<Link to={artistHref(track, a)} className="hover:underline">
|
||||
{a.name}
|
||||
</Link>
|
||||
</span>
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue