feat(subsonic): scan status, artist and album info, lyrics, ratings and users
release / go (push) Failing after 1m15s
release / web (push) Successful in 1m18s
release / govulncheck (push) Successful in 21s
release / integration (push) Successful in 3m57s
release / Attach APK to the Release (tag releases only) (push) Canceled after 0s
release / Build + push container image (push) Canceled after 0s
release / Verify release artifacts (tag releases only) (push) Canceled after 0s
release / android (push) Canceled after 4m33s
release / Build signed APK (push) Canceled after 4m9s
release / go (push) Failing after 1m15s
release / web (push) Successful in 1m18s
release / govulncheck (push) Successful in 21s
release / integration (push) Successful in 3m57s
release / Attach APK to the Release (tag releases only) (push) Canceled after 0s
release / Build + push container image (push) Canceled after 0s
release / Verify release artifacts (tag releases only) (push) Canceled after 0s
release / android (push) Canceled after 4m33s
release / Build signed APK (push) Canceled after 4m9s
The last Subsonic methods apps call that Minstrel didn't answer: - getScanStatus counts the songs whose files are present and says whether a scan is running; startScan, for an admin, starts the scan the web app's Rescan starts, and answers "scanning" straight away since the scan records itself a moment later. - getArtistInfo and getArtistInfo2 give the artist's MusicBrainz id and the artists in this library that sound like them, from an artist, album or song id; getAlbumInfo and getAlbumInfo2 give the album's MusicBrainz id. Minstrel fetches no biographies or outside images, so none are sent. - getLyrics (by artist and title) and getLyricsBySongId (OpenSubsonic songLyrics, now declared) read lyrics when asked: a .lrc file beside the song gives timed lyrics, otherwise the song's own lyrics tag. - setRating accepts a rating and keeps none: a like is Minstrel's only rating, and a low rating is never read as a dislike. - getUsers lists every user, for an admin only. ArtistRef no longer fixes its XML element name, so it can appear as similarArtist; every field holding it names the element. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -113,7 +113,7 @@ Every image carries a signed Android app, all with the same key, so a phone can
|
||||
**Clients and accounts**
|
||||
- A full web app, built into the server.
|
||||
- A native Android app that ships inside the server image, keeps playing what it has cached when the server is out of reach, and updates itself from your server.
|
||||
- OpenSubsonic-compatible, so Subsonic apps such as Symfonium, DSub, play:Sub and Amperfy can browse by artist, album, genre or folder, search, play, like and scrobble, carry a play queue from one device to another, see the daily mixes and your playlists, and get Minstrel's smart shuffle and radio when they ask for random songs or similar songs.
|
||||
- OpenSubsonic-compatible, so Subsonic apps such as Symfonium, DSub, play:Sub and Amperfy can browse by artist, album, genre or folder, search, play, like and scrobble, carry a play queue from one device to another, show lyrics (from a `.lrc` file beside the song, or the song's own tags), see the daily mixes and your playlists, and get Minstrel's smart shuffle and radio when they ask for random songs or similar songs.
|
||||
- Separate accounts for each person, with invites, and an inbox for what happened while you were away.
|
||||
|
||||
## Scope and responsible use
|
||||
|
||||
@@ -108,6 +108,18 @@ func (q *Queries) CountMissingTracks(ctx context.Context) (int64, error) {
|
||||
return count, err
|
||||
}
|
||||
|
||||
const countPlayableTracks = `-- name: CountPlayableTracks :one
|
||||
SELECT count(*) FROM tracks WHERE missing_since IS NULL
|
||||
`
|
||||
|
||||
// The songs whose files are present, for the Subsonic getScanStatus count.
|
||||
func (q *Queries) CountPlayableTracks(ctx context.Context) (int64, error) {
|
||||
row := q.db.QueryRow(ctx, countPlayableTracks)
|
||||
var count int64
|
||||
err := row.Scan(&count)
|
||||
return count, err
|
||||
}
|
||||
|
||||
const countSuspectSourceTracks = `-- name: CountSuspectSourceTracks :one
|
||||
SELECT COUNT(*) FROM tracks t
|
||||
WHERE t.missing_since IS NULL
|
||||
@@ -1025,6 +1037,81 @@ func (q *Queries) ListTracksByAlbum(ctx context.Context, arg ListTracksByAlbumPa
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listTracksByArtistAndTitle = `-- name: ListTracksByArtistAndTitle :many
|
||||
SELECT t.id, t.title, t.album_id, t.artist_id, t.track_number, t.disc_number, t.duration_ms, t.file_path, t.file_size, t.file_format, t.bitrate, t.mbid, t.genre, t.added_at, t.updated_at, t.tag_source, t.tag_sources_version, t.tag_read_version, t.missing_since, t.mbid_source, t.song_id, t.song_key, t.source_verdict, t.source_verdict_at, t.emptied_at, t.removed_reason, t.removed_by, t.artist_credit
|
||||
FROM tracks t
|
||||
JOIN artists ar ON ar.id = t.artist_id
|
||||
WHERE lower(t.title) = lower($1::text)
|
||||
AND ($2::text = ''
|
||||
OR lower(ar.name) = lower($2::text)
|
||||
OR lower(coalesce(t.artist_credit, '')) = lower($2::text))
|
||||
AND t.missing_since IS NULL
|
||||
ORDER BY t.id
|
||||
LIMIT 20
|
||||
`
|
||||
|
||||
type ListTracksByArtistAndTitleParams struct {
|
||||
Title string
|
||||
ArtistName string
|
||||
}
|
||||
|
||||
type ListTracksByArtistAndTitleRow struct {
|
||||
Track Track
|
||||
}
|
||||
|
||||
// Songs matching a title, and an artist when one is given, both regardless
|
||||
// of case, for the Subsonic getLyrics, which names the song rather than
|
||||
// giving an id. The artist matches the filing artist or the song's own
|
||||
// credit ("Low Tide Choir feat. Ruby Calloway").
|
||||
func (q *Queries) ListTracksByArtistAndTitle(ctx context.Context, arg ListTracksByArtistAndTitleParams) ([]ListTracksByArtistAndTitleRow, error) {
|
||||
rows, err := q.db.Query(ctx, listTracksByArtistAndTitle, arg.Title, arg.ArtistName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []ListTracksByArtistAndTitleRow
|
||||
for rows.Next() {
|
||||
var i ListTracksByArtistAndTitleRow
|
||||
if err := rows.Scan(
|
||||
&i.Track.ID,
|
||||
&i.Track.Title,
|
||||
&i.Track.AlbumID,
|
||||
&i.Track.ArtistID,
|
||||
&i.Track.TrackNumber,
|
||||
&i.Track.DiscNumber,
|
||||
&i.Track.DurationMs,
|
||||
&i.Track.FilePath,
|
||||
&i.Track.FileSize,
|
||||
&i.Track.FileFormat,
|
||||
&i.Track.Bitrate,
|
||||
&i.Track.Mbid,
|
||||
&i.Track.Genre,
|
||||
&i.Track.AddedAt,
|
||||
&i.Track.UpdatedAt,
|
||||
&i.Track.TagSource,
|
||||
&i.Track.TagSourcesVersion,
|
||||
&i.Track.TagReadVersion,
|
||||
&i.Track.MissingSince,
|
||||
&i.Track.MbidSource,
|
||||
&i.Track.SongID,
|
||||
&i.Track.SongKey,
|
||||
&i.Track.SourceVerdict,
|
||||
&i.Track.SourceVerdictAt,
|
||||
&i.Track.EmptiedAt,
|
||||
&i.Track.RemovedReason,
|
||||
&i.Track.RemovedBy,
|
||||
&i.Track.ArtistCredit,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listTracksMissingMbidWithPath = `-- name: ListTracksMissingMbidWithPath :many
|
||||
SELECT id, file_path
|
||||
FROM tracks
|
||||
|
||||
@@ -424,3 +424,23 @@ ORDER BY p.plays DESC, l.likes DESC,
|
||||
al.release_date NULLS LAST, al.sort_title, al.id,
|
||||
t.disc_number NULLS FIRST, t.track_number NULLS FIRST, t.id
|
||||
LIMIT sqlc.arg(lim);
|
||||
|
||||
-- name: ListTracksByArtistAndTitle :many
|
||||
-- Songs matching a title, and an artist when one is given, both regardless
|
||||
-- of case, for the Subsonic getLyrics, which names the song rather than
|
||||
-- giving an id. The artist matches the filing artist or the song's own
|
||||
-- credit ("Low Tide Choir feat. Ruby Calloway").
|
||||
SELECT sqlc.embed(t)
|
||||
FROM tracks t
|
||||
JOIN artists ar ON ar.id = t.artist_id
|
||||
WHERE lower(t.title) = lower(sqlc.arg(title)::text)
|
||||
AND (sqlc.arg(artist_name)::text = ''
|
||||
OR lower(ar.name) = lower(sqlc.arg(artist_name)::text)
|
||||
OR lower(coalesce(t.artist_credit, '')) = lower(sqlc.arg(artist_name)::text))
|
||||
AND t.missing_since IS NULL
|
||||
ORDER BY t.id
|
||||
LIMIT 20;
|
||||
|
||||
-- name: CountPlayableTracks :one
|
||||
-- The songs whose files are present, for the Subsonic getScanStatus count.
|
||||
SELECT count(*) FROM tracks WHERE missing_since IS NULL;
|
||||
|
||||
@@ -209,7 +209,17 @@ func (s *Server) Router() http.Handler {
|
||||
LibrarySize: recommendation.NewLibrarySize(nil),
|
||||
Logger: s.Logger,
|
||||
})
|
||||
subsonic.Mount(r, s.Pool, s.Logger, s.SubsonicCfg, writer, netSettings.Hops, subsonicPicker, playlistsSvc)
|
||||
// An admin's startScan runs the scan the web app's Rescan runs.
|
||||
var subsonicScan subsonic.StartScan
|
||||
if s.LibraryScanner != nil {
|
||||
subsonicScan = func(context.Context) (bool, error) {
|
||||
// The scan outlives the request that asked for it.
|
||||
started, _, err := library.TryStartScan(context.Background(), s.Pool,
|
||||
s.LibraryScanner, s.CoverEnricher, s.Logger.With("source", "subsonic"), s.ScanCfg)
|
||||
return started, err
|
||||
}
|
||||
}
|
||||
subsonic.Mount(r, s.Pool, s.Logger, s.SubsonicCfg, writer, netSettings.Hops, subsonicPicker, playlistsSvc, subsonicScan)
|
||||
}
|
||||
|
||||
spa := web.Handler(s.BrandingCfg)
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
package subsonic
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
||||
)
|
||||
|
||||
// Artist and album info is what Minstrel knows beyond the tags: the
|
||||
// MusicBrainz id, and for an artist the artists in this library that sound
|
||||
// like them. Minstrel fetches no biographies, album notes or outside images,
|
||||
// so those are left out rather than sent empty.
|
||||
|
||||
// ArtistInfo is the body of getArtistInfo and getArtistInfo2.
|
||||
type ArtistInfo struct {
|
||||
MusicBrainzID string `json:"musicBrainzId,omitempty" xml:"musicBrainzId,omitempty"`
|
||||
SimilarArtists []ArtistRef `json:"similarArtist" xml:"similarArtist"`
|
||||
}
|
||||
|
||||
type ArtistInfoResponse struct {
|
||||
Envelope
|
||||
ArtistInfo ArtistInfo `json:"artistInfo" xml:"artistInfo"`
|
||||
}
|
||||
|
||||
type ArtistInfo2Response struct {
|
||||
Envelope
|
||||
ArtistInfo2 ArtistInfo `json:"artistInfo2" xml:"artistInfo2"`
|
||||
}
|
||||
|
||||
// AlbumInfo is the body of getAlbumInfo and getAlbumInfo2.
|
||||
type AlbumInfo struct {
|
||||
MusicBrainzID string `json:"musicBrainzId,omitempty" xml:"musicBrainzId,omitempty"`
|
||||
}
|
||||
|
||||
type AlbumInfoResponse struct {
|
||||
Envelope
|
||||
AlbumInfo AlbumInfo `json:"albumInfo" xml:"albumInfo"`
|
||||
}
|
||||
|
||||
func (b *browseHandlers) getArtistInfo(w http.ResponseWriter, r *http.Request) {
|
||||
if info, ok := b.artistInfo(w, r); ok {
|
||||
Write(w, r, ArtistInfoResponse{Envelope: NewEnvelope("ok"), ArtistInfo: info})
|
||||
}
|
||||
}
|
||||
|
||||
func (b *browseHandlers) getArtistInfo2(w http.ResponseWriter, r *http.Request) {
|
||||
if info, ok := b.artistInfo(w, r); ok {
|
||||
Write(w, r, ArtistInfo2Response{Envelope: NewEnvelope("ok"), ArtistInfo2: info})
|
||||
}
|
||||
}
|
||||
|
||||
// artistInfo reads the artist named by id (an artist, or an album or song of
|
||||
// theirs, as the spec allows) and up to count similar artists in this
|
||||
// library, most similar first; count defaults to 20. It returns false once
|
||||
// it has written the failure.
|
||||
func (b *browseHandlers) artistInfo(w http.ResponseWriter, r *http.Request) (ArtistInfo, bool) {
|
||||
params := r.URL.Query()
|
||||
idStr := params.Get("id")
|
||||
if idStr == "" {
|
||||
WriteFail(w, r, ErrMissingParameter, "Missing required parameter: id")
|
||||
return ArtistInfo{}, false
|
||||
}
|
||||
id, ok := parseUUID(idStr)
|
||||
if !ok {
|
||||
WriteFail(w, r, ErrDataNotFound, "Artist not found")
|
||||
return ArtistInfo{}, false
|
||||
}
|
||||
count := clampInt(atoiDefault(params.Get("count"), 20), 0, 100)
|
||||
q := dbq.New(b.pool)
|
||||
artist, err := artistOf(r.Context(), q, id)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
WriteFail(w, r, ErrDataNotFound, "Artist not found")
|
||||
return ArtistInfo{}, false
|
||||
}
|
||||
if err != nil {
|
||||
WriteFail(w, r, ErrGeneric, "Failed to load artist")
|
||||
return ArtistInfo{}, false
|
||||
}
|
||||
info := ArtistInfo{SimilarArtists: []ArtistRef{}}
|
||||
if artist.Mbid != nil {
|
||||
info.MusicBrainzID = *artist.Mbid
|
||||
}
|
||||
if count > 0 {
|
||||
rows, err := q.ListSimilarArtistsForArtist(r.Context(), dbq.ListSimilarArtistsForArtistParams{
|
||||
SeedArtistID: artist.ID, ResultLimit: int32(count),
|
||||
})
|
||||
if err != nil {
|
||||
WriteFail(w, r, ErrGeneric, "Failed to load similar artists")
|
||||
return ArtistInfo{}, false
|
||||
}
|
||||
for _, row := range rows {
|
||||
info.SimilarArtists = append(info.SimilarArtists, artistRef(row.Artist, int(row.AlbumCount)))
|
||||
}
|
||||
}
|
||||
return info, true
|
||||
}
|
||||
|
||||
// artistOf is the artist an id names: the artist itself, or the artist of an
|
||||
// album or a song. pgx.ErrNoRows when it names none of them.
|
||||
func artistOf(ctx context.Context, q *dbq.Queries, id pgtype.UUID) (dbq.Artist, error) {
|
||||
artist, err := q.GetArtistByID(ctx, id)
|
||||
if !errors.Is(err, pgx.ErrNoRows) {
|
||||
return artist, err
|
||||
}
|
||||
artistID := pgtype.UUID{}
|
||||
if album, err := q.GetAlbumByID(ctx, id); err == nil {
|
||||
artistID = album.ArtistID
|
||||
} else if !errors.Is(err, pgx.ErrNoRows) {
|
||||
return dbq.Artist{}, err
|
||||
} else if track, err := q.GetTrackByID(ctx, id); err == nil {
|
||||
artistID = track.ArtistID
|
||||
} else {
|
||||
return dbq.Artist{}, err
|
||||
}
|
||||
return q.GetArtistByID(ctx, artistID)
|
||||
}
|
||||
|
||||
// getAlbumInfo serves both getAlbumInfo and getAlbumInfo2: the two take an
|
||||
// album id and answer the same albumInfo element.
|
||||
func (b *browseHandlers) getAlbumInfo(w http.ResponseWriter, r *http.Request) {
|
||||
idStr := r.URL.Query().Get("id")
|
||||
if idStr == "" {
|
||||
WriteFail(w, r, ErrMissingParameter, "Missing required parameter: id")
|
||||
return
|
||||
}
|
||||
id, ok := parseUUID(idStr)
|
||||
if !ok {
|
||||
WriteFail(w, r, ErrDataNotFound, "Album not found")
|
||||
return
|
||||
}
|
||||
album, err := dbq.New(b.pool).GetAlbumByID(r.Context(), id)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
WriteFail(w, r, ErrDataNotFound, "Album not found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
WriteFail(w, r, ErrGeneric, "Failed to load album")
|
||||
return
|
||||
}
|
||||
info := AlbumInfo{}
|
||||
if album.Mbid != nil {
|
||||
info.MusicBrainzID = *album.Mbid
|
||||
}
|
||||
Write(w, r, AlbumInfoResponse{Envelope: NewEnvelope("ok"), AlbumInfo: info})
|
||||
}
|
||||
@@ -0,0 +1,297 @@
|
||||
package subsonic
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/xml"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
||||
)
|
||||
|
||||
func starts(l songLyrics) []int64 {
|
||||
out := make([]int64, len(l.lines))
|
||||
for i, line := range l.lines {
|
||||
if line.Start == nil {
|
||||
out[i] = -1
|
||||
continue
|
||||
}
|
||||
out[i] = *line.Start
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func values(l songLyrics) []string {
|
||||
out := make([]string, len(l.lines))
|
||||
for i, line := range l.lines {
|
||||
out[i] = line.Value
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// LRC text is timed, in time order, a line sung twice once per time; its
|
||||
// header tags are dropped and its offset kept. Anything else is a line per
|
||||
// line, without the blank lines around it.
|
||||
func TestParseLyrics_TimedFromLRCAndPlainOtherwise(t *testing.T) {
|
||||
lrc := "\ufeff[ar:Tin Orchard]\r\n[ti:Dusk]\r\n[offset:+250]\r\n" +
|
||||
"[00:12.50]First light\r\n[00:20.00][01:05.25]Over the hill\r\n[00:30.1]Down\r\n[1:02:5]Late\r\n"
|
||||
l, ok := parseLyrics(lrc)
|
||||
if !ok || !l.synced {
|
||||
t.Fatalf("LRC: ok=%v synced=%v, want timed lyrics", ok, l.synced)
|
||||
}
|
||||
if got, want := starts(l), []int64{12500, 20000, 30100, 62500, 65250}; !slices.Equal(got, want) {
|
||||
t.Errorf("starts = %v, want %v", got, want)
|
||||
}
|
||||
if got, want := values(l), []string{"First light", "Over the hill", "Down", "Late", "Over the hill"}; !slices.Equal(got, want) {
|
||||
t.Errorf("lines = %q, want %q", got, want)
|
||||
}
|
||||
if l.offset != 250 {
|
||||
t.Errorf("offset = %d, want 250", l.offset)
|
||||
}
|
||||
|
||||
l, ok = parseLyrics("\n\nFirst light\n\n[Chorus]\nOver the hill\n\n")
|
||||
if !ok || l.synced {
|
||||
t.Fatalf("plain: ok=%v synced=%v, want untimed lyrics", ok, l.synced)
|
||||
}
|
||||
if got, want := values(l), []string{"First light", "", "[Chorus]", "Over the hill"}; !slices.Equal(got, want) {
|
||||
t.Errorf("plain lines = %q, want %q", got, want)
|
||||
}
|
||||
if got := starts(l); !slices.Equal(got, []int64{-1, -1, -1, -1}) {
|
||||
t.Errorf("plain starts = %v, want none", got)
|
||||
}
|
||||
|
||||
if _, ok := parseLyrics(" \n\t\n"); ok {
|
||||
t.Error("blank text: found lyrics, want none")
|
||||
}
|
||||
}
|
||||
|
||||
// The .lrc file beside a song is its lyrics; a song with neither that nor a
|
||||
// readable lyrics tag has none.
|
||||
func TestReadLyrics_FromTheLrcBesideTheSong(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
song := filepath.Join(dir, "Dusk.flac")
|
||||
if err := os.WriteFile(song, []byte("not really audio"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, ok := readLyrics(song); ok {
|
||||
t.Error("no .lrc and no readable tags: found lyrics, want none")
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, "Dusk.lrc"), []byte("[00:01.00]First light\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
l, ok := readLyrics(song)
|
||||
if !ok || !l.synced || !slices.Equal(values(l), []string{"First light"}) {
|
||||
t.Errorf("with Dusk.lrc: %+v ok=%v, want its one timed line", l, ok)
|
||||
}
|
||||
if _, ok := readLyrics(filepath.Join(dir, "Missing.flac")); ok {
|
||||
t.Error("a file that is not there: found lyrics, want none")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetLyrics_ReadsTheSongsLrcByIdOrByName(t *testing.T) {
|
||||
f := seedPicks(t)
|
||||
dir := t.TempDir()
|
||||
dusk := filepath.Join(dir, "Dusk.flac")
|
||||
f.exec(t, `UPDATE tracks SET file_path = $2 WHERE id = $1`, f.tracks["Dusk"].ID, dusk)
|
||||
if err := os.WriteFile(filepath.Join(dir, "Dusk.lrc"), []byte("[00:01.00]First light\n[00:04.00]Gone by noon\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
var byID struct {
|
||||
LyricsList LyricsList `json:"lyricsList"`
|
||||
}
|
||||
if code := call(t, f.browse().getLyricsBySongId, f.user, "id="+uuidToID(f.tracks["Dusk"].ID), &byID); code != 0 {
|
||||
t.Fatalf("getLyricsBySongId: error %d", code)
|
||||
}
|
||||
if n := len(byID.LyricsList.StructuredLyrics); n != 1 {
|
||||
t.Fatalf("Dusk has %d sets of lyrics, want 1", n)
|
||||
}
|
||||
got := byID.LyricsList.StructuredLyrics[0]
|
||||
if !got.Synced || got.DisplayTitle != "Dusk" || got.DisplayArtist != "Tin Orchard" || got.Lang != "und" || len(got.Lines) != 2 ||
|
||||
got.Lines[1].Value != "Gone by noon" || got.Lines[1].Start == nil || *got.Lines[1].Start != 4000 {
|
||||
t.Errorf("Dusk's lyrics = %+v, want its two timed lines", got)
|
||||
}
|
||||
|
||||
if code := call(t, f.browse().getLyricsBySongId, f.user, "id="+uuidToID(f.tracks["Harbour"].ID), &byID); code != 0 {
|
||||
t.Fatalf("getLyricsBySongId: error %d", code)
|
||||
}
|
||||
if byID.LyricsList.StructuredLyrics == nil || len(byID.LyricsList.StructuredLyrics) != 0 {
|
||||
t.Errorf("Harbour's lyrics = %+v, want an empty list", byID.LyricsList.StructuredLyrics)
|
||||
}
|
||||
|
||||
var byName struct {
|
||||
Lyrics Lyrics `json:"lyrics"`
|
||||
}
|
||||
if code := call(t, f.browse().getLyrics, f.user, "artist=tin+orchard&title=DUSK", &byName); code != 0 {
|
||||
t.Fatalf("getLyrics: error %d", code)
|
||||
}
|
||||
if byName.Lyrics != (Lyrics{Artist: "Tin Orchard", Title: "Dusk", Value: "First light\nGone by noon"}) {
|
||||
t.Errorf("getLyrics = %+v, want Dusk's text", byName.Lyrics)
|
||||
}
|
||||
byName.Lyrics = Lyrics{}
|
||||
if code := call(t, f.browse().getLyrics, f.user, "artist=Someone+Else&title=Dusk", &byName); code != 0 {
|
||||
t.Fatalf("getLyrics: error %d", code)
|
||||
}
|
||||
if byName.Lyrics != (Lyrics{}) {
|
||||
t.Errorf("another artist's Dusk = %+v, want no lyrics", byName.Lyrics)
|
||||
}
|
||||
}
|
||||
|
||||
// Artist info is the MusicBrainz id and the similar artists in the library,
|
||||
// reached from the artist or from one of their albums or songs.
|
||||
func TestGetArtistInfo_IsTheMBIDAndSimilarArtistsInTheLibrary(t *testing.T) {
|
||||
f := seedPicks(t)
|
||||
ctx := context.Background()
|
||||
q := dbq.New(f.pool)
|
||||
other, err := q.UpsertArtist(ctx, dbq.UpsertArtistParams{Name: "Quiet Harbour", SortName: "Quiet Harbour"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := q.UpsertAlbum(ctx, dbq.UpsertAlbumParams{Title: "Low Water", SortTitle: "Low Water", ArtistID: other.ID}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
const mbid = "0f3e6c2a-1b4d-4e8f-9a7c-5d2b8e1f4a6c"
|
||||
f.exec(t, `UPDATE artists SET mbid = $2 WHERE id = $1`, f.artist.ID, mbid)
|
||||
f.exec(t, `INSERT INTO artist_similarity (artist_a_id, artist_b_id, score, source) VALUES ($1, $2, 0.8, 'listenbrainz')`,
|
||||
f.artist.ID, other.ID)
|
||||
|
||||
for _, id := range []string{uuidToID(f.artist.ID), uuidToID(f.albums["Paper Boats"].ID), uuidToID(f.tracks["Gale"].ID)} {
|
||||
var got struct {
|
||||
ArtistInfo2 ArtistInfo `json:"artistInfo2"`
|
||||
}
|
||||
if code := call(t, f.browse().getArtistInfo2, f.user, "id="+id, &got); code != 0 {
|
||||
t.Fatalf("getArtistInfo2 %s: error %d", id, code)
|
||||
}
|
||||
want := ArtistInfo{MusicBrainzID: mbid, SimilarArtists: []ArtistRef{{ID: uuidToID(other.ID), Name: "Quiet Harbour", AlbumCount: 1}}}
|
||||
if got.ArtistInfo2.MusicBrainzID != want.MusicBrainzID || !slices.Equal(got.ArtistInfo2.SimilarArtists, want.SimilarArtists) {
|
||||
t.Errorf("getArtistInfo2 %s = %+v, want %+v", id, got.ArtistInfo2, want)
|
||||
}
|
||||
}
|
||||
|
||||
var folder struct {
|
||||
ArtistInfo ArtistInfo `json:"artistInfo"`
|
||||
}
|
||||
if code := call(t, f.browse().getArtistInfo, f.user, "id="+uuidToID(f.artist.ID)+"&count=0", &folder); code != 0 {
|
||||
t.Fatalf("getArtistInfo: error %d", code)
|
||||
}
|
||||
if folder.ArtistInfo.SimilarArtists == nil || len(folder.ArtistInfo.SimilarArtists) != 0 {
|
||||
t.Errorf("count=0: similar artists %v, want an empty list", folder.ArtistInfo.SimilarArtists)
|
||||
}
|
||||
if code := call(t, f.browse().getArtistInfo2, f.user, "id=00000000-0000-4000-8000-000000000001", nil); code != ErrDataNotFound {
|
||||
t.Errorf("an unknown id: code %d, want %d", code, ErrDataNotFound)
|
||||
}
|
||||
|
||||
const albumMBID = "7a1c3e5b-2d4f-4a6b-8c9d-0e1f2a3b4c5d"
|
||||
f.exec(t, `UPDATE albums SET mbid = $2 WHERE id = $1`, f.albums["Paper Boats"].ID, albumMBID)
|
||||
var album struct {
|
||||
AlbumInfo AlbumInfo `json:"albumInfo"`
|
||||
}
|
||||
if code := call(t, f.browse().getAlbumInfo, f.user, "id="+uuidToID(f.albums["Paper Boats"].ID), &album); code != 0 {
|
||||
t.Fatalf("getAlbumInfo: error %d", code)
|
||||
}
|
||||
if album.AlbumInfo.MusicBrainzID != albumMBID {
|
||||
t.Errorf("album info = %+v, want MusicBrainz id %s", album.AlbumInfo, albumMBID)
|
||||
}
|
||||
}
|
||||
|
||||
// In XML the similar artists are similarArtist elements and the id is an
|
||||
// element of its own.
|
||||
func TestArtistInfoXML(t *testing.T) {
|
||||
out, err := xml.Marshal(ArtistInfo2Response{
|
||||
Envelope: NewEnvelope("ok"),
|
||||
ArtistInfo2: ArtistInfo{MusicBrainzID: "m", SimilarArtists: []ArtistRef{{ID: "a", Name: "Quiet Harbour"}}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("marshal: %v", err)
|
||||
}
|
||||
if want := `<artistInfo2><musicBrainzId>m</musicBrainzId><similarArtist id="a" name="Quiet Harbour"></similarArtist></artistInfo2>`; !strings.Contains(string(out), want) {
|
||||
t.Errorf("XML = %s, want it to hold %s", out, want)
|
||||
}
|
||||
}
|
||||
|
||||
// The scan status counts the songs whose files are present and says whether
|
||||
// the latest scan is still running; only an admin starts one, and the answer
|
||||
// says scanning at once.
|
||||
func TestScanStatus_AndOnlyAnAdminStartsAScan(t *testing.T) {
|
||||
f := seedPicks(t)
|
||||
// Scan runs are not cleared between tests.
|
||||
f.exec(t, `DELETE FROM scan_runs`)
|
||||
started := 0
|
||||
sc := &scanHandlers{pool: f.pool, start: func(context.Context) (bool, error) { started++; return true, nil }}
|
||||
|
||||
var got struct {
|
||||
ScanStatus ScanStatus `json:"scanStatus"`
|
||||
}
|
||||
if code := call(t, sc.getScanStatus, f.user, "", &got); code != 0 {
|
||||
t.Fatalf("getScanStatus: error %d", code)
|
||||
}
|
||||
// Seven songs, one of them missing.
|
||||
if got.ScanStatus != (ScanStatus{Count: 6}) {
|
||||
t.Errorf("before any scan: %+v, want 6 songs and not scanning", got.ScanStatus)
|
||||
}
|
||||
f.exec(t, `INSERT INTO scan_runs (started_at, finished_at) VALUES (now() - interval '1 hour', now() - interval '50 minutes')`)
|
||||
f.exec(t, `INSERT INTO scan_runs DEFAULT VALUES`)
|
||||
if code := call(t, sc.getScanStatus, f.user, "", &got); code != 0 {
|
||||
t.Fatalf("getScanStatus: error %d", code)
|
||||
}
|
||||
if !got.ScanStatus.Scanning {
|
||||
t.Errorf("with a scan running: %+v, want scanning", got.ScanStatus)
|
||||
}
|
||||
|
||||
if code := call(t, sc.startScan, f.user, "", nil); code != ErrNotAuthorized || started != 0 {
|
||||
t.Errorf("a listener's startScan: code %d, %d scans started; want %d and none", code, started, ErrNotAuthorized)
|
||||
}
|
||||
f.exec(t, `DELETE FROM scan_runs`)
|
||||
admin := f.user
|
||||
admin.IsAdmin = true
|
||||
got.ScanStatus = ScanStatus{}
|
||||
if code := call(t, sc.startScan, admin, "", &got); code != 0 {
|
||||
t.Fatalf("an admin's startScan: error %d", code)
|
||||
}
|
||||
if started != 1 || !got.ScanStatus.Scanning || got.ScanStatus.Count != 6 {
|
||||
t.Errorf("an admin's startScan: %d started, status %+v; want one, scanning, 6 songs", started, got.ScanStatus)
|
||||
}
|
||||
sc.start = func(context.Context) (bool, error) { return false, errors.New("scanner down") }
|
||||
if code := call(t, sc.startScan, admin, "", nil); code != ErrGeneric {
|
||||
t.Errorf("a scan that fails to start: code %d, want %d", code, ErrGeneric)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetUsers_ListsEveryoneForAnAdminOnly(t *testing.T) {
|
||||
h := &userHandlers{list: func(context.Context) ([]dbq.ListUsersRow, error) {
|
||||
return []dbq.ListUsersRow{{Username: "ada", IsAdmin: true}, {Username: "ben"}}, nil
|
||||
}}
|
||||
var got struct {
|
||||
Users UsersContainer `json:"users"`
|
||||
}
|
||||
if code := call(t, h.getUsers, dbq.User{Username: "ada", IsAdmin: true}, "", &got); code != 0 {
|
||||
t.Fatalf("getUsers: error %d", code)
|
||||
}
|
||||
if len(got.Users.Users) != 2 || got.Users.Users[0].Username != "ada" || !got.Users.Users[0].AdminRole ||
|
||||
got.Users.Users[1].Username != "ben" || got.Users.Users[1].AdminRole || !got.Users.Users[1].StreamRole {
|
||||
t.Errorf("users = %+v, want ada (admin) and ben (listener)", got.Users.Users)
|
||||
}
|
||||
if code := call(t, h.getUsers, dbq.User{Username: "ben"}, "", nil); code != ErrNotAuthorized {
|
||||
t.Errorf("a listener's getUsers: code %d, want %d", code, ErrNotAuthorized)
|
||||
}
|
||||
}
|
||||
|
||||
// A rating is accepted and not kept: Minstrel's only rating is a like.
|
||||
func TestSetRating_AcceptsAValidRating(t *testing.T) {
|
||||
m := &mediaHandlers{}
|
||||
user := dbq.User{Username: "ada"}
|
||||
for query, want := range map[string]int{
|
||||
"id=x&rating=5": 0,
|
||||
"id=x&rating=0": 0,
|
||||
"id=x&rating=6": ErrGeneric,
|
||||
"id=x": ErrMissingParameter,
|
||||
} {
|
||||
if code := call(t, m.handleSetRating, user, query, nil); code != want {
|
||||
t.Errorf("setRating %s: code %d, want %d", query, code, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
package subsonic
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"errors"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/dhowden/tag"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/db"
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
||||
)
|
||||
|
||||
// Lyrics are read from the music files when an app asks, not stored: a .lrc
|
||||
// file beside the song ("Dusk.flac" and "Dusk.lrc") gives timed lyrics, and
|
||||
// failing that the lyrics in the song's own tags. Adding or editing a .lrc
|
||||
// file takes effect on the next request, with no rescan.
|
||||
|
||||
// Lyrics is the body of getLyrics: the whole text, with the song it is for.
|
||||
// An empty element means no lyrics were found.
|
||||
type Lyrics struct {
|
||||
Artist string `json:"artist,omitempty" xml:"artist,attr,omitempty"`
|
||||
Title string `json:"title,omitempty" xml:"title,attr,omitempty"`
|
||||
Value string `json:"value,omitempty" xml:",chardata"`
|
||||
}
|
||||
|
||||
type LyricsResponse struct {
|
||||
Envelope
|
||||
Lyrics Lyrics `json:"lyrics" xml:"lyrics"`
|
||||
}
|
||||
|
||||
// LyricLine is one line of OpenSubsonic structured lyrics. Start is
|
||||
// milliseconds into the song, and only timed lyrics have it.
|
||||
type LyricLine struct {
|
||||
Start *int64 `json:"start,omitempty" xml:"start,attr,omitempty"`
|
||||
Value string `json:"value" xml:",chardata"`
|
||||
}
|
||||
|
||||
// StructuredLyrics is one set of lyrics for a song. Lang is "und" because
|
||||
// neither a .lrc file nor a lyrics tag says reliably what language it is in.
|
||||
// Offset, from a .lrc file's [offset:] tag, is milliseconds to show every
|
||||
// line sooner (or later, when negative).
|
||||
type StructuredLyrics struct {
|
||||
DisplayArtist string `json:"displayArtist,omitempty" xml:"displayArtist,attr,omitempty"`
|
||||
DisplayTitle string `json:"displayTitle,omitempty" xml:"displayTitle,attr,omitempty"`
|
||||
Lang string `json:"lang" xml:"lang,attr"`
|
||||
Offset int64 `json:"offset,omitempty" xml:"offset,attr,omitempty"`
|
||||
Synced bool `json:"synced" xml:"synced,attr"`
|
||||
Lines []LyricLine `json:"line" xml:"line"`
|
||||
}
|
||||
|
||||
type LyricsList struct {
|
||||
StructuredLyrics []StructuredLyrics `json:"structuredLyrics" xml:"structuredLyrics"`
|
||||
}
|
||||
|
||||
type LyricsListResponse struct {
|
||||
Envelope
|
||||
LyricsList LyricsList `json:"lyricsList" xml:"lyricsList"`
|
||||
}
|
||||
|
||||
// songLyrics is what a song's files hold.
|
||||
type songLyrics struct {
|
||||
synced bool
|
||||
offset int64
|
||||
lines []LyricLine
|
||||
}
|
||||
|
||||
// text is the lyrics as plain text, one line per line, without timings.
|
||||
func (l songLyrics) text() string {
|
||||
out := make([]string, len(l.lines))
|
||||
for i, line := range l.lines {
|
||||
out[i] = line.Value
|
||||
}
|
||||
return strings.Join(out, "\n")
|
||||
}
|
||||
|
||||
// readLyrics returns the lyrics for the music file at path, or false when it
|
||||
// has none: the .lrc file beside it if there is one, else its lyrics tag.
|
||||
// An unreadable file has no lyrics; it is not an error, since lyrics are
|
||||
// extra and the song still plays.
|
||||
func readLyrics(path string) (songLyrics, bool) {
|
||||
sidecar := strings.TrimSuffix(path, filepath.Ext(path)) + ".lrc"
|
||||
if raw, err := os.ReadFile(sidecar); err == nil {
|
||||
if l, ok := parseLyrics(string(raw)); ok {
|
||||
return l, true
|
||||
}
|
||||
}
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return songLyrics{}, false
|
||||
}
|
||||
defer func() { _ = f.Close() }()
|
||||
meta, err := tag.ReadFrom(f)
|
||||
if err != nil {
|
||||
return songLyrics{}, false
|
||||
}
|
||||
return parseLyrics(meta.Lyrics())
|
||||
}
|
||||
|
||||
var (
|
||||
// lrcTime is one [mm:ss], [mm:ss.xx] or [mm:ss.xxx] timestamp; some
|
||||
// taggers write the fraction after a colon.
|
||||
lrcTime = regexp.MustCompile(`^\[(\d+):(\d{1,2})(?:[.:](\d{1,3}))?\]`)
|
||||
// lrcOffset is the [offset:+250] tag.
|
||||
lrcOffset = regexp.MustCompile(`^\[offset:\s*([+-]?\d+)\s*\]$`)
|
||||
// lrcTag is any other [key:value] header line: [ar:], [ti:], [by:].
|
||||
lrcTag = regexp.MustCompile(`^\[[a-zA-Z]+:.*\]$`)
|
||||
)
|
||||
|
||||
// parseLyrics reads lyrics text. Text in LRC form (lines starting with a
|
||||
// [mm:ss.xx] timestamp, a line sung more than once carrying one timestamp per
|
||||
// time) is timed, in time order; anything else is untimed, a line per line.
|
||||
// Blank text is no lyrics.
|
||||
func parseLyrics(text string) (songLyrics, bool) {
|
||||
text = strings.TrimPrefix(strings.ReplaceAll(text, "\r\n", "\n"), "\ufeff")
|
||||
if strings.TrimSpace(text) == "" {
|
||||
return songLyrics{}, false
|
||||
}
|
||||
var timed songLyrics
|
||||
var plain []LyricLine
|
||||
for _, raw := range strings.Split(text, "\n") {
|
||||
line := strings.TrimSpace(raw)
|
||||
if m := lrcOffset.FindStringSubmatch(line); m != nil {
|
||||
timed.offset, _ = strconv.ParseInt(m[1], 10, 64)
|
||||
continue
|
||||
}
|
||||
var starts []int64
|
||||
for {
|
||||
m := lrcTime.FindStringSubmatch(line)
|
||||
if m == nil {
|
||||
break
|
||||
}
|
||||
starts = append(starts, lrcMillis(m[1], m[2], m[3]))
|
||||
line = line[len(m[0]):]
|
||||
}
|
||||
if len(starts) > 0 {
|
||||
value := strings.TrimSpace(line)
|
||||
for _, start := range starts {
|
||||
timed.lines = append(timed.lines, LyricLine{Start: &start, Value: value})
|
||||
}
|
||||
continue
|
||||
}
|
||||
if lrcTag.MatchString(line) {
|
||||
continue
|
||||
}
|
||||
plain = append(plain, LyricLine{Value: strings.TrimRight(raw, " \t")})
|
||||
}
|
||||
if len(timed.lines) > 0 {
|
||||
slices.SortStableFunc(timed.lines, func(a, b LyricLine) int { return cmp.Compare(*a.Start, *b.Start) })
|
||||
timed.synced = true
|
||||
return timed, true
|
||||
}
|
||||
// Leading and trailing blank lines are formatting, not lyrics.
|
||||
for len(plain) > 0 && strings.TrimSpace(plain[0].Value) == "" {
|
||||
plain = plain[1:]
|
||||
}
|
||||
for len(plain) > 0 && strings.TrimSpace(plain[len(plain)-1].Value) == "" {
|
||||
plain = plain[:len(plain)-1]
|
||||
}
|
||||
return songLyrics{lines: plain}, len(plain) > 0
|
||||
}
|
||||
|
||||
// lrcMillis converts an LRC timestamp's parts to milliseconds. The fraction
|
||||
// is hundredths with two digits and thousandths with three.
|
||||
func lrcMillis(min, sec, frac string) int64 {
|
||||
m, _ := strconv.ParseInt(min, 10, 64)
|
||||
s, _ := strconv.ParseInt(sec, 10, 64)
|
||||
ms := (m*60 + s) * 1000
|
||||
switch len(frac) {
|
||||
case 1:
|
||||
f, _ := strconv.ParseInt(frac, 10, 64)
|
||||
ms += f * 100
|
||||
case 2:
|
||||
f, _ := strconv.ParseInt(frac, 10, 64)
|
||||
ms += f * 10
|
||||
case 3:
|
||||
f, _ := strconv.ParseInt(frac, 10, 64)
|
||||
ms += f
|
||||
}
|
||||
return ms
|
||||
}
|
||||
|
||||
// getLyrics finds a song by artist and title, regardless of case, and
|
||||
// returns its lyrics as text. A song not found, or found without lyrics, is
|
||||
// an empty lyrics element, as the spec has it.
|
||||
func (b *browseHandlers) getLyrics(w http.ResponseWriter, r *http.Request) {
|
||||
params := r.URL.Query()
|
||||
title := strings.TrimSpace(params.Get("title"))
|
||||
empty := LyricsResponse{Envelope: NewEnvelope("ok")}
|
||||
if title == "" {
|
||||
Write(w, r, empty)
|
||||
return
|
||||
}
|
||||
q := dbq.New(b.pool)
|
||||
rows, err := q.ListTracksByArtistAndTitle(r.Context(), dbq.ListTracksByArtistAndTitleParams{
|
||||
Title: title, ArtistName: strings.TrimSpace(params.Get("artist")),
|
||||
})
|
||||
if err != nil {
|
||||
WriteFail(w, r, ErrGeneric, "Failed to look up the song")
|
||||
return
|
||||
}
|
||||
for _, row := range rows {
|
||||
l, ok := readLyrics(row.Track.FilePath)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
artist, err := q.GetArtistByID(r.Context(), row.Track.ArtistID)
|
||||
if err != nil {
|
||||
WriteFail(w, r, ErrGeneric, "Failed to look up the song")
|
||||
return
|
||||
}
|
||||
Write(w, r, LyricsResponse{Envelope: NewEnvelope("ok"), Lyrics: Lyrics{
|
||||
Artist: db.TrackCredit(row.Track, artist.Name), Title: row.Track.Title, Value: l.text(),
|
||||
}})
|
||||
return
|
||||
}
|
||||
Write(w, r, empty)
|
||||
}
|
||||
|
||||
// getLyricsBySongId is OpenSubsonic's songLyrics extension: a song's lyrics
|
||||
// by id, timed when its .lrc file or tag is timed. A song without lyrics
|
||||
// has an empty list.
|
||||
func (b *browseHandlers) getLyricsBySongId(w http.ResponseWriter, r *http.Request) {
|
||||
idStr := r.URL.Query().Get("id")
|
||||
if idStr == "" {
|
||||
WriteFail(w, r, ErrMissingParameter, "Missing required parameter: id")
|
||||
return
|
||||
}
|
||||
id, ok := parseUUID(idStr)
|
||||
if !ok {
|
||||
WriteFail(w, r, ErrDataNotFound, "Song not found")
|
||||
return
|
||||
}
|
||||
q := dbq.New(b.pool)
|
||||
track, err := q.GetTrackByID(r.Context(), id)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
WriteFail(w, r, ErrDataNotFound, "Song not found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
WriteFail(w, r, ErrGeneric, "Failed to load song")
|
||||
return
|
||||
}
|
||||
list := LyricsList{StructuredLyrics: []StructuredLyrics{}}
|
||||
if l, ok := readLyrics(track.FilePath); ok {
|
||||
artist, err := q.GetArtistByID(r.Context(), track.ArtistID)
|
||||
if err != nil {
|
||||
WriteFail(w, r, ErrGeneric, "Failed to load song")
|
||||
return
|
||||
}
|
||||
list.StructuredLyrics = append(list.StructuredLyrics, StructuredLyrics{
|
||||
DisplayArtist: db.TrackCredit(track, artist.Name),
|
||||
DisplayTitle: track.Title,
|
||||
Lang: "und",
|
||||
Offset: l.offset,
|
||||
Synced: l.synced,
|
||||
Lines: l.lines,
|
||||
})
|
||||
}
|
||||
Write(w, r, LyricsListResponse{Envelope: NewEnvelope("ok"), LyricsList: list})
|
||||
}
|
||||
@@ -21,10 +21,12 @@ type OpenSubsonicExtensionsResponse struct {
|
||||
|
||||
// openSubsonicExtensions lists what Minstrel implements beyond Subsonic
|
||||
// 1.16.1. apiKeyAuthentication is the apiKey parameter the auth middleware
|
||||
// accepts. Add an entry only for an extension the server fully serves:
|
||||
// accepts; songLyrics is getLyricsBySongId. Add an entry only for an extension the server fully serves:
|
||||
// apps switch behaviour on this list.
|
||||
var openSubsonicExtensions = []OpenSubsonicExtension{
|
||||
{Name: "apiKeyAuthentication", Versions: []int{1}},
|
||||
// getLyricsBySongId.
|
||||
{Name: "songLyrics", Versions: []int{1}},
|
||||
}
|
||||
|
||||
// handleGetOpenSubsonicExtensions answers without credentials: every
|
||||
|
||||
@@ -19,7 +19,7 @@ import (
|
||||
// against it here never reach the database.
|
||||
func mountedRest() http.Handler {
|
||||
r := chi.NewRouter()
|
||||
Mount(r, nil, slog.New(slog.NewTextHandler(io.Discard, nil)), Config{}, nil, func() int { return 0 }, nil, nil)
|
||||
Mount(r, nil, slog.New(slog.NewTextHandler(io.Discard, nil)), Config{}, nil, func() int { return 0 }, nil, nil, nil)
|
||||
return r
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
package subsonic
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
||||
)
|
||||
|
||||
// StartScan starts a library scan in the background, the same scan as the
|
||||
// admin's Rescan in the web app. started is false when one is already
|
||||
// running.
|
||||
type StartScan func(ctx context.Context) (started bool, err error)
|
||||
|
||||
// ScanStatus is the body of getScanStatus and startScan. Count is the songs
|
||||
// whose files are present; LastScan, from OpenSubsonic, is when the latest
|
||||
// scan finished.
|
||||
type ScanStatus struct {
|
||||
Scanning bool `json:"scanning" xml:"scanning,attr"`
|
||||
Count int64 `json:"count" xml:"count,attr"`
|
||||
LastScan string `json:"lastScan,omitempty" xml:"lastScan,attr,omitempty"`
|
||||
}
|
||||
|
||||
type ScanStatusResponse struct {
|
||||
Envelope
|
||||
ScanStatus ScanStatus `json:"scanStatus" xml:"scanStatus"`
|
||||
}
|
||||
|
||||
type scanHandlers struct {
|
||||
pool dbq.DBTX
|
||||
start StartScan
|
||||
}
|
||||
|
||||
// status reads whether a scan is running from the latest scan run.
|
||||
func (s *scanHandlers) status(ctx context.Context) (ScanStatus, error) {
|
||||
q := dbq.New(s.pool)
|
||||
count, err := q.CountPlayableTracks(ctx)
|
||||
if err != nil {
|
||||
return ScanStatus{}, err
|
||||
}
|
||||
st := ScanStatus{Count: count}
|
||||
run, err := q.GetLatestScanRun(ctx)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return st, nil
|
||||
}
|
||||
if err != nil {
|
||||
return ScanStatus{}, err
|
||||
}
|
||||
st.Scanning = !run.FinishedAt.Valid
|
||||
st.LastScan = timestamptzToRFC3339(run.FinishedAt)
|
||||
return st, nil
|
||||
}
|
||||
|
||||
func (s *scanHandlers) getScanStatus(w http.ResponseWriter, r *http.Request) {
|
||||
st, err := s.status(r.Context())
|
||||
if err != nil {
|
||||
WriteFail(w, r, ErrGeneric, "Failed to read the scan status")
|
||||
return
|
||||
}
|
||||
Write(w, r, ScanStatusResponse{Envelope: NewEnvelope("ok"), ScanStatus: st})
|
||||
}
|
||||
|
||||
// startScan starts a library scan; only an admin may. It answers scanning
|
||||
// at once: the scan records itself a moment after it starts, so the latest
|
||||
// scan run alone would still read as finished.
|
||||
func (s *scanHandlers) startScan(w http.ResponseWriter, r *http.Request) {
|
||||
user, ok := UserFromContext(r.Context())
|
||||
if !ok {
|
||||
WriteFail(w, r, ErrNotAuthorized, "Not authenticated")
|
||||
return
|
||||
}
|
||||
if !user.IsAdmin {
|
||||
WriteFail(w, r, ErrNotAuthorized, "Only an admin can start a scan")
|
||||
return
|
||||
}
|
||||
if s.start == nil {
|
||||
WriteFail(w, r, ErrGeneric, "Scanning is not available on this server")
|
||||
return
|
||||
}
|
||||
if _, err := s.start(r.Context()); err != nil {
|
||||
WriteFail(w, r, ErrGeneric, "Failed to start a scan")
|
||||
return
|
||||
}
|
||||
st, err := s.status(r.Context())
|
||||
if err != nil {
|
||||
WriteFail(w, r, ErrGeneric, "Failed to read the scan status")
|
||||
return
|
||||
}
|
||||
st.Scanning = true
|
||||
Write(w, r, ScanStatusResponse{Envelope: NewEnvelope("ok"), ScanStatus: st})
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strconv"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
@@ -240,3 +241,23 @@ func loadStarred(ctx context.Context, q *dbq.Queries, userID pgtype.UUID) ([]Son
|
||||
|
||||
return songs, albums, artists, nil
|
||||
}
|
||||
|
||||
// handleSetRating accepts a rating and keeps none. Minstrel's only rating is
|
||||
// a like, which apps set with star. A rating is not turned into a like,
|
||||
// because a rating is not a yes or no; and a low rating is never read as a
|
||||
// dislike, because what a listener doesn't want is learned from skips. The
|
||||
// call answers ok so an app's rating control does not show an error.
|
||||
// rating must still be 0 to 5, as the spec has it.
|
||||
func (m *mediaHandlers) handleSetRating(w http.ResponseWriter, r *http.Request) {
|
||||
params := r.URL.Query()
|
||||
if params.Get("id") == "" || params.Get("rating") == "" {
|
||||
WriteFail(w, r, ErrMissingParameter, "Missing required parameter: id and rating")
|
||||
return
|
||||
}
|
||||
rating, err := strconv.Atoi(params.Get("rating"))
|
||||
if err != nil || rating < 0 || rating > 5 {
|
||||
WriteFail(w, r, ErrGeneric, "rating must be 0 to 5")
|
||||
return
|
||||
}
|
||||
Write(w, r, NewEnvelope("ok"))
|
||||
}
|
||||
|
||||
@@ -31,17 +31,21 @@ import (
|
||||
// getRandomSongs and getSimilarSongs from the picker that Minstrel's own
|
||||
// radio uses, and getPlaylists from the playlist service, daily mixes
|
||||
// included.
|
||||
func Mount(r chi.Router, pool *pgxpool.Pool, logger *slog.Logger, cfg Config, events *playevents.Writer, hops func() int, picker *recommendation.Picker, lists *playlists.Service) {
|
||||
//
|
||||
// startScan starts a library scan for an admin's startScan; nil leaves the
|
||||
// method answering that scanning is not available.
|
||||
func Mount(r chi.Router, pool *pgxpool.Pool, logger *slog.Logger, cfg Config, events *playevents.Writer, hops func() int, picker *recommendation.Picker, lists *playlists.Service, startScan StartScan) {
|
||||
b := &browseHandlers{pool: pool}
|
||||
m := newMediaHandlers(pool, events, logger)
|
||||
u := &userHandlers{lookup: dbq.New(pool).GetUserByUsername}
|
||||
u := &userHandlers{lookup: dbq.New(pool).GetUserByUsername, list: dbq.New(pool).ListUsers}
|
||||
sc := &scanHandlers{pool: pool, start: startScan}
|
||||
p := &pickHandlers{pool: pool, picker: picker, playlists: lists, logger: logger}
|
||||
r.Route("/rest", func(rest chi.Router) {
|
||||
// The one method the OpenSubsonic spec has answer without credentials.
|
||||
register(rest, "/getOpenSubsonicExtensions", handleGetOpenSubsonicExtensions)
|
||||
rest.Group(func(sub chi.Router) {
|
||||
sub.Use(Middleware(pool, cfg, auth.NewLoginGuard(), hops))
|
||||
mountAuthed(sub, b, m, u, p)
|
||||
mountAuthed(sub, b, m, u, p, sc)
|
||||
})
|
||||
// Subsonic clients expect every /rest/* miss to come back as a
|
||||
// Subsonic-shaped error envelope, not chi's plain-text 404. Without
|
||||
@@ -55,7 +59,7 @@ func Mount(r chi.Router, pool *pgxpool.Pool, logger *slog.Logger, cfg Config, ev
|
||||
}
|
||||
|
||||
// mountAuthed registers every method that needs a signed-in user.
|
||||
func mountAuthed(sub chi.Router, b *browseHandlers, m *mediaHandlers, u *userHandlers, p *pickHandlers) {
|
||||
func mountAuthed(sub chi.Router, b *browseHandlers, m *mediaHandlers, u *userHandlers, p *pickHandlers, sc *scanHandlers) {
|
||||
register(sub, "/ping", handlePing)
|
||||
register(sub, "/getLicense", handleGetLicense)
|
||||
register(sub, "/getMusicFolders", b.getMusicFolders)
|
||||
@@ -74,6 +78,16 @@ func mountAuthed(sub chi.Router, b *browseHandlers, m *mediaHandlers, u *userHan
|
||||
register(sub, "/getTopSongs", b.getTopSongs)
|
||||
register(sub, "/getPlayQueue", b.getPlayQueue)
|
||||
register(sub, "/savePlayQueue", b.savePlayQueue)
|
||||
register(sub, "/getArtistInfo", b.getArtistInfo)
|
||||
register(sub, "/getArtistInfo2", b.getArtistInfo2)
|
||||
register(sub, "/getAlbumInfo", b.getAlbumInfo)
|
||||
register(sub, "/getAlbumInfo2", b.getAlbumInfo)
|
||||
register(sub, "/getLyrics", b.getLyrics)
|
||||
register(sub, "/getLyricsBySongId", b.getLyricsBySongId)
|
||||
register(sub, "/getScanStatus", sc.getScanStatus)
|
||||
register(sub, "/startScan", sc.startScan)
|
||||
register(sub, "/setRating", m.handleSetRating)
|
||||
register(sub, "/getUsers", u.getUsers)
|
||||
register(sub, "/stream", m.handleStream)
|
||||
register(sub, "/download", m.handleDownload)
|
||||
register(sub, "/getCoverArt", m.handleGetCoverArt)
|
||||
|
||||
@@ -102,8 +102,10 @@ type IndexesResponse struct {
|
||||
|
||||
// ArtistRef is the artist projection used in listings and as an album/song
|
||||
// child reference.
|
||||
//
|
||||
// Like SongRef it carries no XMLName: the field that holds it names the
|
||||
// element, "artist" in listings and "similarArtist" in artist info.
|
||||
type ArtistRef struct {
|
||||
XMLName xml.Name `json:"-" xml:"artist"`
|
||||
ID string `json:"id" xml:"id,attr"`
|
||||
Name string `json:"name" xml:"name,attr"`
|
||||
AlbumCount int `json:"albumCount,omitempty" xml:"albumCount,attr,omitempty"`
|
||||
|
||||
@@ -42,10 +42,46 @@ type User struct {
|
||||
VideoConversionRole bool `json:"videoConversionRole" xml:"videoConversionRole,attr"`
|
||||
}
|
||||
|
||||
// userHandlers serves getUser. lookup finds a user by exact username; it is
|
||||
// a field so tests can answer without a database.
|
||||
// userHandlers serves getUser and getUsers. lookup finds a user by exact
|
||||
// username and list lists every user; they are fields so tests can answer
|
||||
// without a database.
|
||||
type userHandlers struct {
|
||||
lookup func(ctx context.Context, username string) (dbq.User, error)
|
||||
list func(ctx context.Context) ([]dbq.ListUsersRow, error)
|
||||
}
|
||||
|
||||
// UsersResponse is the body of getUsers.
|
||||
type UsersResponse struct {
|
||||
Envelope
|
||||
Users UsersContainer `json:"users" xml:"users"`
|
||||
}
|
||||
|
||||
type UsersContainer struct {
|
||||
Users []User `json:"user" xml:"user"`
|
||||
}
|
||||
|
||||
// getUsers lists every user, for an admin only; anyone else gets
|
||||
// ErrNotAuthorized, as the spec has it.
|
||||
func (h *userHandlers) getUsers(w http.ResponseWriter, r *http.Request) {
|
||||
caller, ok := UserFromContext(r.Context())
|
||||
if !ok {
|
||||
WriteFail(w, r, ErrNotAuthorized, "Not authenticated")
|
||||
return
|
||||
}
|
||||
if !caller.IsAdmin {
|
||||
WriteFail(w, r, ErrNotAuthorized, "Only an admin can list users")
|
||||
return
|
||||
}
|
||||
rows, err := h.list(r.Context())
|
||||
if err != nil {
|
||||
WriteFail(w, r, ErrGeneric, "Failed to list users")
|
||||
return
|
||||
}
|
||||
users := make([]User, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
users = append(users, rolePayload(row.Username, row.IsAdmin))
|
||||
}
|
||||
Write(w, r, UsersResponse{Envelope: NewEnvelope("ok"), Users: UsersContainer{Users: users}})
|
||||
}
|
||||
|
||||
// getUser returns the authenticated user when no username is provided or
|
||||
@@ -79,12 +115,15 @@ func (h *userHandlers) getUser(w http.ResponseWriter, r *http.Request) {
|
||||
Write(w, r, UserResponse{Envelope: NewEnvelope("ok"), User: userPayload(target)})
|
||||
}
|
||||
|
||||
func userPayload(u dbq.User) User {
|
||||
func userPayload(u dbq.User) User { return rolePayload(u.Username, u.IsAdmin) }
|
||||
|
||||
// rolePayload is the role bag for a user with this name and admin flag.
|
||||
func rolePayload(username string, admin bool) User {
|
||||
return User{
|
||||
Username: u.Username,
|
||||
Username: username,
|
||||
ScrobblingEnabled: true,
|
||||
AdminRole: u.IsAdmin,
|
||||
SettingsRole: u.IsAdmin,
|
||||
AdminRole: admin,
|
||||
SettingsRole: admin,
|
||||
DownloadRole: true,
|
||||
UploadRole: false,
|
||||
PlaylistRole: true,
|
||||
|
||||
Reference in New Issue
Block a user