Add alternative names and cover art for soundtracks
CI / docker (push) Failing after 22s
CI / integration (push) Successful in 26s
CI / test (push) Successful in 26s
CI / publish (push) Skipped

Alternative names (#32):
- PUT /api/v1/soundtracks/{uuid}/alternative-names replaces a soundtrack's
  alternative names (trimmed, deduplicated, without the soundtrack's own name).
- alternative_names is in the soundtrack and statistics responses.
- /find matches them too and shows which name matched.

Covers (#12), stored in COVERS_PATH and off when it is not set:
- GET, PUT (upload) and DELETE /api/v1/soundtracks/{uuid}/cover, and
  PUT .../cover/source to pick a SteamGridDB game or AniList anime by ID.
  Uploaded and picked covers are never replaced automatically.
- With STEAMGRIDDB_API_KEY, a background job searches SteamGridDB, then
  AniList, by name, alternative names and the name without bracketed parts,
  at startup, after a sync and after names change. Search results are ranked
  by matching words, so "Civilization IV" gets "Sid Meier's Civilization IV".
- cover_modified (Unix seconds) is in the soundtrack and statistics responses,
  so clients can cache covers.

The new columns are added to migration 000006, which is not released yet.

Closes #12, closes #32

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
SansanandClaude Opus 5.5 committed 2026-10-13 21:57:18 +02:00
1 parent f79f51ea4c
commit bb8de5548d
39 files changed
+2418 -99

No files matched your search

+3 -1
View File
@@ -146,8 +146,10 @@ func apiError(err error) error {
switch {
case errors.Is(err, backend.ErrQueueEmpty), errors.Is(err, backend.ErrNoSongs), errors.Is(err, backend.ErrNotFound):
return huma.Error404NotFound(err.Error())
case errors.Is(err, backend.ErrInvalidName):
case errors.Is(err, backend.ErrInvalidName), errors.Is(err, backend.ErrInvalidImage):
return huma.Error400BadRequest(err.Error())
case errors.Is(err, backend.ErrCoversDisabled):
return huma.Error503ServiceUnavailable(err.Error())
case errors.Is(err, backend.ErrUpstream):
return huma.Error502BadGateway(err.Error())
default:
+114
View File
@@ -0,0 +1,114 @@
package server
import (
"context"
"net/http"
"music-server/internal/backend"
"github.com/danielgtaylor/huma/v2"
"github.com/google/uuid"
)
type coverUploadInput struct {
UUID string `path:"uuid" format:"uuid" doc:"UUID of the soundtrack"`
RawBody []byte `contentType:"image/*" doc:"The image: JPEG, PNG or WebP, at most 10 MB"`
}
// CoverSource is the body of PUT /soundtracks/{uuid}/cover/source.
type CoverSource struct {
Source string `json:"source" enum:"steamgriddb,anilist" doc:"Where the cover comes from"`
ID string `json:"id" minLength:"1" maxLength:"50" doc:"The game's ID on SteamGridDB, or the anime's ID on AniList"`
}
type coverSourceInput struct {
UUID string `path:"uuid" format:"uuid" doc:"UUID of the soundtrack"`
Body CoverSource
}
func (s *Server) registerCovers(a huma.API) {
op := func(id, method, path, summary, description string, errs ...int) huma.Operation {
return huma.Operation{
OperationID: id,
Method: method,
Path: path,
Summary: summary,
Description: description,
Tags: []string{"covers"},
Errors: errs,
}
}
// covers returns the cover service, or ErrCoversDisabled when COVERS_PATH is not set.
covers := func() (*backend.CoverService, error) {
if s.covers == nil {
return nil, apiError(backend.ErrCoversDisabled)
}
return s.covers, nil
}
get := op("get-soundtrack-cover", http.MethodGet, "/soundtracks/{uuid}/cover", "Soundtrack cover",
"Returns the soundtrack's cover image. cover_modified in the soundtrack responses tells when it last changed.",
http.StatusNotFound)
get.Responses = fileResponses("The cover image", "image/jpeg", "image/png", "image/webp")
register(s, a, route{op: get},
func(ctx context.Context, in *uuidInput) (*huma.StreamResponse, error) {
if s.covers == nil {
return nil, huma.Error404NotFound("Not Found")
}
path, err := s.covers.Path(ctx, in.id())
if err != nil {
return nil, apiError(err)
}
return streamFile(path, "", false)
})
upload := op("upload-soundtrack-cover", http.MethodPut, "/soundtracks/{uuid}/cover", "Upload a cover",
"Stores the image as the soundtrack's cover. The automatic search never replaces it; delete it to go back to automatic.",
http.StatusBadRequest, http.StatusNotFound, http.StatusServiceUnavailable)
upload.MaxBodyBytes = backend.MaxCoverBytes
upload.DefaultStatus = http.StatusNoContent
register(s, a, route{op: upload},
func(ctx context.Context, in *coverUploadInput) (*struct{}, error) {
c, err := covers()
if err != nil {
return nil, err
}
if err := c.Upload(ctx, uuid.MustParse(in.UUID), in.RawBody); err != nil {
return nil, apiError(err)
}
return nil, nil
})
source := op("set-soundtrack-cover-source", http.MethodPut, "/soundtracks/{uuid}/cover/source", "Pick a cover",
"Downloads the cover of the given SteamGridDB game or AniList anime and stores it as the soundtrack's cover. "+
"The automatic search never replaces it. SteamGridDB needs STEAMGRIDDB_API_KEY on the server.",
http.StatusBadRequest, http.StatusNotFound, http.StatusBadGateway, http.StatusServiceUnavailable)
source.DefaultStatus = http.StatusNoContent
register(s, a, route{op: source},
func(ctx context.Context, in *coverSourceInput) (*struct{}, error) {
c, err := covers()
if err != nil {
return nil, err
}
if err := c.FromSource(ctx, uuid.MustParse(in.UUID), in.Body.Source, in.Body.ID); err != nil {
return nil, apiError(err)
}
return nil, nil
})
remove := op("delete-soundtrack-cover", http.MethodDelete, "/soundtracks/{uuid}/cover", "Remove the cover",
"Deletes the soundtrack's cover, including one set by hand, so the automatic search looks for a new one.",
http.StatusNotFound, http.StatusServiceUnavailable)
remove.DefaultStatus = http.StatusNoContent
register(s, a, route{op: remove},
func(ctx context.Context, in *uuidInput) (*struct{}, error) {
c, err := covers()
if err != nil {
return nil, err
}
if err := c.Remove(ctx, in.id()); err != nil {
return nil, apiError(err)
}
return nil, nil
})
}
+143
View File
@@ -0,0 +1,143 @@
package server
import (
"bytes"
"encoding/json"
"image"
"image/png"
"io"
"net/http"
"net/http/httptest"
"path/filepath"
"testing"
"music-server/internal/backend"
"music-server/internal/config"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func pngImage(t *testing.T) []byte {
t.Helper()
var buf bytes.Buffer
require.NoError(t, png.Encode(&buf, image.NewRGBA(image.Rect(0, 0, 2, 3))))
return buf.Bytes()
}
// newFakeAniList answers AniList lookups by ID: ID 42 has a cover, others do not.
func newFakeAniList(t *testing.T) string {
img := pngImage(t)
var server *httptest.Server
server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
_, _ = w.Write(img)
return
}
var req struct {
Variables struct {
ID int `json:"id"`
} `json:"variables"`
}
_ = json.NewDecoder(r.Body).Decode(&req)
media := any(nil)
if req.Variables.ID == 42 {
media = map[string]any{"id": 42, "coverImage": map[string]any{"extraLarge": server.URL + "/cover.png"}}
}
_ = json.NewEncoder(w).Encode(map[string]any{"data": map[string]any{"Media": media}})
}))
t.Cleanup(server.Close)
return server.URL
}
func withCovers(t *testing.T) func(*config.Config) {
aniList := newFakeAniList(t)
dir := filepath.Join(t.TempDir(), "covers")
return func(c *config.Config) {
c.CoversPath = dir
c.AniListURL = aniList
}
}
func (e *testEnv) put(path, contentType string, body []byte) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodPut, path, bytes.NewReader(body))
req.Header.Set("Content-Type", contentType)
rec := httptest.NewRecorder()
e.handler.ServeHTTP(rec, req)
return rec
}
func TestCoverUploadAndGet(t *testing.T) {
e := newTestEnv(t, withCovers(t))
song := e.addSong("Game A", "Song", "x")
path := "/api/v1/soundtracks/" + song.SoundtrackUuid.String() + "/cover"
assert.Equal(t, http.StatusNotFound, e.do(http.MethodGet, path).Code, "no cover yet")
img := pngImage(t)
rec := e.put(path, "image/png", img)
require.Equal(t, http.StatusNoContent, rec.Code, rec.Body.String())
rec = e.do(http.MethodGet, path)
assert.Equal(t, http.StatusOK, rec.Code)
assert.Equal(t, "image/png", rec.Header().Get("Content-Type"))
assert.Equal(t, img, rec.Body.Bytes())
assert.NotEmpty(t, rec.Header().Get("Last-Modified"))
var soundtrack backend.Soundtrack
require.NoError(t, json.Unmarshal(e.do(http.MethodGet, "/api/v1/soundtracks/"+song.SoundtrackUuid.String()).Body.Bytes(), &soundtrack))
assert.NotNil(t, soundtrack.CoverModified)
assert.Equal(t, http.StatusBadRequest, e.put(path, "image/png", []byte("not an image")).Code)
big := append(pngImage(t), make([]byte, backend.MaxCoverBytes)...)
assert.Equal(t, http.StatusRequestEntityTooLarge, e.put(path, "image/png", big).Code)
assert.Equal(t, http.StatusNotFound,
e.put("/api/v1/soundtracks/00000000-0000-0000-0000-000000000000/cover", "image/png", img).Code)
}
func TestCoverPickFromSource(t *testing.T) {
e := newTestEnv(t, withCovers(t))
song := e.addSong("Game A", "Song", "x")
path := "/api/v1/soundtracks/" + song.SoundtrackUuid.String() + "/cover"
rec := e.doBody(http.MethodPut, path+"/source", `{"source":"anilist","id":"42"}`)
require.Equal(t, http.StatusNoContent, rec.Code, rec.Body.String())
assert.Equal(t, http.StatusOK, e.do(http.MethodGet, path).Code)
assert.Equal(t, http.StatusNotFound, e.doBody(http.MethodPut, path+"/source", `{"source":"anilist","id":"7"}`).Code)
assert.Equal(t, http.StatusBadRequest, e.doBody(http.MethodPut, path+"/source", `{"source":"steamgriddb","id":"7"}`).Code,
"SteamGridDB needs an API key")
assert.Equal(t, http.StatusUnprocessableEntity, e.doBody(http.MethodPut, path+"/source", `{"source":"igdb","id":"7"}`).Code)
}
func TestCoverDelete(t *testing.T) {
e := newTestEnv(t, withCovers(t))
song := e.addSong("Game A", "Song", "x")
path := "/api/v1/soundtracks/" + song.SoundtrackUuid.String() + "/cover"
require.Equal(t, http.StatusNoContent, e.put(path, "image/png", pngImage(t)).Code)
assert.Equal(t, http.StatusNoContent, e.do(http.MethodDelete, path).Code)
assert.Equal(t, http.StatusNotFound, e.do(http.MethodGet, path).Code)
}
func TestCoversDisabled(t *testing.T) {
e := newTestEnv(t)
song := e.addSong("Game A", "Song", "x")
path := "/api/v1/soundtracks/" + song.SoundtrackUuid.String() + "/cover"
assert.Equal(t, http.StatusNotFound, e.do(http.MethodGet, path).Code)
assert.Equal(t, http.StatusServiceUnavailable, e.put(path, "image/png", pngImage(t)).Code)
assert.Equal(t, http.StatusServiceUnavailable, e.do(http.MethodDelete, path).Code)
rec := e.doBody(http.MethodPut, path+"/source", `{"source":"anilist","id":"42"}`)
assert.Equal(t, http.StatusServiceUnavailable, rec.Code)
body, _ := io.ReadAll(rec.Body)
assert.Contains(t, string(body), "not enabled")
}
func TestCoverWritesRequireToken(t *testing.T) {
e := newTestEnv(t, withAuth("secret"), withCovers(t))
song := e.addSong("Game A", "Song", "x")
path := "/api/v1/soundtracks/" + song.SoundtrackUuid.String() + "/cover"
assert.Equal(t, http.StatusUnauthorized, e.put(path, "image/png", pngImage(t)).Code)
assert.Equal(t, http.StatusUnauthorized, e.do(http.MethodDelete, path).Code)
assert.Equal(t, http.StatusUnauthorized, e.do(http.MethodGet, path).Code)
}
+7
View File
@@ -334,6 +334,8 @@ func (s statsStore) GetAllSoundtracksWithSongs(context.Context) ([]repository.Ge
return []repository.GetAllSoundtracksWithSongsRow{{
SoundtrackUuid: statsSoundtrackUUID,
SoundtrackName: "Game A",
AlternativeNames: []string{"GA"},
CoverModified: pgtype.Timestamptz{Time: time.Unix(1730000000, 0), Valid: true},
SoundtrackPlayed: 4,
Songs: []byte(`[{"song_uuid":"` + statsSongUUID.String() + `","song_name":"Song","times_played":3}]`),
}, {
@@ -375,6 +377,11 @@ func TestStatisticsEndpoints(t *testing.T) {
assert.Equal(t, int32(4), soundtracks[0].SoundtrackPlayed)
assert.Equal(t, "Song", soundtracks[0].Songs[0].SongName)
assert.Empty(t, soundtracks[1].Songs, "no songs is an empty list")
assert.Equal(t, []string{"GA"}, soundtracks[0].AlternativeNames)
require.NotNil(t, soundtracks[0].CoverModified)
assert.Equal(t, int64(1730000000), *soundtracks[0].CoverModified)
assert.Equal(t, []string{}, soundtracks[1].AlternativeNames, "no names is an empty list")
assert.Nil(t, soundtracks[1].CoverModified)
var summary backend.StatisticsSummary
require.NoError(t, json.Unmarshal(e.do(http.MethodGet, "/api/v1/statistics/summary").Body.Bytes(), &summary))
+36
View File
@@ -2,6 +2,7 @@ package server
import (
"context"
"fmt"
"net/http"
"music-server/internal/backend"
@@ -19,6 +20,20 @@ func (in *uuidInput) id() uuid.UUID {
return uuid.MustParse(in.UUID)
}
// AlternativeNames is the body of PUT /soundtracks/{uuid}/alternative-names.
type AlternativeNames struct {
Names []string `json:"names" maxItems:"50" doc:"The new list of alternative names. Replaces the old list; send [] to remove them all."`
}
type alternativeNamesInput struct {
UUID string `path:"uuid" format:"uuid" doc:"UUID of the soundtrack"`
Body AlternativeNames
}
func (in *alternativeNamesInput) id() uuid.UUID {
return uuid.MustParse(in.UUID)
}
func (s *Server) registerLibrary(a huma.API) {
l := s.library
op := func(id, path, summary, description string, errs ...int) huma.Operation {
@@ -49,6 +64,27 @@ func (s *Server) registerLibrary(a huma.API) {
return ok(l.Song(ctx, in.id()))
})
names := op("set-alternative-names", "/soundtracks/{uuid}/alternative-names", "Set alternative names",
"Replaces the soundtrack's alternative names, which search and the cover search also use. "+
"Names are trimmed, and empty names, duplicates and the soundtrack's own name (ignoring case) are dropped.",
http.StatusNotFound)
names.Method = http.MethodPut
register(s, a, route{op: names},
func(ctx context.Context, in *alternativeNamesInput) (*jsonBody[backend.Soundtrack], error) {
for _, name := range in.Body.Names {
if len(name) > backend.MaxNameLength {
return nil, huma.Error422UnprocessableEntity(
fmt.Sprintf("names can be at most %d bytes long", backend.MaxNameLength))
}
}
soundtrack, err := l.SetAlternativeNames(ctx, in.id(), in.Body.Names)
if err != nil {
return nil, apiError(err)
}
s.soundtracksChanged(ctx)
return ok(soundtrack, nil)
})
file := op("get-song-file", "/songs/{uuid}/file", "Stream song",
"Returns the audio file of a song.", http.StatusNotFound)
file.Responses = fileResponses("The song (MP3)", audioMPEG)
+46
View File
@@ -3,6 +3,8 @@ package server
import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"music-server/internal/backend"
@@ -84,3 +86,47 @@ func TestQueueResponsesIncludeUUIDs(t *testing.T) {
require.Len(t, list, 1)
assert.Equal(t, song.Uuid.String(), list[0]["SongUuid"])
}
func TestSetAlternativeNames(t *testing.T) {
e := newTestEnv(t)
song := e.addSong("Final Fantasy VII", "Prelude", "x")
path := "/api/v1/soundtracks/" + song.SoundtrackUuid.String() + "/alternative-names"
rec := e.doBody(http.MethodPut, path, `{"names":[" FF7 ","ff7","Final Fantasy VII"]}`)
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
var soundtrack backend.Soundtrack
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &soundtrack))
assert.Equal(t, []string{"FF7"}, soundtrack.AlternativeNames)
rec = e.do(http.MethodGet, "/api/v1/soundtracks/"+song.SoundtrackUuid.String())
assert.Contains(t, rec.Body.String(), `"alternative_names":["FF7"]`)
// The search page finds it by the new name right away.
req := httptest.NewRequest(http.MethodPost, "/find", strings.NewReader("search_term=ff7"))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rec = httptest.NewRecorder()
e.handler.ServeHTTP(rec, req)
assert.Contains(t, rec.Body.String(), "Final Fantasy VII")
assert.Contains(t, rec.Body.String(), "Also known as FF7")
}
func TestSetAlternativeNamesValidation(t *testing.T) {
e := newTestEnv(t)
song := e.addSong("Game A", "Song", "x")
path := "/api/v1/soundtracks/" + song.SoundtrackUuid.String() + "/alternative-names"
long := strings.Repeat("a", backend.MaxNameLength+1)
assert.Equal(t, http.StatusUnprocessableEntity, e.doBody(http.MethodPut, path, `{"names":["`+long+`"]}`).Code)
many := `{"names":["` + strings.Repeat(`x","`, 50) + `x"]}`
assert.Equal(t, http.StatusUnprocessableEntity, e.doBody(http.MethodPut, path, many).Code, "at most 50 names")
assert.Equal(t, http.StatusUnprocessableEntity, e.doBody(http.MethodPut, path, `{}`).Code, "names is required")
assert.Equal(t, http.StatusUnprocessableEntity,
e.doBody(http.MethodPut, "/api/v1/soundtracks/not-a-uuid/alternative-names", `{"names":[]}`).Code)
}
func TestSetAlternativeNamesRequiresToken(t *testing.T) {
e := newTestEnv(t, withAuth("secret"))
song := e.addSong("Game A", "Song", "x")
rec := e.doBody(http.MethodPut, "/api/v1/soundtracks/"+song.SoundtrackUuid.String()+"/alternative-names", `{"names":["A"]}`)
assert.Equal(t, http.StatusUnauthorized, rec.Code)
}
+20 -1
View File
@@ -74,6 +74,7 @@ func TestOpenAPIDocumentsTheV1API(t *testing.T) {
}
slices.Sort(operations)
assert.Equal(t, []string{
"DELETE /api/v1/soundtracks/{uuid}/cover",
"DELETE /api/v1/token",
"GET /api/v1/character",
"GET /api/v1/character/details",
@@ -102,6 +103,7 @@ func TestOpenAPIDocumentsTheV1API(t *testing.T) {
"GET /api/v1/songs/{uuid}/file",
"GET /api/v1/soundtracks",
"GET /api/v1/soundtracks/{uuid}",
"GET /api/v1/soundtracks/{uuid}/cover",
"GET /api/v1/statistics/songs/least-played",
"GET /api/v1/statistics/songs/most-played",
"GET /api/v1/statistics/soundtracks",
@@ -119,6 +121,9 @@ func TestOpenAPIDocumentsTheV1API(t *testing.T) {
"POST /api/v1/token",
"POST /api/v1/token/cleanup",
"PUT /api/v1/music/played",
"PUT /api/v1/soundtracks/{uuid}/alternative-names",
"PUT /api/v1/soundtracks/{uuid}/cover",
"PUT /api/v1/soundtracks/{uuid}/cover/source",
}, operations, "/api/v1/sync/reset is hidden and legacy routes are not documented")
assert.Equal(t, "http", spec.Components.SecuritySchemes[bearerAuthName].Value.Type)
@@ -169,7 +174,7 @@ func (v *specValidator) check(method, path, body string, wantStatus int, headers
func TestResponsesMatchOpenAPI(t *testing.T) {
gitea := newGitea(t, http.StatusOK)
e := newTestEnv(t, func(c *config.Config) { c.ReleasesURL = gitea })
e := newTestEnv(t, func(c *config.Config) { c.ReleasesURL = gitea }, withCovers(t))
v := newSpecValidator(t, e)
song := e.addSong("Game A", "Song", "0123456789")
songURL := "/api/v1/songs/" + song.Uuid.String()
@@ -202,6 +207,20 @@ func TestResponsesMatchOpenAPI(t *testing.T) {
// Library.
v.check(http.MethodGet, "/api/v1/soundtracks", "", http.StatusOK)
v.check(http.MethodGet, "/api/v1/soundtracks/"+song.SoundtrackUuid.String(), "", http.StatusOK)
v.check(http.MethodPut, "/api/v1/soundtracks/"+song.SoundtrackUuid.String()+"/alternative-names",
`{"names":["Game Alpha"]}`, http.StatusOK)
v.check(http.MethodPut, "/api/v1/soundtracks/00000000-0000-0000-0000-000000000000/alternative-names",
`{"names":[]}`, http.StatusNotFound)
// Covers.
coverURL := "/api/v1/soundtracks/" + song.SoundtrackUuid.String() + "/cover"
v.check(http.MethodGet, coverURL, "", http.StatusNotFound)
v.check(http.MethodPut, coverURL, string(pngImage(t)), http.StatusNoContent, "Content-Type", "image/png")
v.check(http.MethodPut, coverURL, "plain text", http.StatusBadRequest, "Content-Type", "image/png")
v.check(http.MethodGet, coverURL, "", http.StatusOK)
v.check(http.MethodPut, coverURL+"/source", `{"source":"anilist","id":"42"}`, http.StatusNoContent)
v.check(http.MethodPut, coverURL+"/source", `{"source":"anilist","id":"7"}`, http.StatusNotFound)
v.check(http.MethodDelete, coverURL, "", http.StatusNoContent)
v.check(http.MethodGet, "/api/v1/soundtracks/00000000-0000-0000-0000-000000000000", "", http.StatusNotFound)
v.check(http.MethodGet, songURL, "", http.StatusOK)
v.check(http.MethodGet, songURL+"/file", "", http.StatusOK)
+1
View File
@@ -63,6 +63,7 @@ func (s *Server) routes() (*echo.Echo, huma.API) {
s.registerSync(a)
s.registerMusic(a)
s.registerLibrary(a)
s.registerCovers(a)
s.registerStatistics(a)
// Older links to the spec and docs.
+54 -1
View File
@@ -35,6 +35,11 @@ type Server struct {
releases *backend.ReleaseService
stats *backend.StatisticsService
search *backend.SearchCache
// covers is nil when COVERS_PATH is not set.
covers *backend.CoverService
// stopCovers ends the background cover search; coversDone is closed when it has ended.
stopCovers context.CancelFunc
coversDone chan struct{}
httpServer *http.Server
// metrics serves /metrics on its own port; nil when metrics are off.
metrics *metrics.Server
@@ -57,9 +62,19 @@ func New(cfg config.Config, q repository.Querier, database Database) (*Server, e
releases: backend.NewReleaseService(cfg.ReleasesURL),
stats: backend.NewStatisticsService(q),
}
s.search = backend.NewSearchCache(s.music.SoundtrackNames)
s.search = backend.NewSearchCache(s.music.SearchSoundtracks)
s.sync = backend.NewSyncService(q, cfg.MusicPath, s.afterSync)
if cfg.CoversPath != "" {
s.covers, err = backend.NewCoverService(q, cfg.CoversPath, backend.CoverOptions{
SteamGridDBKey: cfg.SteamGridDBAPIKey,
SteamGridDBURL: cfg.SteamGridDBURL,
AniListURL: cfg.AniListURL,
})
if err != nil {
return nil, fmt.Errorf("covers path: %w", err)
}
}
if cfg.MetricsPort > 0 {
s.metrics = metrics.NewServer(cfg.MetricsPort)
}
@@ -73,6 +88,36 @@ func New(cfg config.Config, q repository.Querier, database Database) (*Server, e
return s, nil
}
// startCoverSearch runs the background cover search until Shutdown. It does nothing when
// covers are off or there is no SteamGridDB API key.
func (s *Server) startCoverSearch() {
if s.covers == nil || !s.covers.SearchesAutomatically() {
logging.GetLogger().Info("Automatic cover search is off",
zap.Bool("covers_path_set", s.covers != nil))
return
}
ctx, cancel := context.WithCancel(context.Background())
s.stopCovers, s.coversDone = cancel, make(chan struct{})
go func() {
defer close(s.coversDone)
s.covers.Run(ctx)
}()
}
// soundtracksChanged reloads the cached soundtrack data after soundtracks were edited, and
// lets the cover search try the new names.
func (s *Server) soundtracksChanged(ctx context.Context) {
if err := s.music.ReloadSoundtracks(ctx); err != nil {
logging.GetLogger().Error("Failed to reload soundtracks", zap.Error(err))
}
if err := s.search.Reload(ctx); err != nil {
logging.GetLogger().Error("Failed to reload search cache", zap.Error(err))
}
if s.covers != nil {
s.covers.Trigger()
}
}
// afterSync refreshes cached data once a sync has finished.
func (s *Server) afterSync(ctx context.Context) {
if err := s.music.EndAllQueues(ctx); err != nil {
@@ -84,6 +129,9 @@ func (s *Server) afterSync(ctx context.Context) {
if err := s.search.Reload(ctx); err != nil {
logging.GetLogger().Error("Failed to reload search cache after sync", zap.Error(err))
}
if s.covers != nil {
s.covers.Trigger()
}
}
// NewServerInstance loads the configuration, connects to and migrates the database and creates the Server.
@@ -133,6 +181,7 @@ func (s *Server) ListenAndServe() error {
logging.GetLogger().Error("Failed to start the metrics server", zap.Error(err))
}
}
s.startCoverSearch()
logging.GetLogger().Info("Server starting", zap.String("address", s.httpServer.Addr))
if err := s.httpServer.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
return err
@@ -146,6 +195,10 @@ func (s *Server) Shutdown(ctx context.Context) error {
if s.metrics != nil {
err = errors.Join(err, s.metrics.Shutdown(ctx))
}
if s.stopCovers != nil {
s.stopCovers()
<-s.coversDone
}
s.sync.Wait()
s.characters.Close()
s.db.Close()