feat(subsonic): add support for lyrics (#519)

* Add songLyrics extension since the getLyricsBySongId method is implemented

* Add support for lyrics

* Add check for getLyrics function

* fix typo

* chore: fix tests

* fix(lyrics): if lrc is formatted with empty spaces remove them

* fix(lint): use NewError correctly

bump ts
This commit is contained in:
./daniele
2025-08-26 11:09:00 +01:00
committed by sentriz
parent 5916a7fe7b
commit db97bc753e
11 changed files with 183 additions and 2 deletions

No files matched your search

+1
View File
@@ -235,6 +235,7 @@ type Track struct {
TagTrackNumber int `sql:"default: null"`
TagDiscNumber int `sql:"default: null"`
TagBrainzID string `sql:"default: null"`
TagLyrics string `sql:"default:null"`
ReplayGainTrackGain float32
ReplayGainTrackPeak float32
+5
View File
@@ -80,6 +80,7 @@ func (db *DB) Migrate(ctx MigrationContext) error {
construct(ctx, "202505211202", migrateTrackAddIndexOnBrainzID),
construct(ctx, "202505262025", migrateAlbumAddIndexOnBrainzID),
construct(ctx, "202507062103", migrateAlbumCompilationReleaseType),
construct(ctx, "202508261102", migrateAddLyrics),
}
return gormigrate.
@@ -861,3 +862,7 @@ func migrateAlbumCompilationReleaseType(tx *gorm.DB, _ MigrationContext) error {
Album{},
).Error
}
func migrateAddLyrics(tx *gorm.DB, _ MigrationContext) error {
return tx.AutoMigrate(Track{}).Error
}
+1
View File
@@ -9,6 +9,7 @@ require (
github.com/disintegration/imaging v1.6.2
github.com/djherbis/times v1.6.0
github.com/dustin/go-humanize v1.0.1
github.com/env25/mpdlrc v0.7.4
github.com/fatih/structs v1.1.0
github.com/fsnotify/fsnotify v1.9.0
github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510
+2
View File
@@ -27,6 +27,8 @@ github.com/djherbis/times v1.6.0 h1:w2ctJ92J8fBvWPxugmXIv7Nz7Q3iDMKNx9v5ocVH20c=
github.com/djherbis/times v1.6.0/go.mod h1:gOHeRAz2h+VJNZ5Gmc/o7iD9k4wW7NMVqieYCY99oc0=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/env25/mpdlrc v0.7.4 h1:A9If5JKVjgJldaIjJztqkXpUKXlsoRIwXqGK3qS38pY=
github.com/env25/mpdlrc v0.7.4/go.mod h1:Zyhq2WfcYeSJUCtx7mhbXwlh4Xt6mR7HDw0qQh7LvyY=
github.com/erikstmartin/go-testdb v0.0.0-20160219214506-8d10e4a1bae5 h1:Yzb9+7DPaBjB8zlTR87/ElzFsnQfuHnVUVqpZZIcV5Y=
github.com/erikstmartin/go-testdb v0.0.0-20160219214506-8d10e4a1bae5/go.mod h1:a2zkGnVExMxdzMo3M0Hi/3sEU+cWnZpSni0O6/Yb/P0=
github.com/fatih/structs v1.1.0 h1:Q7juDM0QtcnhCpeyLGQKyg4TOIghuNXrkL32pHAUMxo=
+1
View File
@@ -362,6 +362,7 @@ func (i *TagInfo) Genres() []string { return []string{i.RawGenre} }
func (i *TagInfo) TrackNumber() int { return 1 }
func (i *TagInfo) DiscNumber() int { return 1 }
func (i *TagInfo) Year() int { return 2021 }
func (i *TagInfo) Lyrics() string { return "[00:01.58] Line one\n[00:03.44] Line two\n" }
func (i *TagInfo) Compilation() bool { return false }
func (i *TagInfo) ReleaseType() string { return "album" }
+1
View File
@@ -468,6 +468,7 @@ func populateTrack(tx *db.DB, album *db.Album, track *db.Track, trags tagcommon.
track.FilenameUDec = decoded(basename)
track.Size = size
track.AlbumID = album.ID
track.TagLyrics = trags.Lyrics()
track.TagTitle = trags.Title()
track.TagTitleUDec = decoded(trags.Title())
+1
View File
@@ -127,6 +127,7 @@ func New(dbc *db.DB, scannr *scanner.Scanner, musicPaths []MusicPath, podcastsPa
c.Handle("/getSimilarSongs", chain(resp(c.ServeGetSimilarSongs)))
c.Handle("/getSimilarSongs2", chain(resp(c.ServeGetSimilarSongsTwo)))
c.Handle("/getLyrics", chain(resp(c.ServeGetLyrics)))
c.Handle("/getLyricsBySongId", chain(resp(c.ServeGetLyricsBySongID)))
// raw
c.Handle("/getCoverArt", chainRaw(respRaw(c.ServeGetCoverArt)))
+148 -2
View File
@@ -8,10 +8,12 @@ import (
"net/http"
"os"
"path/filepath"
"strings"
"sync"
"time"
"unicode"
"github.com/env25/mpdlrc/lrc"
"github.com/google/uuid"
"github.com/jinzhu/gorm"
@@ -41,6 +43,7 @@ func (c *Controller) ServeGetOpenSubsonicExtensions(_ *http.Request) *spec.Respo
sub.OpenSubsonicExtensions = &spec.OpenSubsonicExtensions{
{Name: "transcodeOffset", Versions: []int{1}},
{Name: "formPost", Versions: []int{1}},
{Name: "songLyrics", Versions: []int{1}},
}
return sub
}
@@ -482,12 +485,155 @@ func (c *Controller) ServeJukebox(r *http.Request) *spec.Response { // nolint:go
return sub
}
func (c *Controller) ServeGetLyrics(_ *http.Request) *spec.Response {
func (c *Controller) ServeGetLyrics(r *http.Request) *spec.Response {
params := r.Context().Value(CtxParams).(params.Params)
artist, _ := params.Get("artist")
title, _ := params.Get("title")
var track db.Track
err := c.dbc.
Preload("Album").
Joins("JOIN track_artists ON track_artists.track_id = tracks.id").
Joins("JOIN artists ON artists.id = track_artists.artist_id").
Where("tracks.tag_title LIKE ? AND artists.name LIKE ?", title, artist).
First(&track).
Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return spec.NewError(70, "couldn't find a track with that id")
}
if err != nil {
return spec.NewError(0, "lyrics: %v", err)
}
sub := spec.NewResponse()
sub.Lyrics = &spec.Lyrics{}
if track.TagLyrics != "" {
sub.Lyrics = &spec.Lyrics{
Value: track.TagLyrics,
Artist: track.TagTrackArtist,
Title: track.TagTitle,
}
return sub
}
_, text, err := lyricsFile(track)
if os.IsNotExist(err) {
return sub
}
if err != nil {
return spec.NewError(0, "lyricsFile: %v", err)
}
contents := strings.Join(text, "\n")
sub.Lyrics = &spec.Lyrics{
Value: contents,
Artist: track.TagTrackArtist,
Title: track.TagTitle,
}
return sub
}
func (c *Controller) ServeGetLyricsBySongID(r *http.Request) *spec.Response {
params := r.Context().Value(CtxParams).(params.Params)
id, err := params.GetID("id")
if err != nil {
return spec.NewError(10, "provide an `id` parameter")
}
var track db.Track
q := c.dbc.
Preload("Album").
Preload("Album.Artists").
Preload("Artists").
Where("id=?", id.Value).
First(&track)
if err := q.Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return spec.NewError(70, "couldn't find a track with that id")
} else {
return spec.NewError(0, "lyrics: %v", err)
}
}
sub := spec.NewResponse()
if track.TagLyrics != "" {
times, lrc, err := lrc.ParseString(track.TagLyrics)
if err != nil {
return spec.NewError(0, "lyricsFile: %v", err)
}
lines := make([]spec.Lyric, len(times))
for i, time := range times {
lines[i] = spec.Lyric{
Start: time.Milliseconds(),
Value: strings.TrimSpace(lrc[i]),
}
}
structured := spec.StructuredLyrics{
Lang: "xxx",
Synced: true,
Lines: lines,
DisplayArtist: track.TagTrackArtist,
DisplayTitle: track.TagTitle,
Offset: 0,
}
sub.LyricsList = &spec.LyricsList{
StructuredLyrics: []spec.StructuredLyrics{structured},
}
return sub
}
times, lrc, err := lyricsFile(track)
if err != nil {
if os.IsNotExist(err) {
sub.LyricsList = &spec.LyricsList{
StructuredLyrics: []spec.StructuredLyrics{},
}
return sub
}
return spec.NewError(0, "lyricsFile: %v", err)
}
lines := make([]spec.Lyric, len(times))
for i, time := range times {
lines[i] = spec.Lyric{
Start: time.Milliseconds(),
Value: strings.TrimSpace(lrc[i]),
}
}
structured := spec.StructuredLyrics{
Lang: "xxx",
Synced: true,
Lines: lines,
DisplayArtist: track.TagTrackArtist,
DisplayTitle: track.TagTitle,
Offset: 0,
}
sub.LyricsList = &spec.LyricsList{
StructuredLyrics: []spec.StructuredLyrics{structured},
}
return sub
}
func lyricsFile(file db.Track) ([]lrc.Duration, []lrc.Text, error) {
filePath := file.AbsPath()
fileDir := filepath.Dir(filePath)
fileName := strings.TrimSuffix(filepath.Base(filePath), filepath.Ext(filePath))
lrcContent, err := os.ReadFile(filepath.Join(fileDir, fileName+".lrc"))
if err != nil {
return []lrc.Duration{}, []lrc.Text{}, err
}
return lrc.Parse(lrcContent)
}
func scrobbleStatsUpdateTrack(dbc *db.DB, track *db.Track, userID int, playTime time.Time) error {
var play db.Play
if err := dbc.Where("album_id=? AND user_id=?", track.AlbumID, userID).First(&play).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
+19
View File
@@ -71,6 +71,7 @@ type Response struct {
SimilarSongsTwo *SimilarSongsTwo `xml:"similarSongs2" json:"similarSongs2,omitempty"`
InternetRadioStations *InternetRadioStations `xml:"internetRadioStations" json:"internetRadioStations,omitempty"`
Lyrics *Lyrics `xml:"lyrics" json:"lyrics,omitempty"`
LyricsList *LyricsList `xml:"lyricsList" json:"lyricsList,omitempty"`
}
func NewResponse() *Response {
@@ -475,6 +476,24 @@ type Lyrics struct {
Title string `xml:"title,attr,omitempty" json:"title,omitempty"`
}
type Lyric struct {
Start int64 `xml:"start,attr" json:"start"`
Value string `xml:",chardata" json:"value"`
}
type LyricsList struct {
StructuredLyrics []StructuredLyrics `xml:"structuredLyrics" json:"structuredLyrics"`
}
type StructuredLyrics struct {
Lang string `xml:"lang,attr" json:"lang"` // ISO 639 (or und, xxx if unknown)
Synced bool `xml:"synced,attr" json:"synced"`
Lines []Lyric `xml:"line" json:"line"`
DisplayArtist string `xml:"displayArtist,attr,omitempty" json:"displayArtist,omitempty"`
DisplayTitle string `xml:"displayTitle,attr,omitempty" json:"displayTitle,omitempty"`
Offset int `xml:"offset,attr,omitempty" json:"offset,omitempty"`
}
type OpenSubsonicExtension struct {
Name string `xml:"name,attr" json:"name"`
Versions []int `xml:"versions" json:"versions"`
+1
View File
@@ -25,6 +25,7 @@ type Info interface {
TrackNumber() int
DiscNumber() int
Year() int
Lyrics() string
Compilation() bool
ReleaseType() string
+3
View File
@@ -51,6 +51,9 @@ func (i *info) Genres() []string { return find(i.raw, "genres") }
func (i *info) TrackNumber() int { return intSep("/", first(find(i.raw, "tracknumber"))) } // eg. 5/12
func (i *info) DiscNumber() int { return intSep("/", first(find(i.raw, "discnumber"))) } // eg. 1/2
func (i *info) Year() int { return intSep("-", first(find(i.raw, "originaldate", "date", "year"))) } // eg. 2023-12-01
func (i *info) Lyrics() string {
return first(find(i.raw, "lyrics", "lyrics:description", "USLT:description", "LYRICS", "Lyrics", "©lyr"))
}
func (i *info) Compilation() bool { return bl(first(find(i.raw, "compilation"))) }
func (i *info) ReleaseType() string { return first(find(i.raw, "releasetype")) }