A friend's server can now read what an admin chose to share.
- A library has a shared flag, off by default (migration 0024), set with
PATCH /libraries/{id}. Changing it never waits for a scan.
- Requests between friends are signed with each server's Ed25519 key: the
method, the path and query from /api/v1/peer on, a date, a nonce and the
hash of the empty body. A date more than two minutes off, a nonce used
before, an unknown or removed key and a bad signature all get the same
401. A friend still waiting for approval gets 403, and while federation is
off the routes are missing.
- Routes under /api/v1/peer: info, artists, albums, tracks, covers and
streaming with Range. The catalogue, the counts and the format come from
the shared libraries only, and the file served is the one in a shared
library. No path, library id, listen, taste, user or provider data is part
of an answer.
- A friend never makes this server build a cover, read an audio file or ask
a provider: only covers already built from the audio files are served.
- Per-friend limits, set by the admin: parallel streams (default 3) and KiB
a second (default 4096, 0 for none), shared by all the streams of a friend.
- A log of the last requests friends made (route, status, bytes; never the
query), kept for 7 days, in GET /federation/requests.
- POST /federation/friends/{id}/check lets the side that pasted an invite
find out that the other admin approved; a signed call from a friend this
server is waiting for makes it active too.
- Admin: a Shared with friends switch on each library, which asks first, and
limits, recent requests and a Check button in the Federation section, in
English and Italian.
- OpenAPI paths and schemas, contract test, two real servers checked end to
end with tagged audio files.
647 lines
21 KiB
Go
647 lines
21 KiB
Go
package images
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"errors"
|
|
"image"
|
|
"image/color"
|
|
"image/jpeg"
|
|
"io"
|
|
"os"
|
|
"path/filepath"
|
|
"strconv"
|
|
"sync"
|
|
"sync/atomic"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
type fakeStore struct {
|
|
mu sync.Mutex
|
|
recs map[string]Record
|
|
gets int
|
|
err error
|
|
}
|
|
|
|
func key(kind string, id int64) string { return kind + "/" + strconv.FormatInt(id, 10) }
|
|
|
|
func (f *fakeStore) Get(_ context.Context, kind string, id int64) (Record, bool, error) {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
f.gets++
|
|
r, ok := f.recs[key(kind, id)]
|
|
return r, ok, f.err
|
|
}
|
|
|
|
// Save keeps the record only when nothing was cleared since the Gen it carries was
|
|
// read, like the real store.
|
|
func (f *fakeStore) Save(_ context.Context, kind string, id int64, r Record) (bool, error) {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
if f.err != nil {
|
|
return false, f.err
|
|
}
|
|
if cur, ok := f.recs[key(kind, id)]; ok && cur.Gen != r.Gen {
|
|
return false, nil
|
|
}
|
|
f.recs[key(kind, id)] = r
|
|
return true, nil
|
|
}
|
|
|
|
// clear is what a changed file does: the record is marked stale and its generation moves.
|
|
func (f *fakeStore) clear(kind string, id int64) {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
cur := f.recs[key(kind, id)]
|
|
f.recs[key(kind, id)] = Record{Status: StatusStale, Gen: cur.Gen + 1}
|
|
}
|
|
|
|
type fakeSource struct {
|
|
files map[int64][]File
|
|
calls int32
|
|
}
|
|
|
|
func (f *fakeSource) AlbumFiles(_ context.Context, id int64) ([]File, error) {
|
|
atomic.AddInt32(&f.calls, 1)
|
|
files, ok := f.files[id]
|
|
if !ok {
|
|
return nil, ErrAlbumNotFound
|
|
}
|
|
return files, nil
|
|
}
|
|
|
|
type rig struct {
|
|
gate chan struct{} // when set, the embedded stub waits for it to be closed
|
|
svc *Service
|
|
store *fakeStore
|
|
src *fakeSource
|
|
root string
|
|
data string
|
|
embedded map[string][]byte // by full path
|
|
reads int32 // embedded reads
|
|
now time.Time
|
|
}
|
|
|
|
func jpegBytes(t *testing.T, w, h int, c color.Color) []byte {
|
|
t.Helper()
|
|
img := image.NewRGBA(image.Rect(0, 0, w, h))
|
|
for y := 0; y < h; y++ {
|
|
for x := 0; x < w; x++ {
|
|
img.Set(x, y, c)
|
|
}
|
|
}
|
|
var b bytes.Buffer
|
|
if err := jpeg.Encode(&b, img, nil); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return b.Bytes()
|
|
}
|
|
|
|
func newRig(t *testing.T) *rig {
|
|
t.Helper()
|
|
r := &rig{
|
|
store: &fakeStore{recs: map[string]Record{}}, root: t.TempDir(), data: filepath.Join(t.TempDir(), "data"),
|
|
embedded: map[string][]byte{}, now: time.Unix(1_700_000_000, 0),
|
|
}
|
|
if err := os.MkdirAll(filepath.Join(r.root, "Album One"), 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
r.write(t, "Album One/01.mp3", []byte("audio"))
|
|
r.write(t, "Album One/02.mp3", []byte("audio"))
|
|
r.src = &fakeSource{files: map[int64][]File{
|
|
1: {{Root: r.root, RelPath: "Album One/01.mp3"}, {Root: r.root, RelPath: "Album One/02.mp3"}},
|
|
}}
|
|
r.svc = NewService(r.data, r.store, r.src)
|
|
r.svc.embedded = func(path string) ([]byte, error) {
|
|
atomic.AddInt32(&r.reads, 1)
|
|
if r.gate != nil {
|
|
<-r.gate
|
|
}
|
|
if b, ok := r.embedded[path]; ok {
|
|
return b, nil
|
|
}
|
|
return nil, errors.New("no picture")
|
|
}
|
|
r.svc.now = func() time.Time { return r.now }
|
|
return r
|
|
}
|
|
|
|
func (r *rig) write(t *testing.T, rel string, data []byte) {
|
|
t.Helper()
|
|
if err := os.WriteFile(filepath.Join(r.root, filepath.FromSlash(rel)), data, 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
|
|
func (r *rig) read(t *testing.T, id int64, size Size) []byte {
|
|
t.Helper()
|
|
c, err := r.svc.AlbumCover(context.Background(), id, size)
|
|
if err != nil {
|
|
t.Fatalf("AlbumCover: %v", err)
|
|
}
|
|
defer c.File.Close()
|
|
b, _ := io.ReadAll(c.File)
|
|
return b
|
|
}
|
|
|
|
func TestTheEmbeddedPictureComesFirst(t *testing.T) {
|
|
r := newRig(t)
|
|
r.embedded[filepath.Join(r.root, "Album One/01.mp3")] = jpegBytes(t, 1500, 1500, color.RGBA{200, 0, 0, 255})
|
|
r.write(t, "Album One/cover.jpg", jpegBytes(t, 400, 400, color.RGBA{0, 0, 200, 255}))
|
|
img, _ := jpeg.Decode(bytes.NewReader(r.read(t, 1, Large)))
|
|
if w := img.Bounds().Dx(); w != 1000 {
|
|
t.Errorf("large is %d wide, want 1000", w)
|
|
}
|
|
red, _, blue, _ := img.At(500, 500).RGBA()
|
|
if red>>8 < 150 || blue>>8 > 80 {
|
|
t.Errorf("the cover is not the embedded one: (%d, %d)", red>>8, blue>>8)
|
|
}
|
|
rec := r.store.recs["album/1"]
|
|
if rec.Status != StatusOK || rec.Source != SourceEmbedded || rec.Width != 1500 || rec.ETag == "" {
|
|
t.Errorf("record = %+v", rec)
|
|
}
|
|
}
|
|
|
|
func TestTheSmallSizeIsSmall(t *testing.T) {
|
|
r := newRig(t)
|
|
r.embedded[filepath.Join(r.root, "Album One/01.mp3")] = jpegBytes(t, 1500, 1500, color.White)
|
|
cfg, _, err := image.DecodeConfig(bytes.NewReader(r.read(t, 1, Small)))
|
|
if err != nil || cfg.Width != 300 {
|
|
t.Errorf("small = %v err %v, want 300 wide", cfg, err)
|
|
}
|
|
}
|
|
|
|
func TestWithoutAnEmbeddedPictureTheFolderImageIsUsedInPriorityOrder(t *testing.T) {
|
|
r := newRig(t)
|
|
r.write(t, "Album One/scan-back.jpg", jpegBytes(t, 300, 300, color.RGBA{0, 200, 0, 255}))
|
|
r.write(t, "Album One/Folder.PNG", jpegBytes(t, 300, 300, color.RGBA{0, 0, 200, 255})) // wrong extension for the content, still a picture
|
|
r.write(t, "Album One/FRONT.jpg", jpegBytes(t, 300, 300, color.RGBA{200, 0, 0, 255}))
|
|
// "folder" outranks "front"; "scan-back" is not a cover name at all.
|
|
img, _ := jpeg.Decode(bytes.NewReader(r.read(t, 1, Large)))
|
|
_, _, blue, _ := img.At(100, 100).RGBA()
|
|
if blue>>8 < 150 {
|
|
t.Errorf("not the Folder.PNG: blue = %d", blue>>8)
|
|
}
|
|
if got := r.store.recs["album/1"].Source; got != SourceFolder {
|
|
t.Errorf("source = %q", got)
|
|
}
|
|
// "cover" outranks "folder" and "front".
|
|
r.store.clear("album", 1)
|
|
r.write(t, "Album One/cover.jpeg", jpegBytes(t, 300, 300, color.RGBA{0, 200, 0, 255}))
|
|
img, _ = jpeg.Decode(bytes.NewReader(r.read(t, 1, Large)))
|
|
_, green, _, _ := img.At(100, 100).RGBA()
|
|
if green>>8 < 150 {
|
|
t.Errorf("not the cover.jpeg: green = %d", green>>8)
|
|
}
|
|
}
|
|
|
|
func TestAPictureThatCannotBeUsedFallsThroughToTheNextOne(t *testing.T) {
|
|
r := newRig(t)
|
|
r.embedded[filepath.Join(r.root, "Album One/01.mp3")] = []byte("this is not a picture")
|
|
r.write(t, "Album One/cover.jpg", []byte("neither is this"))
|
|
r.write(t, "Album One/folder.jpg", jpegBytes(t, 200, 200, color.White))
|
|
if got := r.read(t, 1, Large); len(got) == 0 {
|
|
t.Fatal("nothing served")
|
|
}
|
|
if got := r.store.recs["album/1"].Source; got != SourceFolder {
|
|
t.Errorf("source = %q, want the folder.jpg that works", got)
|
|
}
|
|
}
|
|
|
|
func TestOnlyTheFirstFewFilesAreTriedForAnEmbeddedPicture(t *testing.T) {
|
|
r := newRig(t)
|
|
var files []File
|
|
for i := 0; i < 10; i++ {
|
|
files = append(files, File{Root: r.root, RelPath: "Album One/01.mp3"})
|
|
}
|
|
r.src.files[1] = files
|
|
_, err := r.svc.AlbumCover(context.Background(), 1, Large)
|
|
if !errors.Is(err, ErrNoCover) {
|
|
t.Fatalf("err = %v", err)
|
|
}
|
|
if n := atomic.LoadInt32(&r.reads); n > MaxFilesTried {
|
|
t.Errorf("%d files read, want at most %d", n, MaxFilesTried)
|
|
}
|
|
}
|
|
|
|
func TestAnAlbumWithoutACoverIsRememberedForADayOnly(t *testing.T) {
|
|
r := newRig(t)
|
|
if _, err := r.svc.AlbumCover(context.Background(), 1, Large); !errors.Is(err, ErrNoCover) {
|
|
t.Fatalf("err = %v", err)
|
|
}
|
|
if rec := r.store.recs["album/1"]; rec.Status != StatusNone {
|
|
t.Fatalf("record = %+v", rec)
|
|
}
|
|
calls := atomic.LoadInt32(&r.src.calls)
|
|
reads := atomic.LoadInt32(&r.reads)
|
|
for i := 0; i < 5; i++ { // the disk is not searched again
|
|
if _, err := r.svc.AlbumCover(context.Background(), 1, Large); !errors.Is(err, ErrNoCover) {
|
|
t.Fatalf("err = %v", err)
|
|
}
|
|
}
|
|
if atomic.LoadInt32(&r.src.calls) != calls || atomic.LoadInt32(&r.reads) != reads {
|
|
t.Error("the files were looked at again within the day")
|
|
}
|
|
// A cover.jpg was added meanwhile; a day later it is found.
|
|
r.write(t, "Album One/cover.jpg", jpegBytes(t, 300, 300, color.White))
|
|
r.now = r.now.Add(NoCoverTTL + time.Minute)
|
|
if got := r.read(t, 1, Large); len(got) == 0 {
|
|
t.Error("the new cover was not found after the day")
|
|
}
|
|
}
|
|
|
|
func TestAnAlbumWhoseRecordWasClearedIsBuiltAgain(t *testing.T) {
|
|
r := newRig(t)
|
|
r.write(t, "Album One/cover.jpg", jpegBytes(t, 300, 300, color.RGBA{200, 0, 0, 255}))
|
|
first := r.read(t, 1, Large)
|
|
r.write(t, "Album One/cover.jpg", jpegBytes(t, 300, 300, color.RGBA{0, 0, 200, 255}))
|
|
if second := r.read(t, 1, Large); !bytes.Equal(first, second) {
|
|
t.Error("a cover that is stored was built again for nothing")
|
|
}
|
|
r.store.clear("album", 1) // what a changed file does (see the storage)
|
|
if third := r.read(t, 1, Large); bytes.Equal(first, third) {
|
|
t.Error("after the record was cleared the old picture was served")
|
|
}
|
|
}
|
|
|
|
func TestAStoredFileThatWentMissingIsBuiltAgain(t *testing.T) {
|
|
r := newRig(t)
|
|
r.write(t, "Album One/cover.jpg", jpegBytes(t, 300, 300, color.White))
|
|
r.read(t, 1, Large)
|
|
if err := os.Remove(filepath.Join(r.data, "images", "album", "1-large.jpg")); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if got := r.read(t, 1, Large); len(got) == 0 {
|
|
t.Error("nothing served after the stored file was removed")
|
|
}
|
|
}
|
|
|
|
func TestStoredFilesArePrivate(t *testing.T) {
|
|
r := newRig(t)
|
|
r.write(t, "Album One/cover.jpg", jpegBytes(t, 300, 300, color.White))
|
|
r.read(t, 1, Large)
|
|
for _, p := range []string{filepath.Join(r.data, "images", "album", "1-large.jpg"), filepath.Join(r.data, "images", "album", "1-small.jpg")} {
|
|
info, err := os.Stat(p)
|
|
if err != nil || info.Mode().Perm()&0o077 != 0 {
|
|
t.Errorf("%s: %v %v, want no access for group or others", p, info, err)
|
|
}
|
|
}
|
|
// And no half-written files are left behind.
|
|
entries, _ := os.ReadDir(filepath.Join(r.data, "images", "album"))
|
|
for _, e := range entries {
|
|
if filepath.Ext(e.Name()) != ".jpg" {
|
|
t.Errorf("stray file %s", e.Name())
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestAnUnknownAlbumIsNotFoundAndLeavesNoRecord(t *testing.T) {
|
|
r := newRig(t)
|
|
if _, err := r.svc.AlbumCover(context.Background(), 9, Large); !errors.Is(err, ErrAlbumNotFound) {
|
|
t.Errorf("err = %v", err)
|
|
}
|
|
if len(r.store.recs) != 0 {
|
|
t.Errorf("records = %v", r.store.recs)
|
|
}
|
|
if _, err := r.svc.AlbumCover(context.Background(), 1, Size("huge")); !errors.Is(err, ErrInvalidSize) {
|
|
t.Errorf("a bad size: err = %v", err)
|
|
}
|
|
if _, err := r.svc.AlbumCover(context.Background(), 0, Large); !errors.Is(err, ErrAlbumNotFound) {
|
|
t.Errorf("album 0: err = %v", err)
|
|
}
|
|
}
|
|
|
|
func TestPicturesOutsideTheLibraryAreNeverRead(t *testing.T) {
|
|
r := newRig(t)
|
|
outside := t.TempDir()
|
|
if err := os.WriteFile(filepath.Join(outside, "secret.jpg"), jpegBytes(t, 300, 300, color.RGBA{255, 0, 0, 255}), 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
// A cover.jpg that is a link to a picture outside the library...
|
|
if err := os.Symlink(filepath.Join(outside, "secret.jpg"), filepath.Join(r.root, "Album One", "cover.jpg")); err != nil {
|
|
t.Skip("symlinks not supported:", err)
|
|
}
|
|
// ...and a folder that is a link to a directory outside it.
|
|
if err := os.Symlink(outside, filepath.Join(r.root, "linked")); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
r.src.files[2] = []File{{Root: r.root, RelPath: "linked/x.mp3"}}
|
|
for _, id := range []int64{1, 2} {
|
|
if _, err := r.svc.AlbumCover(context.Background(), id, Large); !errors.Is(err, ErrNoCover) {
|
|
t.Errorf("album %d: err = %v, want no cover: the picture is outside the library", id, err)
|
|
}
|
|
}
|
|
// An embedded picture is not read from a file that leaves the library either: the
|
|
// file exists (outside), so only the check can be what refuses it.
|
|
if err := os.WriteFile(filepath.Join(outside, "x.mp3"), []byte("audio"), 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
r.embedded[filepath.Join(r.root, "linked/x.mp3")] = jpegBytes(t, 300, 300, color.White)
|
|
r.store.clear("album", 2)
|
|
if _, err := r.svc.AlbumCover(context.Background(), 2, Large); !errors.Is(err, ErrNoCover) {
|
|
t.Errorf("embedded picture of a file outside the library: err = %v", err)
|
|
}
|
|
}
|
|
|
|
func TestOnlyRegularPictureFilesAreRead(t *testing.T) {
|
|
r := newRig(t)
|
|
if err := os.Mkdir(filepath.Join(r.root, "Album One", "cover.jpg"), 0o755); err != nil { // a folder called cover.jpg
|
|
t.Fatal(err)
|
|
}
|
|
big := make([]byte, MaxSourceBytes+10)
|
|
copy(big, jpegBytes(t, 300, 300, color.White))
|
|
r.write(t, "Album One/folder.jpg", big) // too big
|
|
if _, err := r.svc.AlbumCover(context.Background(), 1, Large); !errors.Is(err, ErrNoCover) {
|
|
t.Errorf("err = %v, want no cover", err)
|
|
}
|
|
}
|
|
|
|
func TestManyAsksAtOnceBuildItOnce(t *testing.T) {
|
|
r := newRig(t)
|
|
r.embedded[filepath.Join(r.root, "Album One/01.mp3")] = jpegBytes(t, 1200, 1200, color.White)
|
|
r.gate = make(chan struct{}) // the build waits here, so that every ask arrives while it runs
|
|
var wg sync.WaitGroup
|
|
errs := make(chan error, 20)
|
|
for i := 0; i < 20; i++ {
|
|
wg.Add(1)
|
|
go func() {
|
|
defer wg.Done()
|
|
c, err := r.svc.AlbumCover(context.Background(), 1, Large)
|
|
if err == nil {
|
|
c.File.Close()
|
|
}
|
|
errs <- err
|
|
}()
|
|
}
|
|
time.Sleep(100 * time.Millisecond)
|
|
close(r.gate)
|
|
wg.Wait()
|
|
close(errs)
|
|
for err := range errs {
|
|
if err != nil {
|
|
t.Errorf("err = %v", err)
|
|
}
|
|
}
|
|
if n := atomic.LoadInt32(&r.reads); n != 1 {
|
|
t.Errorf("the embedded picture was read %d times, want 1", n)
|
|
}
|
|
}
|
|
|
|
func TestAListenerWhoLeavesDoesNotStopTheBuild(t *testing.T) {
|
|
r := newRig(t)
|
|
r.embedded[filepath.Join(r.root, "Album One/01.mp3")] = jpegBytes(t, 600, 600, color.White)
|
|
r.gate = make(chan struct{})
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
errc := make(chan error, 1)
|
|
go func() {
|
|
_, err := r.svc.AlbumCover(ctx, 1, Large)
|
|
errc <- err
|
|
}()
|
|
time.Sleep(50 * time.Millisecond)
|
|
cancel() // the first listener gives up while the build is still reading
|
|
if err := <-errc; !errors.Is(err, context.Canceled) {
|
|
t.Fatalf("err = %v, want the listener to be told it left", err)
|
|
}
|
|
close(r.gate)
|
|
// The build went on: the next one finds the cover without reading the file again.
|
|
deadline := time.Now().Add(5 * time.Second)
|
|
for {
|
|
if rec, ok, _ := r.store.Get(context.Background(), "album", 1); ok && rec.Status == StatusOK {
|
|
break
|
|
}
|
|
if time.Now().After(deadline) {
|
|
t.Fatal("the build was stopped when the listener left")
|
|
}
|
|
time.Sleep(10 * time.Millisecond)
|
|
}
|
|
reads := atomic.LoadInt32(&r.reads)
|
|
if got := r.read(t, 1, Large); len(got) == 0 || atomic.LoadInt32(&r.reads) != reads {
|
|
t.Error("the second listener did not get the cover that was built")
|
|
}
|
|
}
|
|
|
|
func TestAChangeDuringABuildIsNotUndoneByIt(t *testing.T) {
|
|
r := newRig(t)
|
|
r.gate = make(chan struct{})
|
|
done := make(chan error, 1)
|
|
go func() {
|
|
_, err := r.svc.AlbumCover(context.Background(), 1, Large)
|
|
done <- err
|
|
}()
|
|
time.Sleep(50 * time.Millisecond) // the build looked at the files and found no picture
|
|
// A new file arrives in the album, and with it a picture.
|
|
r.write(t, "Album One/cover.jpg", jpegBytes(t, 400, 400, color.RGBA{0, 200, 0, 255}))
|
|
r.store.clear("album", 1)
|
|
close(r.gate)
|
|
// The build that started before the change must not leave its "no cover" behind.
|
|
got, err := func() ([]byte, error) {
|
|
<-done
|
|
c, err := r.svc.AlbumCover(context.Background(), 1, Large)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer c.File.Close()
|
|
return io.ReadAll(c.File)
|
|
}()
|
|
if err != nil || len(got) == 0 {
|
|
t.Fatalf("after the change: %v, want the new cover", err)
|
|
}
|
|
if rec := r.store.recs["album/1"]; rec.Status != StatusOK {
|
|
t.Errorf("record = %+v, want the cover that was added", rec)
|
|
}
|
|
}
|
|
|
|
func TestAtMostAFewCoversAreBuiltAtOnce(t *testing.T) {
|
|
r := newRig(t)
|
|
var inFlight, maxSeen int32
|
|
r.gate = nil
|
|
r.svc.embedded = func(string) ([]byte, error) {
|
|
n := atomic.AddInt32(&inFlight, 1)
|
|
for {
|
|
m := atomic.LoadInt32(&maxSeen)
|
|
if n <= m || atomic.CompareAndSwapInt32(&maxSeen, m, n) {
|
|
break
|
|
}
|
|
}
|
|
time.Sleep(30 * time.Millisecond)
|
|
atomic.AddInt32(&inFlight, -1)
|
|
return nil, errors.New("no picture")
|
|
}
|
|
for id := int64(10); id < 30; id++ {
|
|
r.src.files[id] = []File{{Root: r.root, RelPath: "Album One/01.mp3"}}
|
|
}
|
|
var wg sync.WaitGroup
|
|
for id := int64(10); id < 30; id++ {
|
|
wg.Add(1)
|
|
go func() {
|
|
defer wg.Done()
|
|
_, _ = r.svc.AlbumCover(context.Background(), id, Large)
|
|
}()
|
|
}
|
|
wg.Wait()
|
|
if m := atomic.LoadInt32(&maxSeen); m < 1 || m > MaxParallelBuilds {
|
|
t.Errorf("%d builds at once, want at most %d", m, MaxParallelBuilds)
|
|
}
|
|
}
|
|
|
|
func TestACoverThatWasFoundIsCheckedAgainAfterAWhile(t *testing.T) {
|
|
r := newRig(t)
|
|
r.write(t, "Album One/cover.jpg", jpegBytes(t, 300, 300, color.RGBA{200, 0, 0, 255}))
|
|
first := r.read(t, 1, Large)
|
|
r.write(t, "Album One/cover.jpg", jpegBytes(t, 300, 300, color.RGBA{0, 0, 200, 255}))
|
|
if again := r.read(t, 1, Large); !bytes.Equal(first, again) {
|
|
t.Error("rebuilt for nothing")
|
|
}
|
|
r.now = r.now.Add(CoverTTL + time.Minute)
|
|
if later := r.read(t, 1, Large); bytes.Equal(first, later) {
|
|
t.Error("a picture replaced in the folder was never noticed")
|
|
}
|
|
}
|
|
|
|
func TestACDFolderUsesThePictureOfItsParent(t *testing.T) {
|
|
r := newRig(t)
|
|
for _, d := range []string{"Double/CD1", "Double/Disc 2"} {
|
|
if err := os.MkdirAll(filepath.Join(r.root, filepath.FromSlash(d)), 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
r.write(t, d+"/01.mp3", []byte("audio"))
|
|
}
|
|
r.write(t, "Double/cover.jpg", jpegBytes(t, 300, 300, color.White))
|
|
r.src.files[5] = []File{{Root: r.root, RelPath: "Double/CD1/01.mp3"}, {Root: r.root, RelPath: "Double/Disc 2/01.mp3"}}
|
|
if got := r.read(t, 5, Large); len(got) == 0 {
|
|
t.Fatal("no cover from the folder above the disc folders")
|
|
}
|
|
// A folder that is not a disc folder does not borrow the picture of its parent.
|
|
if err := os.MkdirAll(filepath.Join(r.root, "Various", "Album A"), 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
r.write(t, "Various/Album A/01.mp3", []byte("audio"))
|
|
r.write(t, "Various/cover.jpg", jpegBytes(t, 300, 300, color.White))
|
|
r.src.files[6] = []File{{Root: r.root, RelPath: "Various/Album A/01.mp3"}}
|
|
if _, err := r.svc.AlbumCover(context.Background(), 6, Large); !errors.Is(err, ErrNoCover) {
|
|
t.Errorf("err = %v, want no cover: that picture belongs to the folder, not to this album", err)
|
|
}
|
|
}
|
|
|
|
func TestAStoredFileThatIsEmptyIsBuiltAgain(t *testing.T) {
|
|
r := newRig(t)
|
|
r.write(t, "Album One/cover.jpg", jpegBytes(t, 300, 300, color.White))
|
|
r.read(t, 1, Large)
|
|
if err := os.WriteFile(filepath.Join(r.data, "images", "album", "1-large.jpg"), nil, 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if got := r.read(t, 1, Large); len(got) == 0 {
|
|
t.Error("an empty file was served")
|
|
}
|
|
}
|
|
|
|
func TestOldLeftoverTemporaryFilesAreRemoved(t *testing.T) {
|
|
r := newRig(t)
|
|
dir := filepath.Join(r.data, "images", "album")
|
|
if err := os.MkdirAll(dir, 0o700); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
old, fresh := filepath.Join(dir, "tmp-old"), filepath.Join(dir, "tmp-fresh")
|
|
for _, p := range []string{old, fresh} {
|
|
if err := os.WriteFile(p, []byte("x"), 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
past := time.Now().Add(-2 * time.Hour)
|
|
if err := os.Chtimes(old, past, past); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
r.write(t, "Album One/cover.jpg", jpegBytes(t, 300, 300, color.White))
|
|
r.read(t, 1, Large)
|
|
if _, err := os.Stat(old); !os.IsNotExist(err) {
|
|
t.Error("a temporary file from a crash was kept")
|
|
}
|
|
if _, err := os.Stat(fresh); err != nil {
|
|
t.Error("a recent temporary file (maybe of a build in progress) was removed")
|
|
}
|
|
info, err := os.Stat(filepath.Join(r.data, "images"))
|
|
if err != nil || info.Mode().Perm()&0o077 != 0 {
|
|
t.Errorf("the data folder is %v, want no access for others", info.Mode())
|
|
}
|
|
}
|
|
|
|
func TestStoreErrorsPass(t *testing.T) {
|
|
r := newRig(t)
|
|
boom := errors.New("boom")
|
|
r.store.err = boom
|
|
if _, err := r.svc.AlbumCover(context.Background(), 1, Large); !errors.Is(err, boom) {
|
|
t.Errorf("err = %v", err)
|
|
}
|
|
}
|
|
|
|
func TestTheETagChangesWithThePictureNotTheSize(t *testing.T) {
|
|
r := newRig(t)
|
|
r.write(t, "Album One/cover.jpg", jpegBytes(t, 600, 600, color.RGBA{200, 0, 0, 255}))
|
|
c1, err := r.svc.AlbumCover(context.Background(), 1, Large)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
c1.File.Close()
|
|
c2, _ := r.svc.AlbumCover(context.Background(), 1, Small)
|
|
c2.File.Close()
|
|
if c1.ETag == "" || c1.ETag == c2.ETag {
|
|
t.Errorf("etags: large %q, small %q: they must be set and differ by size", c1.ETag, c2.ETag)
|
|
}
|
|
r.store.clear("album", 1)
|
|
r.write(t, "Album One/cover.jpg", jpegBytes(t, 600, 600, color.RGBA{0, 0, 200, 255}))
|
|
c3, _ := r.svc.AlbumCover(context.Background(), 1, Large)
|
|
c3.File.Close()
|
|
if c3.ETag == c1.ETag {
|
|
t.Error("the picture changed but the etag did not")
|
|
}
|
|
}
|
|
|
|
func TestAFriendGetsOnlyACoverThatIsAlreadyBuiltFromTheFiles(t *testing.T) {
|
|
r := newRig(t)
|
|
ctx := context.Background()
|
|
stored := StoredOnly{r.svc}
|
|
|
|
// Nothing was built: nothing is built for a friend, and no file is read.
|
|
if _, err := stored.AlbumCover(ctx, 1, Large); !errors.Is(err, ErrNoCover) {
|
|
t.Fatalf("before anyone asked: %v, want ErrNoCover", err)
|
|
}
|
|
if n := atomic.LoadInt32(&r.src.calls) + atomic.LoadInt32(&r.reads); n != 0 {
|
|
t.Errorf("a friend's ask looked at the files %d times", n)
|
|
}
|
|
|
|
// A listener opens it: it is built from the files.
|
|
r.embedded[filepath.Join(r.root, "Album One/01.mp3")] = jpegBytes(t, 600, 600, color.White)
|
|
want := r.read(t, 1, Large)
|
|
c, err := stored.AlbumCover(ctx, 1, Large)
|
|
if err != nil {
|
|
t.Fatalf("after a listener built it: %v", err)
|
|
}
|
|
got, _ := io.ReadAll(c.File)
|
|
_ = c.File.Close()
|
|
if !bytes.Equal(got, want) {
|
|
t.Error("a friend gets another picture than a listener")
|
|
}
|
|
if s, err := stored.AlbumCover(ctx, 1, Small); err != nil {
|
|
t.Errorf("small: %v", err)
|
|
} else {
|
|
_ = s.File.Close()
|
|
}
|
|
if _, err := stored.AlbumCover(ctx, 1, Size("huge")); !errors.Is(err, ErrInvalidSize) {
|
|
t.Errorf("a bad size: %v", err)
|
|
}
|
|
if _, err := stored.AlbumCover(ctx, 0, Large); !errors.Is(err, ErrAlbumNotFound) {
|
|
t.Errorf("no album: %v", err)
|
|
}
|
|
|
|
// A cover that came from the Cover Art Archive has no licence to share: friends do not get it.
|
|
r.store.recs[key(kindAlbum, 1)] = Record{Status: StatusOK, Source: SourceCoverArt, CheckedAt: r.now, ETag: "x"}
|
|
if _, err := stored.AlbumCover(ctx, 1, Large); !errors.Is(err, ErrNoCover) {
|
|
t.Errorf("a cover from the archive: %v, want ErrNoCover", err)
|
|
}
|
|
// A cover whose file is gone is not an error for a friend, just no cover.
|
|
r.store.recs[key(kindAlbum, 2)] = Record{Status: StatusOK, Source: SourceEmbedded, CheckedAt: r.now, ETag: "y"}
|
|
if _, err := stored.AlbumCover(ctx, 2, Large); !errors.Is(err, ErrNoCover) {
|
|
t.Errorf("a file that is gone: %v, want ErrNoCover", err)
|
|
}
|
|
}
|