sonda/internal/api/http/lidarr_test.go
tgiachi a880b87a9e chore: move the module path to git.kmalloc.org/squid/sonda
Migrating hosting from Codeberg to git.kmalloc.org. Renames the
module path in go.mod, every internal import, and the OCI image
source label in the Dockerfile. Build and full test suite verified
green after the rename.
2026-11-15 17:30:29 +01:00

357 lines
16 KiB
Go

package httpapi
import (
"context"
"encoding/json"
"fmt"
"net/http"
"strings"
"testing"
"github.com/uptrace/bun"
"git.kmalloc.org/squid/sonda/internal/discovery"
"git.kmalloc.org/squid/sonda/internal/providers/lidarr"
"git.kmalloc.org/squid/sonda/internal/storage"
)
const lidarrAPIKey = "fedcba9876543210fedcba9876543210"
type fakeLidarr struct {
options lidarr.Options
err error
asked int
}
func (f *fakeLidarr) Options(context.Context) (lidarr.Options, error) {
f.asked++
return f.options, f.err
}
func newLidarrAPI(t *testing.T) (http.Handler, *fakeLidarr, string, string) {
t.Helper()
fake := &fakeLidarr{options: lidarr.Options{
QualityProfiles: []lidarr.Profile{{ID: 1, Name: "Any"}, {ID: 2, Name: "Lossless"}},
MetadataProfiles: []lidarr.Profile{{ID: 1, Name: "Standard"}},
RootFolders: []lidarr.RootFolder{{Path: "/music", Accessible: true}},
}}
h, _ := newTestEnvDB(t, func(d *Deps, _ *bun.DB) { d.Lidarr = fake })
admin := registerAndLogin(t, h)
_, bob := addUser(t, h, admin, "bob", false)
return h, fake, admin, bob
}
func TestLidarrIsListedAfterTheOthersWithItsAddressAndOptions(t *testing.T) {
h, _, admin, _ := newLidarrAPI(t)
list := do(t, h, "GET", "/api/v1/providers", admin, nil).Body["providers"].([]any)
if len(list) != 7 {
t.Fatalf("providers = %v", list)
}
for _, it := range list[:5] {
p := it.(map[string]any)
if p["needs_url"] != false || p["url"] != "" || p["lidarr"] != nil {
t.Errorf("%v has an address or Lidarr options: %v", p["name"], p)
}
}
l := list[5].(map[string]any)
sameKeys(t, "lidarr", l, "name", "enabled", "needs_api_key", "needs_url", "has_api_key", "contact", "url", "lidarr", "sends", "notes", "updated_at")
opts, _ := l["lidarr"].(map[string]any)
sameKeys(t, "lidarr options", opts, "quality_profile_id", "metadata_profile_id", "root_folder_path", "monitor", "search_missing")
if l["name"] != "lidarr" || l["enabled"] != false || l["needs_api_key"] != true || l["needs_url"] != true ||
opts["monitor"] != "all" || opts["search_missing"] != true || opts["quality_profile_id"] != float64(0) {
t.Errorf("lidarr = %v", l)
}
}
func TestSettingLidarrUp(t *testing.T) {
h, _, admin, _ := newLidarrAPI(t)
put := func(body map[string]any) resp { return do(t, h, "PUT", "/api/v1/providers/lidarr", admin, body) }
if r := put(map[string]any{"enabled": true}); r.Code != http.StatusBadRequest || errCode(r) != "invalid_input" {
t.Fatalf("enabled with nothing: %d %v", r.Code, r.Body)
}
r := put(map[string]any{"api_key": lidarrAPIKey, "url": "http://orion:8686/"})
if r.Code != http.StatusOK || r.Body["url"] != "http://orion:8686" || r.Body["has_api_key"] != true || r.Body["enabled"] != false {
t.Fatalf("key and address: %d %v", r.Code, r.Body)
}
if raw, _ := json.Marshal(r.Body); strings.Contains(string(raw), lidarrAPIKey) {
t.Fatal("the response carries the API key")
}
// What is not said in the options is the default; what is said replaces all of them.
r = put(map[string]any{"lidarr": map[string]any{"quality_profile_id": 2, "metadata_profile_id": 1, "root_folder_path": "/music"}})
opts, _ := r.Body["lidarr"].(map[string]any)
if r.Code != http.StatusOK || opts["quality_profile_id"] != float64(2) || opts["root_folder_path"] != "/music" ||
opts["monitor"] != "all" || opts["search_missing"] != true {
t.Fatalf("options: %d %v", r.Code, r.Body)
}
r = put(map[string]any{"lidarr": map[string]any{"quality_profile_id": 2, "metadata_profile_id": 1, "root_folder_path": "/music", "monitor": "latest", "search_missing": false}})
opts, _ = r.Body["lidarr"].(map[string]any)
if opts["monitor"] != "latest" || opts["search_missing"] != false {
t.Fatalf("options: %v", r.Body)
}
if r := put(map[string]any{"enabled": true}); r.Code != http.StatusOK || r.Body["enabled"] != true {
t.Fatalf("enable: %d %v", r.Code, r.Body)
}
for name, body := range map[string]map[string]any{
"an address that is not http": {"url": "ftp://orion"},
"an address with a secret": {"url": "http://orion/?apikey=x"},
"a short key": {"api_key": "abc"},
"a monitor that is not one": {"lidarr": map[string]any{"monitor": "everything"}},
} {
if r := put(body); r.Code != http.StatusBadRequest || errCode(r) != "invalid_input" {
t.Errorf("%s: %d %v", name, r.Code, r.Body)
}
}
// Clearing the address turns it off.
if r := put(map[string]any{"url": ""}); r.Code != http.StatusOK || r.Body["enabled"] != false || r.Body["url"] != "" {
t.Errorf("clear the address: %d %v", r.Code, r.Body)
}
// Other providers have neither.
if r := do(t, h, "PUT", "/api/v1/providers/musicbrainz", admin, map[string]any{"url": "http://orion"}); r.Code != http.StatusBadRequest {
t.Errorf("an address for MusicBrainz: %d %v", r.Code, r.Body)
}
}
func TestOnlyAnAdminReadsWhatLidarrOffers(t *testing.T) {
h, fake, admin, bob := newLidarrAPI(t)
if r := do(t, h, "GET", "/api/v1/providers/lidarr/options", "", nil); r.Code != http.StatusUnauthorized {
t.Errorf("without a token: %d", r.Code)
}
if r := do(t, h, "GET", "/api/v1/providers/lidarr/options", bob, nil); r.Code != http.StatusForbidden || errCode(r) != "admin_required" {
t.Errorf("as a user: %d %v", r.Code, r.Body)
}
if fake.asked != 0 {
t.Error("Lidarr was asked on behalf of someone who is not an admin")
}
r := do(t, h, "GET", "/api/v1/providers/lidarr/options", admin, nil)
if r.Code != http.StatusOK {
t.Fatalf("%d %v", r.Code, r.Body)
}
sameKeys(t, "options", r.Body, "quality_profiles", "metadata_profiles", "root_folders")
q := r.Body["quality_profiles"].([]any)
if len(q) != 2 || q[1].(map[string]any)["id"] != float64(2) || q[1].(map[string]any)["name"] != "Lossless" {
t.Errorf("quality profiles = %v", q)
}
sameKeys(t, "profile", q[0].(map[string]any), "id", "name")
f := r.Body["root_folders"].([]any)[0].(map[string]any)
sameKeys(t, "root folder", f, "path", "accessible")
if f["path"] != "/music" || f["accessible"] != true {
t.Errorf("root folder = %v", f)
}
}
func TestWhatGoesWrongAskingLidarrIsSaidPlainly(t *testing.T) {
h, fake, admin, _ := newLidarrAPI(t)
for _, c := range []struct {
err error
status int
code string
}{
{lidarr.ErrNotConfigured, http.StatusConflict, "lidarr_not_configured"},
{lidarr.ErrKeyRefused, http.StatusBadGateway, "lidarr_key_refused"},
{lidarr.ErrUnreachable, http.StatusBadGateway, "lidarr_unavailable"},
{lidarr.ErrBadResponse, http.StatusBadGateway, "lidarr_unavailable"},
{context.DeadlineExceeded, http.StatusBadGateway, "lidarr_unavailable"},
} {
fake.err = c.err
if r := do(t, h, "GET", "/api/v1/providers/lidarr/options", admin, nil); r.Code != c.status || errCode(r) != c.code {
t.Errorf("%v: %d %v, want %d %s", c.err, r.Code, r.Body, c.status, c.code)
}
}
}
// ---- sending an artist ----
type fakeSender struct {
outcome lidarr.Outcome
err error
sent []int64
presence lidarr.Presence
perr error
}
func (f *fakeSender) Send(_ context.Context, id int64) (lidarr.Outcome, error) {
if f.err != nil {
return "", f.err
}
f.sent = append(f.sent, id)
return f.outcome, nil
}
func (f *fakeSender) Presence(context.Context, int64) (lidarr.Presence, error) {
return f.presence, f.perr
}
func newSenderAPI(t *testing.T) (http.Handler, *fakeSender, string, string) {
t.Helper()
fake := &fakeSender{outcome: lidarr.Added}
h, _ := newTestEnvDB(t, func(d *Deps, _ *bun.DB) { d.LidarrArtists = fake })
admin := registerAndLogin(t, h)
_, bob := addUser(t, h, admin, "bob", false)
return h, fake, admin, bob
}
func TestOnlyAnAdminSendsAnArtistToLidarr(t *testing.T) {
h, fake, admin, bob := newSenderAPI(t)
if r := do(t, h, "POST", "/api/v1/artists/7/lidarr", "", nil); r.Code != http.StatusUnauthorized {
t.Errorf("without a token: %d", r.Code)
}
if r := do(t, h, "POST", "/api/v1/artists/7/lidarr", bob, nil); r.Code != http.StatusForbidden || errCode(r) != "admin_required" {
t.Errorf("as a user: %d %v", r.Code, r.Body)
}
if len(fake.sent) != 0 {
t.Fatal("an artist was sent on behalf of someone who is not an admin")
}
r := do(t, h, "POST", "/api/v1/artists/7/lidarr", admin, nil)
if r.Code != http.StatusOK || r.Body["status"] != "added" || len(fake.sent) != 1 || fake.sent[0] != 7 {
t.Fatalf("%d %v sent %v", r.Code, r.Body, fake.sent)
}
sameKeys(t, "sent", r.Body, "status")
fake.outcome = lidarr.AlreadyAdded
if r := do(t, h, "POST", "/api/v1/artists/7/lidarr", admin, nil); r.Code != http.StatusOK || r.Body["status"] != "already_added" {
t.Errorf("again: %d %v", r.Code, r.Body)
}
if r := do(t, h, "POST", "/api/v1/artists/abc/lidarr", admin, nil); r.Code != http.StatusBadRequest || errCode(r) != "invalid_input" {
t.Errorf("a bad id: %d %v", r.Code, r.Body)
}
}
func TestWhatStopsAnArtistFromBeingSentIsSaid(t *testing.T) {
h, fake, admin, _ := newSenderAPI(t)
for _, c := range []struct {
err error
status int
code string
}{
{discovery.ErrNotFound, http.StatusNotFound, "artist_not_found"},
{lidarr.ErrNoID, http.StatusUnprocessableEntity, "no_musicbrainz_id"},
{lidarr.ErrDisabled, http.StatusConflict, "lidarr_disabled"},
{lidarr.ErrNotSetUp, http.StatusConflict, "lidarr_not_configured"},
{lidarr.ErrNotConfigured, http.StatusConflict, "lidarr_not_configured"},
{lidarr.ErrNotFound, http.StatusUnprocessableEntity, "lidarr_unknown_artist"},
{lidarr.ErrKeyRefused, http.StatusBadGateway, "lidarr_key_refused"},
{lidarr.ErrUnreachable, http.StatusBadGateway, "lidarr_unavailable"},
{lidarr.ErrBadResponse, http.StatusBadGateway, "lidarr_unavailable"},
{context.DeadlineExceeded, http.StatusBadGateway, "lidarr_unavailable"},
} {
fake.err = c.err
if r := do(t, h, "POST", "/api/v1/artists/7/lidarr", admin, nil); r.Code != c.status || errCode(r) != c.code {
t.Errorf("%v: %d %v, want %d %s", c.err, r.Code, r.Body, c.status, c.code)
}
}
// A refusal carries Lidarr's reason, which the admin needs; a timeout says the artist may be there.
fake.err = fmt.Errorf("%w: Root folder does not exist", lidarr.ErrRejected)
r := do(t, h, "POST", "/api/v1/artists/7/lidarr", admin, nil)
msg, _ := r.Body["error"].(map[string]any)["message"].(string)
if r.Code != http.StatusUnprocessableEntity || errCode(r) != "lidarr_rejected" || !strings.Contains(msg, "Root folder does not exist") {
t.Errorf("rejected: %d %v", r.Code, r.Body)
}
for _, cause := range []error{lidarr.ErrUnreachable, lidarr.ErrBadResponse, context.DeadlineExceeded} {
fake.err = cause
r = do(t, h, "POST", "/api/v1/artists/7/lidarr", admin, nil)
msg, _ = r.Body["error"].(map[string]any)["message"].(string)
if !strings.Contains(msg, "may have been added") {
t.Errorf("%v: %q, want it to say the artist may have been added", cause, msg)
}
}
fake.err = context.Canceled
if r := do(t, h, "POST", "/api/v1/artists/7/lidarr", admin, nil); r.Code != 499 {
t.Errorf("a request that left: %d", r.Code)
}
}
func TestAnyUserSeesWhetherLidarrHasAnArtist(t *testing.T) {
h, fake, _, bob := newSenderAPI(t)
if r := do(t, h, "GET", "/api/v1/artists/7/lidarr", "", nil); r.Code != http.StatusUnauthorized {
t.Errorf("without a token: %d", r.Code)
}
fake.presence = lidarr.Presence{Status: "ok", InLidarr: true, Monitored: true}
r := do(t, h, "GET", "/api/v1/artists/7/lidarr", bob, nil)
sameKeys(t, "presence", r.Body, "provider_status", "in_lidarr", "monitored")
if r.Code != http.StatusOK || r.Body["provider_status"] != "ok" || r.Body["in_lidarr"] != true || r.Body["monitored"] != true {
t.Errorf("%d %v", r.Code, r.Body)
}
fake.presence = lidarr.Presence{Status: "disabled"}
if r := do(t, h, "GET", "/api/v1/artists/7/lidarr", bob, nil); r.Body["provider_status"] != "disabled" || r.Body["in_lidarr"] != false {
t.Errorf("off: %v", r.Body)
}
fake.perr = discovery.ErrNotFound
if r := do(t, h, "GET", "/api/v1/artists/7/lidarr", bob, nil); r.Code != http.StatusNotFound || errCode(r) != "artist_not_found" {
t.Errorf("unknown: %d %v", r.Code, r.Body)
}
}
func TestTheArtistsSentToLidarrAreListedAndSayWhenTheirMusicArrives(t *testing.T) {
fake := &fakeSender{outcome: lidarr.Added}
h, db := newTestEnvDB(t, func(d *Deps, _ *bun.DB) { d.LidarrArtists = fake })
admin := registerAndLogin(t, h)
_, bob := addUser(t, h, admin, "bob", false)
var artist int64
if err := db.QueryRow("INSERT INTO artists (mbid, name, name_key, search_key, discovered) VALUES ('a74b1b7f-71a5-4011-9441-d0b5e4122711', 'Chet Baker', 'chet baker', ?, ?) RETURNING id", storage.SearchKey("Chet Baker"), true).Scan(&artist); err != nil {
t.Fatal(err)
}
send := fmt.Sprintf("/api/v1/artists/%d/lidarr", artist)
if r := do(t, h, "GET", "/api/v1/lidarr/requests", admin, nil); r.Code != http.StatusOK || r.Body["total"] != 0.0 || len(r.Body["items"].([]any)) != 0 {
t.Fatalf("before sending anything: %d %v, want an empty list", r.Code, r.Body)
}
if r := do(t, h, "POST", send, admin, nil); r.Code != http.StatusOK {
t.Fatalf("send: %d %v", r.Code, r.Body)
}
if r := do(t, h, "POST", send, admin, nil); r.Code != http.StatusOK { // again: still one request
t.Fatalf("send again: %d %v", r.Code, r.Body)
}
r := do(t, h, "GET", "/api/v1/lidarr/requests", admin, nil)
sameKeys(t, "requests", r.Body, "items", "total", "limit", "offset", "counts")
if r.Body["total"] != 1.0 || r.Body["limit"] != 50.0 {
t.Fatalf("list = %v, want one request", r.Body)
}
counts, _ := r.Body["counts"].(map[string]any)
sameKeys(t, "counts", counts, "waiting", "arrived")
item := r.Body["items"].([]any)[0].(map[string]any)
sameKeys(t, "request", item, "id", "artist", "mbid", "requested_at", "status", "arrived_at")
who, _ := item["artist"].(map[string]any)
if who["name"] != "Chet Baker" || who["id"] != float64(artist) || item["status"] != "waiting" || item["arrived_at"] != nil || item["mbid"] != "a74b1b7f-71a5-4011-9441-d0b5e4122711" || counts["waiting"] != 1.0 {
t.Errorf("request = %v, counts %v", item, counts)
}
// Lidarr finishes and the music is scanned in.
seedSong(t, db, "a.flac", "Almost Blue", "Elvis Costello", "Chet Baker")
r = do(t, h, "GET", "/api/v1/lidarr/requests", admin, nil)
item = r.Body["items"].([]any)[0].(map[string]any)
if item["status"] != "arrived" || item["arrived_at"] == nil || r.Body["counts"].(map[string]any)["arrived"] != 1.0 {
t.Errorf("after the music arrived: %v", r.Body)
}
if r := do(t, h, "GET", "/api/v1/lidarr/requests?status=waiting", admin, nil); r.Body["total"] != 0.0 {
t.Errorf("waiting = %v, want none", r.Body)
}
if r := do(t, h, "GET", "/api/v1/lidarr/requests?status=lost", admin, nil); r.Code != http.StatusBadRequest || errCode(r) != "invalid_input" {
t.Errorf("a status that does not exist: %d %v", r.Code, r.Body)
}
if r := do(t, h, "GET", "/api/v1/lidarr/requests?limit=-1", admin, nil); r.Code != http.StatusBadRequest {
t.Errorf("a negative limit: %d", r.Code)
}
if r := do(t, h, "GET", "/api/v1/lidarr/requests", bob, nil); r.Code != http.StatusForbidden || errCode(r) != "admin_required" {
t.Errorf("as a user: %d %v, want 403 admin_required", r.Code, r.Body)
}
if r := do(t, h, "GET", "/api/v1/lidarr/requests", "", nil); r.Code != http.StatusUnauthorized {
t.Errorf("without a token: %d", r.Code)
}
}
func TestASendThatFailsIsNotWrittenDown(t *testing.T) {
fake := &fakeSender{err: lidarr.ErrDisabled}
h, db := newTestEnvDB(t, func(d *Deps, _ *bun.DB) { d.LidarrArtists = fake })
admin := registerAndLogin(t, h)
var artist int64
if err := db.QueryRow("INSERT INTO artists (name, name_key, search_key, discovered) VALUES ('Sade', 'sade', ?, ?) RETURNING id", storage.SearchKey("Sade"), true).Scan(&artist); err != nil {
t.Fatal(err)
}
if r := do(t, h, "POST", fmt.Sprintf("/api/v1/artists/%d/lidarr", artist), admin, nil); r.Code != http.StatusConflict {
t.Fatalf("send: %d %v", r.Code, r.Body)
}
if r := do(t, h, "GET", "/api/v1/lidarr/requests", admin, nil); r.Body["total"] != 0.0 {
t.Errorf("list = %v, want nothing: Lidarr was not asked", r.Body)
}
}