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}) }