Merge with upstream

Merge pull request #1 from BetaPictoris/master
This commit is contained in:
Daniel
2024-02-15 11:00:04 -08:00
committed by GitHub
47 changed files with 969 additions and 688 deletions

No files matched your search

-1
View File
@@ -32,7 +32,6 @@ linters:
- gofmt - gofmt
- goheader - goheader
- goimports - goimports
- gomoddirectives
- gomodguard - gomodguard
- goprintffuncname - goprintffuncname
- gosec - gosec
+11 -10
View File
@@ -2,6 +2,7 @@
<h4 align="center">free-software <a href="http://www.subsonic.org/">subsonic</a> server API implementation, supporting its <a href="https://github.com/sentriz/gonic?tab=readme-ov-file#features">many clients</a></h4> <h4 align="center">free-software <a href="http://www.subsonic.org/">subsonic</a> server API implementation, supporting its <a href="https://github.com/sentriz/gonic?tab=readme-ov-file#features">many clients</a></h4>
<p align="center"> <p align="center">
<a href="http://hub.docker.com/r/sentriz/gonic"><img src="https://img.shields.io/docker/pulls/sentriz/gonic.svg"></a> <a href="http://hub.docker.com/r/sentriz/gonic"><img src="https://img.shields.io/docker/pulls/sentriz/gonic.svg"></a>
<a href="https://repology.org/project/gonic/"><img src="https://repology.org/badge/tiny-repos/gonic.svg"></a>
<a href="https://github.com/sentriz/gonic/releases"><img src="https://img.shields.io/github/v/release/sentriz/gonic.svg"></a> <a href="https://github.com/sentriz/gonic/releases"><img src="https://img.shields.io/github/v/release/sentriz/gonic.svg"></a>
<a href="https://web.libera.chat/#gonic"><img src="https://img.shields.io/badge/libera.chat-%23gonic-blue.svg"></a> <a href="https://web.libera.chat/#gonic"><img src="https://img.shields.io/badge/libera.chat-%23gonic-blue.svg"></a>
</p> </p>
@@ -18,7 +19,7 @@
- [last.fm](https://www.last.fm/) scrobbling - [last.fm](https://www.last.fm/) scrobbling
- [listenbrainz](https://listenbrainz.org/) scrobbling (thank you [spezifisch](https://github.com/spezifisch), [lxea](https://github.com/lxea)) - [listenbrainz](https://listenbrainz.org/) scrobbling (thank you [spezifisch](https://github.com/spezifisch), [lxea](https://github.com/lxea))
- artist similarities and biographies from the last.fm api - artist similarities and biographies from the last.fm api
- support for multi valued tags like albumartists and genres ([see more](#multi-valued-tags)) - support for multi valued tags like albumartists and genres ([see more](#multi-valued-tags-v016))
- a web interface for configuration (set up last.fm, manage users, start scans, etc.) - a web interface for configuration (set up last.fm, manage users, start scans, etc.)
- support for the [album-artist](https://mkoby.com/2007/02/18/artist-versus-album-artist/) tag, to not clutter your artist list with compilation album appearances - support for the [album-artist](https://mkoby.com/2007/02/18/artist-versus-album-artist/) tag, to not clutter your artist list with compilation album appearances
- written in [go](https://golang.org/), so lightweight and suitable for a raspberry pi, etc. (see ARM images below) - written in [go](https://golang.org/), so lightweight and suitable for a raspberry pi, etc. (see ARM images below)
@@ -67,24 +68,24 @@ password can then be changed from the web interface
| `GONIC_JUKEBOX_MPV_EXTRA_ARGS` | `-jukebox-mpv-extra-args` | **optional** extra command line arguments to pass to the jukebox mpv daemon | | `GONIC_JUKEBOX_MPV_EXTRA_ARGS` | `-jukebox-mpv-extra-args` | **optional** extra command line arguments to pass to the jukebox mpv daemon |
| `GONIC_PODCAST_PURGE_AGE` | `-podcast-purge-age` | **optional** age (in days) to purge podcast episodes if not accessed | | `GONIC_PODCAST_PURGE_AGE` | `-podcast-purge-age` | **optional** age (in days) to purge podcast episodes if not accessed |
| `GONIC_EXCLUDE_PATTERN` | `-exclude-pattern` | **optional** files matching this regex pattern will not be imported | | `GONIC_EXCLUDE_PATTERN` | `-exclude-pattern` | **optional** files matching this regex pattern will not be imported |
| `GONIC_MULTI_VALUE_GENRE` | `-multi-value-genre` | **optional** setting for multi-valued genre tags when scanning ([see more](#multi-valued-tags)) | | `GONIC_MULTI_VALUE_GENRE` | `-multi-value-genre` | **optional** setting for multi-valued genre tags when scanning ([see more](#multi-valued-tags-v016)) |
| `GONIC_MULTI_VALUE_ARTIST` | `-multi-value-artist` | **optional** setting for multi-valued artist tags when scanning ([see more](#multi-valued-tags)) | | `GONIC_MULTI_VALUE_ARTIST` | `-multi-value-artist` | **optional** setting for multi-valued artist tags when scanning ([see more](#multi-valued-tags-v016)) |
| `GONIC_MULTI_VALUE_ALBUM_ARTIST` | `-multi-value-album-artist` | **optional** setting for multi-valued album artist tags when scanning ([see more](#multi-valued-tags)) | | `GONIC_MULTI_VALUE_ALBUM_ARTIST` | `-multi-value-album-artist` | **optional** setting for multi-valued album artist tags when scanning ([see more](#multi-valued-tags-v016)) |
| `GONIC_EXPVAR` | `-expvar` | **optional** enable the /debug/vars endpoint (exposes useful debugging attributes as well as database stats) | | `GONIC_EXPVAR` | `-expvar` | **optional** enable the /debug/vars endpoint (exposes useful debugging attributes as well as database stats) |
## multi valued tags (v0.16+) ## multi valued tags (v0.16+)
gonic can support potentially multi valued tags like `genres` and `albumartists`. in both cases gonic will individual entries in its database for each. gonic can support potentially multi valued tags like `genres`, `artists`, and `albumartists`. in both cases gonic will individual entries in its database for each.
this means being able to click find album "X" under both "techno" and "house" for example. or finding the album "My Life in the Bush of Ghosts" under either "David Byrne" or "Brian Eno". it also means not cluttering up your artists list with "A & X", "A and Y", "A ft. Z", etc. you will only have A, X, Y, and Z. this means being able to click find album "X" under both "techno" and "house" for example. or finding the album "My Life in the Bush of Ghosts" under either "David Byrne" or "Brian Eno". it also means not cluttering up your artists list with "A & X", "A and Y", "A ft. Z", etc. you will only have A, X, Y, and Z.
the available modes are: the available modes are:
| value | desc | | value | desc |
| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `multi` | gonic will explictly look for multi value fields in your audio metadata. software like musicbrainz picard or beets can set set these ([soon](https://github.com/beetbox/beets/pull/4743)) | | `multi` | gonic will explictly look for multi value fields in your audio metadata such as "genres" or "album_artists". software like [musicbrainz picard](https://picard.musicbrainz.org/), [beets](https://beets.io/) (v1.6.1+ / master), or [betanin](https://github.com/sentriz/betanin/) can set set these |
| `delim <delim>` | gonic will look at your normal audio metadata fields like "genre" or "album_artist", but split them on a delimiter. for example you could set `-multi-value-genre "delim ;"` to split the single genre field on ";" | | `delim <delim>` | gonic will look at your normal audio metadata fields like "genre" or "album_artist", but split them on a delimiter. for example you could set `-multi-value-genre "delim ;"` to split the single genre field on ";". note this mode is not recommended unless you use an uncommon delimiter such as ";" or "\|". using a delimiter like "&" will likely lead to many [false positives](https://musicbrainz.org/artist/ccd4879c-5e88-4385-b131-bf65296bf245) |
| `none` (default) | gonic will not attempt to do any multi value processing | | `none` (default) | gonic will not attempt to do any multi value processing |
## screenshots ## screenshots
+12 -1
View File
@@ -388,6 +388,17 @@ func main() {
return nil return nil
}) })
errgrp.Go(func() error {
defer logJob("podcast download")()
ctxTick(ctx, 5*time.Second, func() {
if err := podcast.DownloadTick(); err != nil {
log.Printf("failed to download podcast: %s", err)
}
})
return nil
})
errgrp.Go(func() error { errgrp.Go(func() error {
if *confPodcastPurgeAgeDays == 0 { if *confPodcastPurgeAgeDays == 0 {
return nil return nil
@@ -515,7 +526,7 @@ func (mvs multiValueSetting) String() string {
case scanner.Delim: case scanner.Delim:
return fmt.Sprintf("delim(%s)", mvs.Delim) return fmt.Sprintf("delim(%s)", mvs.Delim)
case scanner.Multi: case scanner.Multi:
return fmt.Sprint("multi", mvs.Delim) return "multi"
default: default:
return "none" return "none"
} }
+2 -1
View File
@@ -339,6 +339,7 @@ type Album struct {
AlbumStar *AlbumStar AlbumStar *AlbumStar
AlbumRating *AlbumRating AlbumRating *AlbumRating
AverageRating float64 `sql:"default: null"` AverageRating float64 `sql:"default: null"`
Play *Play
} }
func (a *Album) SID() *specid.ID { func (a *Album) SID() *specid.ID {
@@ -527,7 +528,7 @@ func (pe *PodcastEpisode) MIME() string {
} }
func (pe *PodcastEpisode) AbsPath() string { func (pe *PodcastEpisode) AbsPath() string {
if pe.Podcast == nil { if pe.Podcast == nil || pe.Podcast.RootDir == "" {
return "" return ""
} }
return filepath.Join(pe.Podcast.RootDir, pe.Filename) return filepath.Join(pe.Podcast.RootDir, pe.Filename)
+11
View File
@@ -71,6 +71,7 @@ func (db *DB) Migrate(ctx MigrationContext) error {
construct(ctx, "202311062259", migrateArtistAppearances), construct(ctx, "202311062259", migrateArtistAppearances),
construct(ctx, "202311072309", migrateAlbumInfo), construct(ctx, "202311072309", migrateAlbumInfo),
construct(ctx, "202311082304", migrateTemporaryDisplayAlbumArtist), construct(ctx, "202311082304", migrateTemporaryDisplayAlbumArtist),
construct(ctx, "202312110003", migrateAddExtraIndexes),
} }
return gormigrate. return gormigrate.
@@ -802,3 +803,13 @@ func migrateTemporaryDisplayAlbumArtist(tx *gorm.DB, _ MigrationContext) error {
WHERE tag_album_artist='' WHERE tag_album_artist=''
`).Error `).Error
} }
func migrateAddExtraIndexes(tx *gorm.DB, _ MigrationContext) error {
return tx.Exec(`
CREATE INDEX idx_track_genres_genre_id ON "track_genres" (genre_id);
CREATE INDEX idx_album_genres_genre_id ON "album_genres" (genre_id);
CREATE INDEX idx_album_artists_artist_id ON "album_artists" (artist_id);
CREATE INDEX idx_track_artists_artist_id ON "track_artists" (artist_id);
CREATE INDEX idx_artist_appearances_album_id ON "artist_appearances" (album_id);
`).Error
}
+5
View File
@@ -54,3 +54,8 @@ func First(path ...string) (string, error) {
} }
return "", err return "", err
} }
// HasPrefix checks a path has a prefix, making sure to respect path boundaries. So that /aa & /a does not match, but /a/a & /a does.
func HasPrefix(p, prefix string) bool {
return p == prefix || strings.HasPrefix(p, filepath.Clean(prefix)+string(filepath.Separator))
}
+10 -10
View File
@@ -12,24 +12,24 @@ require (
github.com/fsnotify/fsnotify v1.7.0 github.com/fsnotify/fsnotify v1.7.0
github.com/go-ldap/ldap/v3 v3.4.6 github.com/go-ldap/ldap/v3 v3.4.6
github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510
github.com/google/uuid v1.4.0 github.com/google/uuid v1.6.0
github.com/gorilla/securecookie v1.1.2 github.com/gorilla/securecookie v1.1.2
github.com/gorilla/sessions v1.2.2 github.com/gorilla/sessions v1.2.2
github.com/jinzhu/gorm v1.9.17-0.20211120011537-5c235b72a414 github.com/jinzhu/gorm v1.9.17-0.20211120011537-5c235b72a414
github.com/josephburnett/jd v1.7.1 github.com/josephburnett/jd v1.7.1
github.com/mattn/go-sqlite3 v1.14.18 github.com/mattn/go-sqlite3 v1.14.22
github.com/mitchellh/mapstructure v1.5.0 github.com/mitchellh/mapstructure v1.5.0
github.com/mmcdole/gofeed v1.2.1 github.com/mmcdole/gofeed v1.2.1
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646
github.com/peterbourgon/ff v1.7.1 github.com/peterbourgon/ff v1.7.1
github.com/philippta/go-template v0.0.0-20220911145045-4556aca435e4 github.com/philippta/go-template v0.0.0-20220911145045-4556aca435e4
github.com/rainycape/unidecode v0.0.0-20150907023854-cb7f23ec59be github.com/rainycape/unidecode v0.0.0-20150907023854-cb7f23ec59be
github.com/sentriz/audiotags v0.0.0-20230419125925-8886243b2137 github.com/sentriz/audiotags v0.0.0-20240202193907-618ae39d7743
github.com/sentriz/gormstore v0.0.0-20220105134332-64e31f7f6981 github.com/sentriz/gormstore v0.0.0-20220105134332-64e31f7f6981
github.com/stretchr/testify v1.8.4 github.com/stretchr/testify v1.8.4
golang.org/x/exp v0.0.0-20231127185646-65229373498e golang.org/x/exp v0.0.0-20240205201215-2c58cdc269a3
golang.org/x/net v0.19.0 golang.org/x/net v0.21.0
golang.org/x/sync v0.5.0 golang.org/x/sync v0.6.0
gopkg.in/gormigrate.v1 v1.6.0 gopkg.in/gormigrate.v1 v1.6.0
jaytaylor.com/html2text v0.0.0-20230321000545-74c2419ad056 jaytaylor.com/html2text v0.0.0-20230321000545-74c2419ad056
) )
@@ -60,12 +60,12 @@ require (
github.com/modern-go/reflect2 v1.0.2 // indirect github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/olekukonko/tablewriter v0.0.5 // indirect github.com/olekukonko/tablewriter v0.0.5 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/rivo/uniseg v0.4.4 // indirect github.com/rivo/uniseg v0.4.7 // indirect
github.com/rogpeppe/go-internal v1.11.0 // indirect github.com/rogpeppe/go-internal v1.11.0 // indirect
github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect
golang.org/x/crypto v0.16.0 // indirect golang.org/x/crypto v0.19.0 // indirect
golang.org/x/image v0.14.0 // indirect golang.org/x/image v0.15.0 // indirect
golang.org/x/sys v0.15.0 // indirect golang.org/x/sys v0.17.0 // indirect
golang.org/x/text v0.14.0 // indirect golang.org/x/text v0.14.0 // indirect
gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce // indirect gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect
+20 -21
View File
@@ -56,9 +56,8 @@ github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0=
github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 h1:El6M4kTTCOh6aBiKaUGG7oYTSPP8MxqL4YI3kZKwcP4= github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 h1:El6M4kTTCOh6aBiKaUGG7oYTSPP8MxqL4YI3kZKwcP4=
github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510/go.mod h1:pupxD2MaaD3pAXIBCelhxNneeOaAeabZDe5s4K6zSpQ= github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510/go.mod h1:pupxD2MaaD3pAXIBCelhxNneeOaAeabZDe5s4K6zSpQ=
github.com/google/uuid v1.3.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.4.0 h1:MtMxsa51/r9yyhkyLsVeVt0B+BGQZzpQiTQ4eHZ8bc4= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/google/uuid v1.4.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg= github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg=
github.com/gorilla/context v1.1.2 h1:WRkNAv2uoa03QNIc1A6u4O7DAGMUVoopZhkiXWA2V1o= github.com/gorilla/context v1.1.2 h1:WRkNAv2uoa03QNIc1A6u4O7DAGMUVoopZhkiXWA2V1o=
github.com/gorilla/context v1.1.2/go.mod h1:KDPwT9i/MeWHiLl90fuTgrt4/wPcv75vFAZLaOOcbxM= github.com/gorilla/context v1.1.2/go.mod h1:KDPwT9i/MeWHiLl90fuTgrt4/wPcv75vFAZLaOOcbxM=
@@ -105,8 +104,8 @@ github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZ
github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/mattn/go-sqlite3 v1.10.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= github.com/mattn/go-sqlite3 v1.10.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc=
github.com/mattn/go-sqlite3 v1.14.0/go.mod h1:JIl7NbARA7phWnGvh0LKTyg7S9BA+6gx71ShQilpsus= github.com/mattn/go-sqlite3 v1.14.0/go.mod h1:JIl7NbARA7phWnGvh0LKTyg7S9BA+6gx71ShQilpsus=
github.com/mattn/go-sqlite3 v1.14.18 h1:JL0eqdCOq6DJVNPSvArO/bIV9/P7fbGrV00LZHc+5aI= github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
github.com/mattn/go-sqlite3 v1.14.18/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg= github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw= github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=
github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s= github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=
github.com/mitchellh/go-wordwrap v1.0.0/go.mod h1:ZXFpozHsX6DPmq2I0TCekCxypsnAUbP2oI0UX1GXzOo= github.com/mitchellh/go-wordwrap v1.0.0/go.mod h1:ZXFpozHsX6DPmq2I0TCekCxypsnAUbP2oI0UX1GXzOo=
@@ -137,12 +136,12 @@ github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZN
github.com/rainycape/unidecode v0.0.0-20150907023854-cb7f23ec59be h1:ta7tUOvsPHVHGom5hKW5VXNc2xZIkfCKP8iaqOyYtUQ= github.com/rainycape/unidecode v0.0.0-20150907023854-cb7f23ec59be h1:ta7tUOvsPHVHGom5hKW5VXNc2xZIkfCKP8iaqOyYtUQ=
github.com/rainycape/unidecode v0.0.0-20150907023854-cb7f23ec59be/go.mod h1:MIDFMn7db1kT65GmV94GzpX9Qdi7N/pQlwb+AN8wh+Q= github.com/rainycape/unidecode v0.0.0-20150907023854-cb7f23ec59be/go.mod h1:MIDFMn7db1kT65GmV94GzpX9Qdi7N/pQlwb+AN8wh+Q=
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rivo/uniseg v0.4.4 h1:8TfxU8dW6PdqD27gjM8MVNuicgxIjxpm4K7x4jp8sis= github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
github.com/rivo/uniseg v0.4.4/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M= github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M=
github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA= github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA=
github.com/sentriz/audiotags v0.0.0-20230419125925-8886243b2137 h1:K0PSMi/p9ISHpfRFJB03d7VX+jjEsDARsTlAcN1zpac= github.com/sentriz/audiotags v0.0.0-20240202193907-618ae39d7743 h1:aecPwcrY8mYmZmd9XgQcG8aILRuhRxeQMSunnr6DQ3U=
github.com/sentriz/audiotags v0.0.0-20230419125925-8886243b2137/go.mod h1:nUVlCJ7n2jQoJ5rttpHozZ8pHJIhD9VehL6GP21FoDU= github.com/sentriz/audiotags v0.0.0-20240202193907-618ae39d7743/go.mod h1:Zoo4UP5t2ySbPwScJfoydAlLLBonoqntv4ovA1T91Z8=
github.com/sentriz/gormstore v0.0.0-20220105134332-64e31f7f6981 h1:sLILANWN76ja66/K4k/mBqJuCjDZaM67w+Ru6rEB0s0= github.com/sentriz/gormstore v0.0.0-20220105134332-64e31f7f6981 h1:sLILANWN76ja66/K4k/mBqJuCjDZaM67w+Ru6rEB0s0=
github.com/sentriz/gormstore v0.0.0-20220105134332-64e31f7f6981/go.mod h1:Rx8XB1ck+so+41uu9VY1gMKs1CPQ2NTq0pzf+OCCQHo= github.com/sentriz/gormstore v0.0.0-20220105134332-64e31f7f6981/go.mod h1:Rx8XB1ck+so+41uu9VY1gMKs1CPQ2NTq0pzf+OCCQHo=
github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf h1:pvbZ0lM0XWPBqUKqFU8cmavspvIl9nulOYwdy6IFRRo= github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf h1:pvbZ0lM0XWPBqUKqFU8cmavspvIl9nulOYwdy6IFRRo=
@@ -160,13 +159,13 @@ golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACk
golang.org/x/crypto v0.0.0-20190325154230-a5d413f7728c/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190325154230-a5d413f7728c/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191205180655-e7c4368fe9dd/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20191205180655-e7c4368fe9dd/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.16.0 h1:mMMrFzRSCF0GvB7Ne27XVtVAaXLrPmgPC7/v0tkwHaY= golang.org/x/crypto v0.19.0 h1:ENy+Az/9Y1vSrlrvBSyna3PITt4tiZLf7sgCjZBX7Wo=
golang.org/x/crypto v0.16.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4= golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
golang.org/x/exp v0.0.0-20231127185646-65229373498e h1:Gvh4YaCaXNs6dKTlfgismwWZKyjVZXwOPfIyUaqU3No= golang.org/x/exp v0.0.0-20240205201215-2c58cdc269a3 h1:/RIbNt/Zr7rVhIkQhooTxCxFcdWLGIKnZA4IXNFSrvo=
golang.org/x/exp v0.0.0-20231127185646-65229373498e/go.mod h1:iRJReGqOEeBhDZGkGbynYwcHlctCvnjTYIamk7uXpHI= golang.org/x/exp v0.0.0-20240205201215-2c58cdc269a3/go.mod h1:idGWGoKP1toJGkd5/ig9ZLuPcZBC3ewk7SzmH0uou08=
golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/image v0.14.0 h1:tNgSxAFe3jC4uYqvZdTr84SZoM1KfwdC9SKIFrLjFn4= golang.org/x/image v0.15.0 h1:kOELfmgrmJlw4Cdb7g/QGuB3CvDrXbqEIww/pNtNBm8=
golang.org/x/image v0.14.0/go.mod h1:HUYqC05R2ZcZ3ejNQsIHQDQiwWM4JBqmm6MKANTp4LE= golang.org/x/image v0.15.0/go.mod h1:HUYqC05R2ZcZ3ejNQsIHQDQiwWM4JBqmm6MKANTp4LE=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/net v0.0.0-20180218175443-cbe0f9307d01/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180218175443-cbe0f9307d01/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
@@ -181,13 +180,13 @@ golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns= golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns=
golang.org/x/net v0.19.0 h1:zTwKpTd2XuCqf8huc7Fo2iSy+4RHPd10s4KzeTnVr1c= golang.org/x/net v0.21.0 h1:AQyQV4dYCvJ7vGmJyKki9+PBdyvhkSd8EIx/qb0AYv4=
golang.org/x/net v0.19.0/go.mod h1:CfAk/cbD4CthTvqiEl8NpboMuiuOYsAr/7NOjZJtv1U= golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.5.0 h1:60k92dhOjHxJkrqnwsfl8KuaHbn/5dl0lUPUklKo3qE= golang.org/x/sync v0.6.0 h1:5BMeUDZ7vkXGfEr1x9B4bRcTH4lpkTkpdh0T/J+qjbQ=
golang.org/x/sync v0.5.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
@@ -198,8 +197,8 @@ golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.15.0 h1:h48lPFYpsTvQJZF4EKyI4aLHaev3CxivZmv7yZig9pc= golang.org/x/sys v0.17.0 h1:25cE3gD+tdBA7lp7QfhuV+rJiE9YXTcS3VG1SqssI/Y=
golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
+1 -1
View File
@@ -410,7 +410,7 @@ func lockr(mu *sync.RWMutex) func() {
return mu.RUnlock return mu.RUnlock
} }
var mpvVersionExpr = regexp.MustCompile(`mpv\s(\d+)\.(\d+)\.(\d+)`) var mpvVersionExpr = regexp.MustCompile(`mpv\sv?(\d+)\.(\d+)\.(\d+)`)
func parseMPVVersion(version string) (major, minor, patch int) { func parseMPVVersion(version string) (major, minor, patch int) {
m := mpvVersionExpr.FindStringSubmatch(version) m := mpvVersionExpr.FindStringSubmatch(version)
+1
View File
@@ -57,6 +57,7 @@ func (c *Client) ArtistGetInfo(artistName string) (Artist, error) {
if err != nil { if err != nil {
return Artist{}, fmt.Errorf("make request: %w", err) return Artist{}, fmt.Errorf("make request: %w", err)
} }
return resp.Artist, nil return resp.Artist, nil
} }
+6 -3
View File
@@ -10,6 +10,7 @@ import (
"net/http/httputil" "net/http/httputil"
"time" "time"
"go.senan.xyz/gonic"
"go.senan.xyz/gonic/db" "go.senan.xyz/gonic/db"
"go.senan.xyz/gonic/scrobble" "go.senan.xyz/gonic/scrobble"
) )
@@ -44,9 +45,11 @@ func (c *Client) Scrobble(user db.User, track scrobble.Track, stamp time.Time, s
payload := &Payload{ payload := &Payload{
TrackMetadata: &TrackMetadata{ TrackMetadata: &TrackMetadata{
AdditionalInfo: &AdditionalInfo{ AdditionalInfo: &AdditionalInfo{
TrackNumber: int(track.TrackNumber), TrackNumber: int(track.TrackNumber),
RecordingMBID: track.MusicBrainzID, RecordingMBID: track.MusicBrainzID,
TrackLength: int(track.Duration.Seconds()), ReleaseMBID: track.MusicBrainzReleaseID,
Duration: int(track.Duration.Seconds()),
SubmissionClient: gonic.Name,
}, },
ArtistName: track.Artist, ArtistName: track.Artist,
TrackName: track.Track, TrackName: track.Track,
+9 -1
View File
@@ -37,7 +37,15 @@ func TestScrobble(t *testing.T) {
err := client.Scrobble( err := client.Scrobble(
db.User{ListenBrainzURL: "https://listenbrainz.org", ListenBrainzToken: "token1"}, db.User{ListenBrainzURL: "https://listenbrainz.org", ListenBrainzToken: "token1"},
scrobble.Track{Track: "title", Artist: "artist", Album: "album", TrackNumber: 1}, scrobble.Track{
Track: "title",
Artist: "artist",
Album: "album",
TrackNumber: 1,
Duration: 242 * time.Second,
MusicBrainzID: "00000000-0000-0000-0000-000000000000",
MusicBrainzReleaseID: "00000000-0000-0000-0000-000000000001",
},
time.Unix(1683804525, 0), time.Unix(1683804525, 0),
true, true,
) )
+6 -4
View File
@@ -9,10 +9,12 @@ type (
} }
AdditionalInfo struct { AdditionalInfo struct {
TrackNumber int `json:"tracknumber,omitempty"` TrackNumber int `json:"tracknumber,omitempty"`
TrackMBID string `json:"track_mbid,omitempty"` TrackMBID string `json:"track_mbid,omitempty"`
RecordingMBID string `json:"recording_mbid,omitempty"` RecordingMBID string `json:"recording_mbid,omitempty"`
TrackLength int `json:"track_length,omitempty"` ReleaseMBID string `json:"release_mbid,omitempty"`
Duration int `json:"duration,omitempty"`
SubmissionClient string `json:"submission_client,omitempty"`
} }
TrackMetadata struct { TrackMetadata struct {
+5 -1
View File
@@ -5,7 +5,11 @@
"listened_at": 1683804525, "listened_at": 1683804525,
"track_metadata": { "track_metadata": {
"additional_info": { "additional_info": {
"tracknumber": 1 "tracknumber": 1,
"duration": 242,
"recording_mbid": "00000000-0000-0000-0000-000000000000",
"release_mbid": "00000000-0000-0000-0000-000000000001",
"submission_client": "gonic"
}, },
"artist_name": "artist", "artist_name": "artist",
"track_name": "title", "track_name": "title",
+4 -4
View File
@@ -83,17 +83,17 @@ func (m *MockFS) DB() *db.DB { return m.db }
func (m *MockFS) TmpDir() string { return m.dir } func (m *MockFS) TmpDir() string { return m.dir }
func (m *MockFS) TagReader() tagcommon.Reader { return m.tagReader } func (m *MockFS) TagReader() tagcommon.Reader { return m.tagReader }
func (m *MockFS) ScanAndClean() *scanner.Context { func (m *MockFS) ScanAndClean() *scanner.State {
m.t.Helper() m.t.Helper()
ctx, err := m.scanner.ScanAndClean(scanner.ScanOptions{}) st, err := m.scanner.ScanAndClean(scanner.ScanOptions{})
if err != nil { if err != nil {
m.t.Fatalf("error scan and cleaning: %v", err) m.t.Fatalf("error scan and cleaning: %v", err)
} }
return ctx return st
} }
func (m *MockFS) ScanAndCleanErr() (*scanner.Context, error) { func (m *MockFS) ScanAndCleanErr() (*scanner.State, error) {
m.t.Helper() m.t.Helper()
return m.scanner.ScanAndClean(scanner.ScanOptions{}) return m.scanner.ScanAndClean(scanner.ScanOptions{})
+85 -61
View File
@@ -26,40 +26,6 @@ const (
extM3U8 = ".m3u8" extM3U8 = ".m3u8"
) )
type Store struct {
basePath string
mu sync.Mutex
}
func NewStore(basePath string) (*Store, error) {
if basePath == "" {
return nil, ErrInvalidBasePath
}
// sanity check layout, just in case someone tries to use an existing folder
entries, err := os.ReadDir(basePath)
if err != nil {
return nil, fmt.Errorf("sanity checking: reading dir: %w", err)
}
var found string
for _, entry := range entries {
if !entry.IsDir() {
continue
}
if _, err := userIDFromPath(entry.Name()); err != nil {
found = entry.Name()
break
}
}
if found != "" {
return nil, fmt.Errorf("sanity checking: %w: item %q in playlists directory is not a user id. see wiki for details on layout of the playlists dir", ErrNoUserPrefix, found)
}
return &Store{
basePath: basePath,
}, nil
}
type Playlist struct { type Playlist struct {
UpdatedAt time.Time UpdatedAt time.Time
UserID int UserID int
@@ -69,18 +35,33 @@ type Playlist struct {
IsPublic bool IsPublic bool
} }
func NewPath(userID int, playlistName string) string { type Store struct {
playlistName = fileutil.Safe(playlistName) basePath string
if playlistName == "" { mu sync.Mutex
playlistName = "pl" }
func NewStore(basePath string) (*Store, error) {
if basePath == "" {
return nil, ErrInvalidBasePath
} }
playlistName = fmt.Sprintf("%s-%d%s", playlistName, time.Now().UnixMilli(), extM3U) if err := sanityCheck(basePath); err != nil {
return filepath.Join(fmt.Sprint(userID), playlistName) return nil, err
}
return &Store{
basePath: basePath,
}, nil
} }
// List finds playlist items in s.basePath. // List finds playlist items in s.basePath.
// the expected format is <base path>/<user id>/**/<playlist name>.m3u // the expected format is <base path>/<user id>/**/<playlist name>.m3u
func (s *Store) List() ([]string, error) { func (s *Store) List() ([]string, error) {
defer lock(&s.mu)()
if err := sanityCheck(s.basePath); err != nil {
return nil, err
}
var relPaths []string var relPaths []string
return relPaths, filepath.WalkDir(s.basePath, func(path string, d fs.DirEntry, err error) error { return relPaths, filepath.WalkDir(s.basePath, func(path string, d fs.DirEntry, err error) error {
if err != nil { if err != nil {
@@ -100,30 +81,13 @@ func (s *Store) List() ([]string, error) {
}) })
} }
const (
attrPrefix = "#GONIC-"
attrName = "NAME"
attrCommment = "COMMENT"
attrIsPublic = "IS-PUBLIC"
)
func encodeAttr(name, value string) string {
return fmt.Sprintf("%s%s:%s", attrPrefix, name, strconv.Quote(value))
}
func decodeAttr(line string) (name, value string) {
if !strings.HasPrefix(line, attrPrefix) {
return "", ""
}
prefixAndName, rawValue, _ := strings.Cut(line, ":")
name = strings.TrimPrefix(prefixAndName, attrPrefix)
value, _ = strconv.Unquote(rawValue)
return name, value
}
func (s *Store) Read(relPath string) (*Playlist, error) { func (s *Store) Read(relPath string) (*Playlist, error) {
defer lock(&s.mu)() defer lock(&s.mu)()
if err := sanityCheck(s.basePath); err != nil {
return nil, err
}
absPath := filepath.Join(s.basePath, relPath) absPath := filepath.Join(s.basePath, relPath)
stat, err := os.Stat(absPath) stat, err := os.Stat(absPath)
if err != nil { if err != nil {
@@ -171,6 +135,10 @@ func (s *Store) Read(relPath string) (*Playlist, error) {
func (s *Store) Write(relPath string, playlist *Playlist) error { func (s *Store) Write(relPath string, playlist *Playlist) error {
defer lock(&s.mu)() defer lock(&s.mu)()
if err := sanityCheck(s.basePath); err != nil {
return err
}
absPath := filepath.Join(s.basePath, relPath) absPath := filepath.Join(s.basePath, relPath)
if err := os.MkdirAll(filepath.Dir(absPath), 0o777); err != nil { if err := os.MkdirAll(filepath.Dir(absPath), 0o777); err != nil {
return fmt.Errorf("make m3u base dir: %w", err) return fmt.Errorf("make m3u base dir: %w", err)
@@ -217,6 +185,10 @@ func (s *Store) Write(relPath string, playlist *Playlist) error {
} }
func (s *Store) Delete(relPath string) error { func (s *Store) Delete(relPath string) error {
if err := sanityCheck(s.basePath); err != nil {
return err
}
return os.Remove(filepath.Join(s.basePath, relPath)) return os.Remove(filepath.Join(s.basePath, relPath))
} }
@@ -237,3 +209,55 @@ func lock(mu *sync.Mutex) func() {
mu.Lock() mu.Lock()
return mu.Unlock return mu.Unlock
} }
func sanityCheck(basePath string) error {
// sanity check layout, just in case someone tries to use an existing folder
entries, err := os.ReadDir(basePath)
if err != nil {
return fmt.Errorf("sanity checking: reading dir: %w", err)
}
var found string
for _, entry := range entries {
if !entry.IsDir() {
continue
}
if _, err := userIDFromPath(entry.Name()); err != nil {
found = entry.Name()
break
}
}
if found != "" {
return fmt.Errorf("sanity checking: %w: item %q in playlists directory is not a user id. see wiki for details on layout of the playlists dir", ErrNoUserPrefix, found)
}
return nil
}
const (
attrPrefix = "#GONIC-"
attrName = "NAME"
attrCommment = "COMMENT"
attrIsPublic = "IS-PUBLIC"
)
func encodeAttr(name, value string) string {
return fmt.Sprintf("%s%s:%s", attrPrefix, name, strconv.Quote(value))
}
func decodeAttr(line string) (name, value string) {
if !strings.HasPrefix(line, attrPrefix) {
return "", ""
}
prefixAndName, rawValue, _ := strings.Cut(line, ":")
name = strings.TrimPrefix(prefixAndName, attrPrefix)
value, _ = strconv.Unquote(rawValue)
return name, value
}
func NewPath(userID int, playlistName string) string {
playlistName = fileutil.Safe(playlistName)
if playlistName == "" {
playlistName = "pl"
}
playlistName = fmt.Sprintf("%s-%d%s", playlistName, time.Now().UnixMilli(), extM3U)
return filepath.Join(fmt.Sprint(userID), playlistName)
}
+198 -225
View File
@@ -26,63 +26,44 @@ import (
var ErrNoAudioInFeedItem = errors.New("no audio in feed item") var ErrNoAudioInFeedItem = errors.New("no audio in feed item")
const ( const (
downloadAllWaitInterval = 3 * time.Second fetchUserAgent = `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11`
fetchUserAgent = `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11`
) )
type Podcasts struct { type Podcasts struct {
db *db.DB httpClient *http.Client
baseDir string db *db.DB
tagReader tagcommon.Reader baseDir string
tagReader tagcommon.Reader
} }
func New(db *db.DB, base string, tagReader tagcommon.Reader) *Podcasts { func New(db *db.DB, base string, tagReader tagcommon.Reader) *Podcasts {
return &Podcasts{ return &Podcasts{
db: db, db: db,
baseDir: base, baseDir: base,
tagReader: tagReader, tagReader: tagReader,
httpClient: &http.Client{},
} }
} }
func (p *Podcasts) GetPodcastOrAll(id int, includeEpisodes bool) ([]*db.Podcast, error) { func (p *Podcasts) GetPodcastOrAll(id int, includeEpisodes bool) ([]*db.Podcast, error) {
var err error var podcasts []*db.Podcast
podcasts := []*db.Podcast{} q := p.db.DB
if id != 0 { if id != 0 {
err = p.db.Where("id=?", id).Find(&podcasts).Error q = q.Where("id=?", id)
} else {
err = p.db.Find(&podcasts).Error
} }
if err != nil { if includeEpisodes {
return nil, fmt.Errorf("finding podcasts: %w", err) q = q.Preload("Episodes", func(db *gorm.DB) *gorm.DB {
return db.Order("podcast_episodes.publish_date DESC")
})
} }
if !includeEpisodes { if err := q.Find(&podcasts).Error; err != nil {
return podcasts, nil return nil, fmt.Errorf("find podcasts: %w", err)
}
for _, c := range podcasts {
episodes, err := p.GetPodcastEpisodes(c.ID)
if err != nil {
return nil, fmt.Errorf("finding podcast episodes: %w", err)
}
c.Episodes = episodes
} }
return podcasts, nil return podcasts, nil
} }
func (p *Podcasts) GetPodcastEpisodes(podcastID int) ([]*db.PodcastEpisode, error) {
episodes := []*db.PodcastEpisode{}
err := p.db.
Where("podcast_id=?", podcastID).
Order("publish_date DESC").
Find(&episodes).
Error
if err != nil {
return nil, fmt.Errorf("find episodes by podcast id: %w", err)
}
return episodes, nil
}
func (p *Podcasts) GetNewestPodcastEpisodes(count int) ([]*db.PodcastEpisode, error) { func (p *Podcasts) GetNewestPodcastEpisodes(count int) ([]*db.PodcastEpisode, error) {
episodes := []*db.PodcastEpisode{} var episodes []*db.PodcastEpisode
err := p.db. err := p.db.
Order("publish_date DESC"). Order("publish_date DESC").
Limit(count). Limit(count).
@@ -112,14 +93,12 @@ func (p *Podcasts) AddNewPodcast(rssURL string, feed *gofeed.Feed) (*db.Podcast,
if err := p.db.Save(&podcast).Error; err != nil { if err := p.db.Save(&podcast).Error; err != nil {
return &podcast, err return &podcast, err
} }
if err := p.AddNewEpisodes(&podcast, feed.Items); err != nil { if err := p.RefreshPodcast(&podcast, feed.Items); err != nil {
return nil, err log.Printf("error adding new episodes : %v", err)
}
if err := p.downloadPodcastCover(&podcast); err != nil {
log.Printf("error downloading podcast cover: %v", err)
} }
go func() {
if err := p.downloadPodcastCover(&podcast); err != nil {
log.Printf("error downloading podcast cover: %v", err)
}
}()
return &podcast, nil return &podcast, nil
} }
@@ -150,67 +129,42 @@ func getEntriesAfterDate(feed []*gofeed.Item, after time.Time) []*gofeed.Item {
return items return items
} }
func (p *Podcasts) AddNewEpisodes(podcast *db.Podcast, items []*gofeed.Item) error { func (p *Podcasts) RefreshPodcast(podcast *db.Podcast, items []*gofeed.Item) error {
podcastEpisode := db.PodcastEpisode{} var lastPodcastEpisode db.PodcastEpisode
err := p.db. err := p.db.
Where("podcast_id=?", podcast.ID). Where("podcast_id=?", podcast.ID).
Order("publish_date DESC"). Order("publish_date DESC").
First(&podcastEpisode).Error First(&lastPodcastEpisode).
itemFound := true Error
if errors.Is(err, gorm.ErrRecordNotFound) { if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
itemFound = false
} else if err != nil {
return err return err
} }
if !itemFound {
for _, item := range items { if lastPodcastEpisode.ID != 0 {
if _, err := p.AddEpisode(podcast.ID, item); err != nil { items = getEntriesAfterDate(items, *lastPodcastEpisode.PublishDate)
return err
}
}
return nil
} }
for _, item := range getEntriesAfterDate(items, *podcastEpisode.PublishDate) {
episode, err := p.AddEpisode(podcast.ID, item) var episodeErrs []error
if errors.Is(err, ErrNoAudioInFeedItem) { for _, item := range items {
log.Printf("failed to find audio in feed (%s, %s) item, skipping", podcast.Title, item.Title) podcastEpisode, err := p.addEpisode(podcast.ID, item)
if err != nil {
episodeErrs = append(episodeErrs, err)
continue continue
} }
if err != nil {
return err if lastPodcastEpisode.ID != 0 && podcast.AutoDownload == db.PodcastAutoDownloadLatest {
} podcastEpisode.Status = db.PodcastEpisodeStatusDownloading
if podcast.AutoDownload == db.PodcastAutoDownloadLatest && if err := p.db.Save(&podcastEpisode).Error; err != nil {
(episode.Status != db.PodcastEpisodeStatusCompleted && episode.Status != db.PodcastEpisodeStatusDownloading) { return fmt.Errorf("save podcast episode: %w", err)
if err := p.DownloadEpisode(episode.ID); err != nil {
return err
} }
} }
} }
return nil
return errors.Join(episodeErrs...)
} }
func getSecondsFromString(time string) int { func (p *Podcasts) addEpisode(podcastID int, item *gofeed.Item) (*db.PodcastEpisode, error) {
duration, err := strconv.Atoi(time) var duration int
if err == nil {
return duration
}
splitTime := strings.Split(time, ":")
if len(splitTime) == 3 {
hours, _ := strconv.Atoi(splitTime[0])
minutes, _ := strconv.Atoi(splitTime[1])
seconds, _ := strconv.Atoi(splitTime[2])
return (3600 * hours) + (60 * minutes) + seconds
}
if len(splitTime) == 2 {
minutes, _ := strconv.Atoi(splitTime[0])
seconds, _ := strconv.Atoi(splitTime[1])
return (60 * minutes) + seconds
}
return 0
}
func (p *Podcasts) AddEpisode(podcastID int, item *gofeed.Item) (*db.PodcastEpisode, error) {
duration := 0
// if it has the media extension use it // if it has the media extension use it
for _, content := range item.Extensions["media"]["content"] { for _, content := range item.Extensions["media"]["content"] {
durationExt := content.Attrs["duration"] durationExt := content.Attrs["duration"]
@@ -247,9 +201,7 @@ func (p *Podcasts) isAudio(rawItemURL string) (bool, error) {
return p.tagReader.CanRead(itemURL.Path), nil return p.tagReader.CanRead(itemURL.Path), nil
} }
func itemToEpisode(podcastID, size, duration int, audio string, func itemToEpisode(podcastID, size, duration int, audio string, item *gofeed.Item) *db.PodcastEpisode {
item *gofeed.Item,
) *db.PodcastEpisode {
return &db.PodcastEpisode{ return &db.PodcastEpisode{
PodcastID: podcastID, PodcastID: podcastID,
Description: item.Description, Description: item.Description,
@@ -288,17 +240,11 @@ func (p *Podcasts) findMediaAudio(podcastID, duration int, item *gofeed.Item) (*
} }
func (p *Podcasts) RefreshPodcasts() error { func (p *Podcasts) RefreshPodcasts() error {
podcasts := []*db.Podcast{} var podcasts []*db.Podcast
if err := p.db.Find(&podcasts).Error; err != nil { if err := p.db.Find(&podcasts).Error; err != nil {
return fmt.Errorf("find podcasts: %w", err) return fmt.Errorf("find podcasts: %w", err)
} }
if err := p.refreshPodcasts(podcasts); err != nil {
return fmt.Errorf("refresh podcasts: %w", err)
}
return nil
}
func (p *Podcasts) refreshPodcasts(podcasts []*db.Podcast) error {
var errs []error var errs []error
for _, podcast := range podcasts { for _, podcast := range podcasts {
fp := gofeed.NewParser() fp := gofeed.NewParser()
@@ -307,7 +253,7 @@ func (p *Podcasts) refreshPodcasts(podcasts []*db.Podcast) error {
errs = append(errs, fmt.Errorf("refreshing podcast with url %q: %w", podcast.URL, err)) errs = append(errs, fmt.Errorf("refreshing podcast with url %q: %w", podcast.URL, err))
continue continue
} }
if err = p.AddNewEpisodes(podcast, feed.Items); err != nil { if err = p.RefreshPodcast(podcast, feed.Items); err != nil {
errs = append(errs, fmt.Errorf("adding episodes: %w", err)) errs = append(errs, fmt.Errorf("adding episodes: %w", err))
continue continue
} }
@@ -316,97 +262,57 @@ func (p *Podcasts) refreshPodcasts(podcasts []*db.Podcast) error {
} }
func (p *Podcasts) DownloadPodcastAll(podcastID int) error { func (p *Podcasts) DownloadPodcastAll(podcastID int) error {
podcastEpisodes := []db.PodcastEpisode{}
err := p.db. err := p.db.
Model(db.PodcastEpisode{}).
Where("status=?", db.PodcastEpisodeStatusSkipped).
Where("podcast_id=?", podcastID). Where("podcast_id=?", podcastID).
Find(&podcastEpisodes). Update("status", db.PodcastEpisodeStatusDownloading).
Error Error
if err != nil { if err != nil {
return fmt.Errorf("get episodes by podcast id: %w", err) return fmt.Errorf("update podcast episodes: %w", err)
} }
go func() {
for _, episode := range podcastEpisodes {
if episode.Status == db.PodcastEpisodeStatusDownloading || episode.Status == db.PodcastEpisodeStatusCompleted {
log.Println("skipping episode is in progress or already downloaded")
continue
}
if err := p.DownloadEpisode(episode.ID); err != nil {
log.Printf("error downloading episode: %v", err)
continue
}
log.Printf("finished downloading episode: %q", episode.Title)
time.Sleep(downloadAllWaitInterval)
}
}()
return nil return nil
} }
func (p *Podcasts) DownloadEpisode(episodeID int) error { func (p *Podcasts) DownloadEpisode(episodeID int) error {
podcastEpisode := db.PodcastEpisode{}
podcast := db.Podcast{}
err := p.db. err := p.db.
Preload("Podcast"). Model(db.PodcastEpisode{}).
Where("id=?", episodeID). Where("id=?", episodeID).
First(&podcastEpisode). Update("status", db.PodcastEpisodeStatusDownloading).
Error Error
if err != nil { if err != nil {
return fmt.Errorf("get podcast episode by id: %w", err) return fmt.Errorf("update podcast episodes: %w", err)
} }
err = p.db. return nil
Where("id=?", podcastEpisode.PodcastID). }
First(&podcast).
Error func getContentDispositionFilename(header http.Header) (string, bool) {
if err != nil { contentHeader := header.Get("content-disposition")
return fmt.Errorf("get podcast by id: %w", err) _, params, _ := mime.ParseMediaType(contentHeader)
filename, ok := params["filename"]
return filename, ok
}
func getPodcastEpisodeFilename(podcast *db.Podcast, podcastEpisode *db.PodcastEpisode, header http.Header) (string, error) {
if podcastEpisode.Filename != "" {
return podcastEpisode.Filename, nil
} }
if podcastEpisode.Status == db.PodcastEpisodeStatusDownloading || podcastEpisode.Status == db.PodcastEpisodeStatusCompleted {
log.Printf("already downloading podcast episode with id %d", episodeID) filename, ok := getContentDispositionFilename(header)
return nil
}
podcastEpisode.Status = db.PodcastEpisodeStatusDownloading
p.db.Save(&podcastEpisode)
client := &http.Client{}
req, err := http.NewRequest("GET", podcastEpisode.AudioURL, nil)
if err != nil {
return fmt.Errorf("create http request: %w", err)
}
req.Header.Add("User-Agent", fetchUserAgent)
// nolint: bodyclose
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("fetch podcast audio: %w", err)
}
filename, ok := getContentDispositionFilename(resp.Header.Get("content-disposition"))
if !ok { if !ok {
audioURL, err := url.Parse(podcastEpisode.AudioURL) audioURL, err := url.Parse(podcastEpisode.AudioURL)
if err != nil { if err != nil {
return fmt.Errorf("parse podcast audio url: %w", err) return "", fmt.Errorf("parse podcast audio url: %w", err)
} }
filename = path.Base(audioURL.Path) filename = path.Base(audioURL.Path)
} }
path, err := fileutil.Unique(podcast.RootDir, fileutil.Safe(filename)) path, err := fileutil.Unique(podcast.RootDir, fileutil.Safe(filename))
if err != nil { if err != nil {
return fmt.Errorf("find unique path: %w", err) return "", fmt.Errorf("find unique path: %w", err)
} }
_, filename = filepath.Split(path) _, filename = filepath.Split(path)
audioFile, err := os.Create(filepath.Join(podcast.RootDir, filename))
if err != nil {
return fmt.Errorf("create audio file: %w", err)
}
podcastEpisode.Filename = filename
p.db.Save(&podcastEpisode)
go func() {
if err := p.doPodcastDownload(&podcastEpisode, audioFile, resp.Body); err != nil {
log.Printf("error downloading podcast: %v", err)
}
}()
return nil
}
func getContentDispositionFilename(header string) (string, bool) { return filename, nil
_, params, _ := mime.ParseMediaType(header)
filename, ok := params["filename"]
return filename, ok
} }
func (p *Podcasts) downloadPodcastCover(podcast *db.Podcast) error { func (p *Podcasts) downloadPodcastCover(podcast *db.Podcast) error {
@@ -420,22 +326,22 @@ func (p *Podcasts) downloadPodcastCover(podcast *db.Podcast) error {
} }
req.Header.Add("User-Agent", fetchUserAgent) req.Header.Add("User-Agent", fetchUserAgent)
client := &http.Client{} resp, err := p.httpClient.Do(req)
resp, err := client.Do(req)
if err != nil { if err != nil {
return fmt.Errorf("fetch image url: %w", err) return fmt.Errorf("fetch image url: %w", err)
} }
defer resp.Body.Close() defer resp.Body.Close()
ext := path.Ext(imageURL.Path) var ext = path.Ext(imageURL.Path)
if ext == "" { if ext == "" {
contentHeader := resp.Header.Get("content-disposition") filename, _ := getContentDispositionFilename(resp.Header)
filename, _ := getContentDispositionFilename(contentHeader)
ext = filepath.Ext(filename) ext = filepath.Ext(filename)
} }
cover := "cover" + ext if err := os.MkdirAll(podcast.RootDir, os.ModePerm); err != nil {
coverFile, err := os.Create(filepath.Join(podcast.RootDir, cover)) return fmt.Errorf("make podcast root dir: %w", err)
}
coverFile, err := os.Create(filepath.Join(podcast.RootDir, "cover"+ext))
if err != nil { if err != nil {
return fmt.Errorf("creating podcast cover: %w", err) return fmt.Errorf("creating podcast cover: %w", err)
} }
@@ -451,39 +357,9 @@ func (p *Podcasts) downloadPodcastCover(podcast *db.Podcast) error {
return nil return nil
} }
func (p *Podcasts) doPodcastDownload(podcastEpisode *db.PodcastEpisode, file *os.File, src io.Reader) error {
if _, err := io.Copy(file, src); err != nil {
return fmt.Errorf("writing podcast episode: %w", err)
}
defer file.Close()
podcastTags, err := p.tagReader.Read(podcastEpisode.AbsPath())
if err != nil {
log.Printf("error parsing podcast audio: %e", err)
podcastEpisode.Status = db.PodcastEpisodeStatusError
p.db.Save(podcastEpisode)
return nil
}
stat, _ := file.Stat()
podcastEpisode.Bitrate = podcastTags.Bitrate()
podcastEpisode.Status = db.PodcastEpisodeStatusCompleted
podcastEpisode.Length = podcastTags.Length()
podcastEpisode.Size = int(stat.Size())
if err := p.db.Save(podcastEpisode).Error; err != nil {
return fmt.Errorf("save podcast episode: %w", err)
}
return nil
}
func (p *Podcasts) DeletePodcast(podcastID int) error { func (p *Podcasts) DeletePodcast(podcastID int) error {
podcast := db.Podcast{} var podcast db.Podcast
err := p.db. if err := p.db.Where("id=?", podcastID).First(&podcast).Error; err != nil {
Where("id=?", podcastID).
First(&podcast).
Error
if err != nil {
return err return err
} }
if podcast.RootDir == "" { if podcast.RootDir == "" {
@@ -493,38 +369,36 @@ func (p *Podcasts) DeletePodcast(podcastID int) error {
if err := os.RemoveAll(podcast.RootDir); err != nil { if err := os.RemoveAll(podcast.RootDir); err != nil {
return fmt.Errorf("delete podcast directory: %w", err) return fmt.Errorf("delete podcast directory: %w", err)
} }
err = p.db.
Where("id=?", podcastID). if err := p.db.Where("id=?", podcastID).Delete(db.Podcast{}).Error; err != nil {
Delete(db.Podcast{}).
Error
if err != nil {
return fmt.Errorf("delete podcast row: %w", err) return fmt.Errorf("delete podcast row: %w", err)
} }
return nil return nil
} }
func (p *Podcasts) DeletePodcastEpisode(podcastEpisodeID int) error { func (p *Podcasts) DeletePodcastEpisode(podcastEpisodeID int) error {
episode := db.PodcastEpisode{} var podcastEpisode db.PodcastEpisode
err := p.db.Preload("Podcast").First(&episode, podcastEpisodeID).Error if err := p.db.Preload("Podcast").First(&podcastEpisode, podcastEpisodeID).Error; err != nil {
if err != nil {
return err return err
} }
episode.Status = db.PodcastEpisodeStatusDeleted podcastEpisode.Status = db.PodcastEpisodeStatusDeleted
p.db.Save(&episode) if err := p.db.Save(&podcastEpisode).Error; err != nil {
if err := os.Remove(episode.AbsPath()); err != nil { return fmt.Errorf("save podcast episode: %w", err)
return err
} }
return err if err := os.Remove(podcastEpisode.AbsPath()); err != nil {
return fmt.Errorf("remove episode: %w", err)
}
return nil
} }
func (p *Podcasts) PurgeOldPodcasts(maxAge time.Duration) error { func (p *Podcasts) PurgeOldPodcasts(maxAge time.Duration) error {
expDate := time.Now().Add(-maxAge) expDate := time.Now().Add(-maxAge)
var episodes []*db.PodcastEpisode var episodes []*db.PodcastEpisode
err := p.db. err := p.db.
Where("status = ?", db.PodcastEpisodeStatusCompleted). Where("status=?", db.PodcastEpisodeStatusCompleted).
Where("created_at < ?", expDate). Where("created_at<?", expDate).
Where("updated_at < ?", expDate). Where("updated_at<?", expDate).
Where("modified_at < ?", expDate). Where("modified_at<?", expDate).
Preload("Podcast"). Preload("Podcast").
Find(&episodes). Find(&episodes).
Error Error
@@ -545,3 +419,102 @@ func (p *Podcasts) PurgeOldPodcasts(maxAge time.Duration) error {
} }
return nil return nil
} }
func getSecondsFromString(time string) int {
duration, err := strconv.Atoi(time)
if err == nil {
return duration
}
splitTime := strings.Split(time, ":")
if len(splitTime) == 3 {
hours, _ := strconv.Atoi(splitTime[0])
minutes, _ := strconv.Atoi(splitTime[1])
seconds, _ := strconv.Atoi(splitTime[2])
return (3600 * hours) + (60 * minutes) + seconds
}
if len(splitTime) == 2 {
minutes, _ := strconv.Atoi(splitTime[0])
seconds, _ := strconv.Atoi(splitTime[1])
return (60 * minutes) + seconds
}
return 0
}
func (p *Podcasts) DownloadTick() error {
var podcastEpisode db.PodcastEpisode
err := p.db.
Preload("Podcast").
Where("status=?", db.PodcastEpisodeStatusDownloading).
Order("updated_at DESC").
Find(&podcastEpisode).
Error
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
return fmt.Errorf("find episode: %w", err)
}
if podcastEpisode.ID == 0 {
return nil
}
if err := p.doPodcastDownload(podcastEpisode.Podcast, &podcastEpisode); err != nil {
return fmt.Errorf("do download: %w", err)
}
log.Printf("downloaded podcast episode %q - %q", podcastEpisode.Podcast.Title, podcastEpisode.Title)
return nil
}
func (p *Podcasts) doPodcastDownload(podcast *db.Podcast, podcastEpisode *db.PodcastEpisode) (err error) {
req, err := http.NewRequest(http.MethodGet, podcastEpisode.AudioURL, nil)
if err != nil {
return fmt.Errorf("create http request: %w", err)
}
req.Header.Add("User-Agent", fetchUserAgent)
resp, err := p.httpClient.Do(req)
if err != nil {
return fmt.Errorf("fetch podcast audio: %w", err)
}
defer resp.Body.Close()
filename, err := getPodcastEpisodeFilename(podcast, podcastEpisode, resp.Header)
if err != nil {
return fmt.Errorf("get podcast episode filename: %w", err)
}
podcastEpisode.Filename = filename
if err := p.db.Save(&podcastEpisode).Error; err != nil {
return fmt.Errorf("save podcast episode: %w", err)
}
file, err := os.Create(filepath.Join(podcast.RootDir, podcastEpisode.Filename))
if err != nil {
return fmt.Errorf("create audio file: %w", err)
}
defer file.Close()
defer func() {
if err != nil {
podcastEpisode.Status = db.PodcastEpisodeStatusError
_ = p.db.Save(&podcastEpisode).Error
}
}()
if _, err := io.Copy(file, resp.Body); err != nil {
return fmt.Errorf("writing podcast episode: %w", err)
}
podcastTags, err := p.tagReader.Read(podcastEpisode.AbsPath())
if err != nil {
return fmt.Errorf("read podcast tags: %w", err)
}
podcastEpisode.Status = db.PodcastEpisodeStatusCompleted
podcastEpisode.Bitrate = podcastTags.Bitrate()
podcastEpisode.Length = podcastTags.Length()
stat, _ := file.Stat()
podcastEpisode.Size = int(stat.Size())
if err := p.db.Save(podcastEpisode).Error; err != nil {
return fmt.Errorf("save podcast episode: %w", err)
}
return nil
}
+91 -68
View File
@@ -9,6 +9,7 @@ import (
"os" "os"
"path/filepath" "path/filepath"
"regexp" "regexp"
"slices"
"sort" "sort"
"strconv" "strconv"
"strings" "strings"
@@ -20,6 +21,7 @@ import (
"github.com/rainycape/unidecode" "github.com/rainycape/unidecode"
"go.senan.xyz/gonic/db" "go.senan.xyz/gonic/db"
"go.senan.xyz/gonic/fileutil"
"go.senan.xyz/gonic/tags/tagcommon" "go.senan.xyz/gonic/tags/tagcommon"
) )
@@ -61,14 +63,14 @@ type ScanOptions struct {
IsFull bool IsFull bool
} }
func (s *Scanner) ScanAndClean(opts ScanOptions) (*Context, error) { func (s *Scanner) ScanAndClean(opts ScanOptions) (*State, error) {
if !s.StartScanning() { if !s.StartScanning() {
return nil, ErrAlreadyScanning return nil, ErrAlreadyScanning
} }
defer s.StopScanning() defer s.StopScanning()
start := time.Now() start := time.Now()
c := &Context{ st := &State{
seenTracks: map[int]struct{}{}, seenTracks: map[int]struct{}{},
seenAlbums: map[int]struct{}{}, seenAlbums: map[int]struct{}{},
isFull: opts.IsFull, isFull: opts.IsFull,
@@ -77,28 +79,28 @@ func (s *Scanner) ScanAndClean(opts ScanOptions) (*Context, error) {
log.Println("starting scan") log.Println("starting scan")
defer func() { defer func() {
log.Printf("finished scan in %s, +%d/%d tracks (%d err)\n", log.Printf("finished scan in %s, +%d/%d tracks (%d err)\n",
durSince(start), c.SeenTracksNew(), c.SeenTracks(), len(c.errs)) durSince(start), st.SeenTracksNew(), st.SeenTracks(), len(st.errs))
}() }()
for _, dir := range s.musicDirs { for _, dir := range s.musicDirs {
err := filepath.WalkDir(dir, func(absPath string, d fs.DirEntry, err error) error { err := filepath.WalkDir(dir, func(absPath string, d fs.DirEntry, err error) error {
return s.scanCallback(c, absPath, d, err) return s.scanCallback(st, absPath, d, err)
}) })
if err != nil { if err != nil {
return nil, fmt.Errorf("walk: %w", err) return nil, fmt.Errorf("walk: %w", err)
} }
} }
if err := s.cleanTracks(c); err != nil { if err := s.cleanTracks(st); err != nil {
return nil, fmt.Errorf("clean tracks: %w", err) return nil, fmt.Errorf("clean tracks: %w", err)
} }
if err := s.cleanAlbums(c); err != nil { if err := s.cleanAlbums(st); err != nil {
return nil, fmt.Errorf("clean albums: %w", err) return nil, fmt.Errorf("clean albums: %w", err)
} }
if err := s.cleanArtists(c); err != nil { if err := s.cleanArtists(st); err != nil {
return nil, fmt.Errorf("clean artists: %w", err) return nil, fmt.Errorf("clean artists: %w", err)
} }
if err := s.cleanGenres(c); err != nil { if err := s.cleanGenres(st); err != nil {
return nil, fmt.Errorf("clean genres: %w", err) return nil, fmt.Errorf("clean genres: %w", err)
} }
@@ -106,7 +108,7 @@ func (s *Scanner) ScanAndClean(opts ScanOptions) (*Context, error) {
return nil, fmt.Errorf("set scan time: %w", err) return nil, fmt.Errorf("set scan time: %w", err)
} }
return c, errors.Join(c.errs...) return st, errors.Join(st.errs...)
} }
func (s *Scanner) ExecuteWatch(done <-chan struct{}) error { func (s *Scanner) ExecuteWatch(done <-chan struct{}) error {
@@ -138,11 +140,11 @@ func (s *Scanner) ExecuteWatch(done <-chan struct{}) error {
break break
} }
for absPath := range batchSeen { for absPath := range batchSeen {
c := &Context{ st := &State{
seenTracks: map[int]struct{}{}, seenTracks: map[int]struct{}{},
seenAlbums: map[int]struct{}{}, seenAlbums: map[int]struct{}{},
} }
err = filepath.WalkDir(absPath, func(absPath string, d fs.DirEntry, err error) error { err := filepath.WalkDir(absPath, func(absPath string, d fs.DirEntry, err error) error {
return watchCallback(watcher, absPath, d, err) return watchCallback(watcher, absPath, d, err)
}) })
if err != nil { if err != nil {
@@ -150,7 +152,7 @@ func (s *Scanner) ExecuteWatch(done <-chan struct{}) error {
continue continue
} }
err = filepath.WalkDir(absPath, func(absPath string, d fs.DirEntry, err error) error { err = filepath.WalkDir(absPath, func(absPath string, d fs.DirEntry, err error) error {
return s.scanCallback(c, absPath, d, err) return s.scanCallback(st, absPath, d, err)
}) })
if err != nil { if err != nil {
log.Printf("error walking: %v", err) log.Printf("error walking: %v", err)
@@ -175,7 +177,7 @@ func (s *Scanner) ExecuteWatch(done <-chan struct{}) error {
} }
batchT.Reset(batchInterval) batchT.Reset(batchInterval)
case err = <-watcher.Errors: case err := <-watcher.Errors:
log.Printf("error from watcher: %v\n", err) log.Printf("error from watcher: %v\n", err)
case <-done: case <-done:
@@ -192,9 +194,7 @@ func watchCallback(watcher *fsnotify.Watcher, absPath string, d fs.DirEntry, err
switch d.Type() { switch d.Type() {
case os.ModeDir: case os.ModeDir:
case os.ModeSymlink: case os.ModeSymlink:
eval, _ := filepath.EvalSymlinks(absPath) return symWalk(absPath, func(subAbs string, d fs.DirEntry, err error) error {
return filepath.WalkDir(eval, func(subAbs string, d fs.DirEntry, err error) error {
subAbs = strings.Replace(subAbs, eval, absPath, 1)
return watchCallback(watcher, subAbs, d, err) return watchCallback(watcher, subAbs, d, err)
}) })
default: default:
@@ -207,19 +207,17 @@ func watchCallback(watcher *fsnotify.Watcher, absPath string, d fs.DirEntry, err
return nil return nil
} }
func (s *Scanner) scanCallback(c *Context, absPath string, d fs.DirEntry, err error) error { func (s *Scanner) scanCallback(st *State, absPath string, d fs.DirEntry, err error) error {
if err != nil { if err != nil {
c.errs = append(c.errs, err) st.errs = append(st.errs, err)
return nil return nil
} }
switch d.Type() { switch d.Type() {
case os.ModeDir: case os.ModeDir:
case os.ModeSymlink: case os.ModeSymlink:
eval, _ := filepath.EvalSymlinks(absPath) return symWalk(absPath, func(subAbs string, d fs.DirEntry, err error) error {
return filepath.WalkDir(eval, func(subAbs string, d fs.DirEntry, err error) error { return s.scanCallback(st, subAbs, d, err)
subAbs = strings.Replace(subAbs, eval, absPath, 1)
return s.scanCallback(c, subAbs, d, err)
}) })
default: default:
return nil return nil
@@ -233,15 +231,15 @@ func (s *Scanner) scanCallback(c *Context, absPath string, d fs.DirEntry, err er
log.Printf("processing folder %q", absPath) log.Printf("processing folder %q", absPath)
return s.db.Transaction(func(tx *db.DB) error { return s.db.Transaction(func(tx *db.DB) error {
if err := s.scanDir(tx, c, absPath); err != nil { if err := s.scanDir(tx, st, absPath); err != nil {
c.errs = append(c.errs, fmt.Errorf("%q: %w", absPath, err)) st.errs = append(st.errs, fmt.Errorf("%q: %w", absPath, err))
return nil return nil
} }
return nil return nil
}) })
} }
func (s *Scanner) scanDir(tx *db.DB, c *Context, absPath string) error { func (s *Scanner) scanDir(tx *db.DB, st *State, absPath string) error {
musicDir, relPath := musicDirRelative(s.musicDirs, absPath) musicDir, relPath := musicDirRelative(s.musicDirs, absPath)
if musicDir == absPath { if musicDir == absPath {
return nil return nil
@@ -280,7 +278,7 @@ func (s *Scanner) scanDir(tx *db.DB, c *Context, absPath string) error {
return fmt.Errorf("first or create parent: %w", err) return fmt.Errorf("first or create parent: %w", err)
} }
c.seenAlbums[parent.ID] = struct{}{} st.seenAlbums[parent.ID] = struct{}{}
dir, basename := filepath.Split(relPath) dir, basename := filepath.Split(relPath)
var album db.Album var album db.Album
@@ -288,12 +286,12 @@ func (s *Scanner) scanDir(tx *db.DB, c *Context, absPath string) error {
return fmt.Errorf("populate album basics: %w", err) return fmt.Errorf("populate album basics: %w", err)
} }
c.seenAlbums[album.ID] = struct{}{} st.seenAlbums[album.ID] = struct{}{}
sort.Strings(tracks) sort.Strings(tracks)
for i, basename := range tracks { for i, basename := range tracks {
absPath := filepath.Join(musicDir, relPath, basename) absPath := filepath.Join(musicDir, relPath, basename)
if err := s.populateTrackAndArtists(tx, c, i, &album, basename, absPath); err != nil { if err := s.populateTrackAndArtists(tx, st, i, &album, basename, absPath); err != nil {
return fmt.Errorf("populate track %q: %w", basename, err) return fmt.Errorf("populate track %q: %w", basename, err)
} }
} }
@@ -301,7 +299,7 @@ func (s *Scanner) scanDir(tx *db.DB, c *Context, absPath string) error {
return nil return nil
} }
func (s *Scanner) populateTrackAndArtists(tx *db.DB, c *Context, i int, album *db.Album, basename string, absPath string) error { func (s *Scanner) populateTrackAndArtists(tx *db.DB, st *State, i int, album *db.Album, basename string, absPath string) error {
stat, err := os.Stat(absPath) stat, err := os.Stat(absPath)
if err != nil { if err != nil {
return fmt.Errorf("stating %q: %w", basename, err) return fmt.Errorf("stating %q: %w", basename, err)
@@ -312,8 +310,8 @@ func (s *Scanner) populateTrackAndArtists(tx *db.DB, c *Context, i int, album *d
return fmt.Errorf("query track: %w", err) return fmt.Errorf("query track: %w", err)
} }
if !c.isFull && track.ID != 0 && stat.ModTime().Before(track.UpdatedAt) { if !st.isFull && track.ID != 0 && stat.ModTime().Before(track.UpdatedAt) {
c.seenTracks[track.ID] = struct{}{} st.seenTracks[track.ID] = struct{}{}
return nil return nil
} }
@@ -322,7 +320,7 @@ func (s *Scanner) populateTrackAndArtists(tx *db.DB, c *Context, i int, album *d
return fmt.Errorf("%w: %w", err, ErrReadingTags) return fmt.Errorf("%w: %w", err, ErrReadingTags)
} }
genreNames := parseMulti(trags, s.multiValueSettings[Genre], tagcommon.MustGenres, tagcommon.MustGenre) genreNames := ParseMulti(s.multiValueSettings[Genre], tagcommon.MustGenres(trags), tagcommon.MustGenre(trags))
genreIDs, err := populateGenres(tx, genreNames) genreIDs, err := populateGenres(tx, genreNames)
if err != nil { if err != nil {
return fmt.Errorf("populate genres: %w", err) return fmt.Errorf("populate genres: %w", err)
@@ -334,7 +332,7 @@ func (s *Scanner) populateTrackAndArtists(tx *db.DB, c *Context, i int, album *d
return fmt.Errorf("delete artist appearances: %w", err) return fmt.Errorf("delete artist appearances: %w", err)
} }
albumArtistNames := parseMulti(trags, s.multiValueSettings[AlbumArtist], tagcommon.MustAlbumArtists, tagcommon.MustAlbumArtist) albumArtistNames := ParseMulti(s.multiValueSettings[AlbumArtist], tagcommon.MustAlbumArtists(trags), tagcommon.MustAlbumArtist(trags))
var albumArtistIDs []int var albumArtistIDs []int
for _, albumArtistName := range albumArtistNames { for _, albumArtistName := range albumArtistNames {
albumArtist, err := populateArtist(tx, albumArtistName) albumArtist, err := populateArtist(tx, albumArtistName)
@@ -367,7 +365,7 @@ func (s *Scanner) populateTrackAndArtists(tx *db.DB, c *Context, i int, album *d
return fmt.Errorf("populate track genres: %w", err) return fmt.Errorf("populate track genres: %w", err)
} }
trackArtistNames := parseMulti(trags, s.multiValueSettings[Artist], tagcommon.MustArtists, tagcommon.MustArtist) trackArtistNames := ParseMulti(s.multiValueSettings[Artist], tagcommon.MustArtists(trags), tagcommon.MustArtist(trags))
var trackArtistIDs []int var trackArtistIDs []int
for _, trackArtistName := range trackArtistNames { for _, trackArtistName := range trackArtistNames {
trackArtist, err := populateArtist(tx, trackArtistName) trackArtist, err := populateArtist(tx, trackArtistName)
@@ -384,8 +382,8 @@ func (s *Scanner) populateTrackAndArtists(tx *db.DB, c *Context, i int, album *d
return fmt.Errorf("populate track artists: %w", err) return fmt.Errorf("populate track artists: %w", err)
} }
c.seenTracks[track.ID] = struct{}{} st.seenTracks[track.ID] = struct{}{}
c.seenTracksNew++ st.seenTracksNew++
return nil return nil
} }
@@ -540,9 +538,9 @@ func populateArtistAppearances(tx *db.DB, album *db.Album, artistIDs []int) erro
return nil return nil
} }
func (s *Scanner) cleanTracks(c *Context) error { func (s *Scanner) cleanTracks(st *State) error {
start := time.Now() start := time.Now()
defer func() { log.Printf("finished clean tracks in %s, %d removed", durSince(start), c.TracksMissing()) }() defer func() { log.Printf("finished clean tracks in %s, %d removed", durSince(start), st.TracksMissing()) }()
var all []int var all []int
err := s.db. err := s.db.
@@ -553,18 +551,18 @@ func (s *Scanner) cleanTracks(c *Context) error {
return fmt.Errorf("plucking ids: %w", err) return fmt.Errorf("plucking ids: %w", err)
} }
for _, a := range all { for _, a := range all {
if _, ok := c.seenTracks[a]; !ok { if _, ok := st.seenTracks[a]; !ok {
c.tracksMissing = append(c.tracksMissing, int64(a)) st.tracksMissing = append(st.tracksMissing, int64(a))
} }
} }
return s.db.TransactionChunked(c.tracksMissing, func(tx *db.DB, chunk []int64) error { return s.db.TransactionChunked(st.tracksMissing, func(tx *db.DB, chunk []int64) error {
return tx.Where(chunk).Delete(&db.Track{}).Error return tx.Where(chunk).Delete(&db.Track{}).Error
}) })
} }
func (s *Scanner) cleanAlbums(c *Context) error { func (s *Scanner) cleanAlbums(st *State) error {
start := time.Now() start := time.Now()
defer func() { log.Printf("finished clean albums in %s, %d removed", durSince(start), c.AlbumsMissing()) }() defer func() { log.Printf("finished clean albums in %s, %d removed", durSince(start), st.AlbumsMissing()) }()
var all []int var all []int
err := s.db. err := s.db.
@@ -575,18 +573,18 @@ func (s *Scanner) cleanAlbums(c *Context) error {
return fmt.Errorf("plucking ids: %w", err) return fmt.Errorf("plucking ids: %w", err)
} }
for _, a := range all { for _, a := range all {
if _, ok := c.seenAlbums[a]; !ok { if _, ok := st.seenAlbums[a]; !ok {
c.albumsMissing = append(c.albumsMissing, int64(a)) st.albumsMissing = append(st.albumsMissing, int64(a))
} }
} }
return s.db.TransactionChunked(c.albumsMissing, func(tx *db.DB, chunk []int64) error { return s.db.TransactionChunked(st.albumsMissing, func(tx *db.DB, chunk []int64) error {
return tx.Where(chunk).Delete(&db.Album{}).Error return tx.Where(chunk).Delete(&db.Album{}).Error
}) })
} }
func (s *Scanner) cleanArtists(c *Context) error { func (s *Scanner) cleanArtists(st *State) error {
start := time.Now() start := time.Now()
defer func() { log.Printf("finished clean artists in %s, %d removed", durSince(start), c.ArtistsMissing()) }() defer func() { log.Printf("finished clean artists in %s, %d removed", durSince(start), st.ArtistsMissing()) }()
// gorm doesn't seem to support subqueries without parens for UNION // gorm doesn't seem to support subqueries without parens for UNION
q := s.db.Exec(` q := s.db.Exec(`
@@ -602,30 +600,44 @@ func (s *Scanner) cleanArtists(c *Context) error {
if err := q.Error; err != nil { if err := q.Error; err != nil {
return err return err
} }
c.artistsMissing = int(q.RowsAffected) st.artistsMissing = int(q.RowsAffected)
return nil return nil
} }
func (s *Scanner) cleanGenres(c *Context) error { //nolint:unparam func (s *Scanner) cleanGenres(st *State) error { //nolint:unparam
start := time.Now() start := time.Now()
defer func() { log.Printf("finished clean genres in %s, %d removed", durSince(start), c.GenresMissing()) }() defer func() { log.Printf("finished clean genres in %s, %d removed", durSince(start), st.GenresMissing()) }()
subTrack := s.db. subTrack := s.db.
Select("genres.id"). Select("genres.id").
Model(&db.Genre{}). Model(db.Genre{}).
Joins("LEFT JOIN track_genres ON track_genres.genre_id=genres.id"). Joins("LEFT JOIN track_genres ON track_genres.genre_id=genres.id").
Where("track_genres.genre_id IS NULL"). Where("track_genres.genre_id IS NULL").
SubQuery() SubQuery()
subAlbum := s.db. subAlbum := s.db.
Select("genres.id"). Select("genres.id").
Model(&db.Genre{}). Model(db.Genre{}).
Joins("LEFT JOIN album_genres ON album_genres.genre_id=genres.id"). Joins("LEFT JOIN album_genres ON album_genres.genre_id=genres.id").
Where("album_genres.genre_id IS NULL"). Where("album_genres.genre_id IS NULL").
SubQuery() SubQuery()
q := s.db. q := s.db.
Where("genres.id IN ? AND genres.id IN ?", subTrack, subAlbum). Where("genres.id IN ? AND genres.id IN ?", subTrack, subAlbum).
Delete(&db.Genre{}) Delete(db.Genre{})
c.genresMissing = int(q.RowsAffected) st.genresMissing += int(q.RowsAffected)
subAlbumGenresNoTracks := s.db.
Select("album_genres.genre_id").
Model(db.AlbumGenre{}).
Joins("JOIN albums ON albums.id=album_genres.album_id").
Joins("LEFT JOIN tracks ON tracks.album_id=albums.id").
Group("album_genres.genre_id").
Having("count(tracks.id)=0").
SubQuery()
q = s.db.
Where("genres.id IN ?", subAlbumGenresNoTracks).
Delete(db.Genre{})
st.genresMissing += int(q.RowsAffected)
return nil return nil
} }
@@ -663,7 +675,7 @@ func durSince(t time.Time) time.Duration {
return time.Since(t).Truncate(10 * time.Microsecond) return time.Since(t).Truncate(10 * time.Microsecond)
} }
type Context struct { type State struct {
errs []error errs []error
isFull bool isFull bool
@@ -677,14 +689,14 @@ type Context struct {
genresMissing int genresMissing int
} }
func (c *Context) SeenTracks() int { return len(c.seenTracks) } func (s *State) SeenTracks() int { return len(s.seenTracks) }
func (c *Context) SeenAlbums() int { return len(c.seenAlbums) } func (s *State) SeenAlbums() int { return len(s.seenAlbums) }
func (c *Context) SeenTracksNew() int { return c.seenTracksNew } func (s *State) SeenTracksNew() int { return s.seenTracksNew }
func (c *Context) TracksMissing() int { return len(c.tracksMissing) } func (s *State) TracksMissing() int { return len(s.tracksMissing) }
func (c *Context) AlbumsMissing() int { return len(c.albumsMissing) } func (s *State) AlbumsMissing() int { return len(s.albumsMissing) }
func (c *Context) ArtistsMissing() int { return c.artistsMissing } func (s *State) ArtistsMissing() int { return s.artistsMissing }
func (c *Context) GenresMissing() int { return c.genresMissing } func (s *State) GenresMissing() int { return s.genresMissing }
type MultiValueMode uint8 type MultiValueMode uint8
@@ -707,28 +719,39 @@ type MultiValueSetting struct {
Delim string Delim string
} }
func parseMulti(parser tagcommon.Info, setting MultiValueSetting, getMulti func(tagcommon.Info) []string, get func(tagcommon.Info) string) []string { func ParseMulti(setting MultiValueSetting, values []string, value string) []string {
var parts []string var parts []string
switch setting.Mode { switch setting.Mode {
case Multi: case Multi:
parts = getMulti(parser) parts = values
case Delim: case Delim:
parts = strings.Split(get(parser), setting.Delim) parts = strings.Split(value, setting.Delim)
default: default:
parts = []string{get(parser)} parts = []string{value}
} }
for i := range parts { for i := range parts {
parts[i] = strings.TrimSpace(parts[i]) parts[i] = strings.TrimSpace(parts[i])
} }
parts = slices.DeleteFunc(parts, func(s string) bool {
return s == ""
})
return parts return parts
} }
func musicDirRelative(musicDirs []string, absPath string) (musicDir, relPath string) { func musicDirRelative(musicDirs []string, absPath string) (musicDir, relPath string) {
for _, musicDir := range musicDirs { for _, musicDir := range musicDirs {
if strings.HasPrefix(absPath, musicDir) { if fileutil.HasPrefix(absPath, musicDir) {
relPath, _ = filepath.Rel(musicDir, absPath) relPath, _ = filepath.Rel(musicDir, absPath)
return musicDir, relPath return musicDir, relPath
} }
} }
return return
} }
func symWalk(absPath string, fn fs.WalkDirFunc) error {
eval, _ := filepath.EvalSymlinks(absPath)
return filepath.WalkDir(eval, func(subAbs string, d fs.DirEntry, err error) error {
subAbs = strings.Replace(subAbs, eval, absPath, 1)
return fn(subAbs, d, err)
})
}
+7 -7
View File
@@ -16,13 +16,13 @@ import (
func FuzzScanner(f *testing.F) { func FuzzScanner(f *testing.F) {
checkDelta := func(assert *assert.Assertions, m *mockfs.MockFS, expSeen, expNew int) { checkDelta := func(assert *assert.Assertions, m *mockfs.MockFS, expSeen, expNew int) {
ctx := m.ScanAndClean() st := m.ScanAndClean()
assert.Equal(ctx.SeenTracks(), expSeen) assert.Equal(st.SeenTracks(), expSeen)
assert.Equal(ctx.SeenTracksNew(), expNew) assert.Equal(st.SeenTracksNew(), expNew)
assert.Equal(ctx.TracksMissing(), 0) assert.Equal(st.TracksMissing(), 0)
assert.Equal(ctx.AlbumsMissing(), 0) assert.Equal(st.AlbumsMissing(), 0)
assert.Equal(ctx.ArtistsMissing(), 0) assert.Equal(st.ArtistsMissing(), 0)
assert.Equal(ctx.GenresMissing(), 0) assert.Equal(st.GenresMissing(), 0)
} }
f.Fuzz(func(t *testing.T, data []byte, seed int64) { f.Fuzz(func(t *testing.T, data []byte, seed int64) {
+82 -8
View File
@@ -524,22 +524,22 @@ func TestTagErrors(t *testing.T) {
tags.Error = scanner.ErrReadingTags tags.Error = scanner.ErrReadingTags
}) })
ctx, err := m.ScanAndCleanErr() st, err := m.ScanAndCleanErr()
errs, ok := err.(interface{ Unwrap() []error }) errs, ok := err.(interface{ Unwrap() []error })
assert.True(t, ok) assert.True(t, ok)
assert.ErrorAs(t, err, &errs) assert.ErrorAs(t, err, &errs)
assert.Equal(t, 2, len(errs.Unwrap())) // we have 2 dir errors assert.Equal(t, 2, len(errs.Unwrap())) // we have 2 dir errors
assert.Equal(t, m.NumTracks()-(3*2), ctx.SeenTracks()) // we saw all tracks bar 2 album contents assert.Equal(t, m.NumTracks()-(3*2), st.SeenTracks()) // we saw all tracks bar 2 album contents
assert.Equal(t, m.NumTracks()-(3*2), ctx.SeenTracksNew()) // we have all tracks bar 2 album contents assert.Equal(t, m.NumTracks()-(3*2), st.SeenTracksNew()) // we have all tracks bar 2 album contents
ctx, err = m.ScanAndCleanErr() st, err = m.ScanAndCleanErr()
errs, ok = err.(interface{ Unwrap() []error }) errs, ok = err.(interface{ Unwrap() []error })
assert.True(t, ok) assert.True(t, ok)
assert.Equal(t, 2, len(errs.Unwrap())) // we have 2 dir errors assert.Equal(t, 2, len(errs.Unwrap())) // we have 2 dir errors
assert.Equal(t, m.NumTracks()-(3*2), ctx.SeenTracks()) // we saw all tracks bar 2 album contents assert.Equal(t, m.NumTracks()-(3*2), st.SeenTracks()) // we saw all tracks bar 2 album contents
assert.Equal(t, 0, ctx.SeenTracksNew()) // we have no new tracks assert.Equal(t, 0, st.SeenTracksNew()) // we have no new tracks
} }
// https://github.com/sentriz/gonic/issues/185#issuecomment-1050092128 // https://github.com/sentriz/gonic/issues/185#issuecomment-1050092128
@@ -643,6 +643,41 @@ func TestNoOrphanedGenres(t *testing.T) {
assert.Equal(t, 0, genreCount) assert.Equal(t, 0, genreCount)
} }
// https://github.com/sentriz/gonic/issues/466
func TestNoOrphanedGenresButOnlyDeleteTracks(t *testing.T) {
t.Parallel()
m := mockfs.New(t)
m.AddItems()
m.SetTags("artist-0/album-0/track-0.flac", func(tags *mockfs.TagInfo) { tags.RawGenre = "genre-a" })
m.ScanAndClean()
trackPaths, err := filepath.Glob(filepath.Join(m.TmpDir(), "*", "*", "*.flac"))
assert.NoError(t, err)
for _, path := range trackPaths {
assert.NoError(t, os.Remove(path))
}
m.ScanAndClean()
var tracks []*db.Track
assert.NoError(t, m.DB().Find(&tracks).Error)
assert.Len(t, tracks, 0)
var genres []*db.Genre
assert.NoError(t, m.DB().Find(&genres).Error)
assert.Len(t, genres, 0)
var trackGenres []*db.TrackGenre
assert.NoError(t, m.DB().Find(&trackGenres).Error)
assert.Len(t, trackGenres, 0)
var albumGenres []*db.AlbumGenre
assert.NoError(t, m.DB().Find(&albumGenres).Error)
assert.Len(t, albumGenres, 0)
}
func TestMultiArtistSupport(t *testing.T) { func TestMultiArtistSupport(t *testing.T) {
t.Parallel() t.Parallel()
m := mockfs.New(t) m := mockfs.New(t)
@@ -787,3 +822,42 @@ func TestRootNoClobberOnError(t *testing.T) {
require.Equal(t, ".", roots[0].RightPath) require.Equal(t, ".", roots[0].RightPath)
require.Equal(t, 0, roots[0].ParentID) require.Equal(t, 0, roots[0].ParentID)
} }
// https://github.com/sentriz/gonic/issues/437
func TestPrefixOverlap(t *testing.T) {
t.Parallel()
m := mockfs.NewWithDirs(t, []string{
"/music/tagged",
"/music/taggedmanual",
})
m.AddItemsPrefix("/music/tagged")
m.AddItemsPrefix("/music/taggedmanual")
m.ScanAndClean()
var taggedManual int
require.NoError(t, m.DB().Model(db.Album{}).Where("root_dir LIKE ?", `%/taggedmanual`).Count(&taggedManual).Error)
require.Greater(t, taggedManual, 1)
var tagged int
require.NoError(t, m.DB().Model(db.Album{}).Where("root_dir LIKE ?", `%/tagged`).Count(&tagged).Error)
require.Greater(t, tagged, 1)
}
// https://github.com/sentriz/gonic/pull/448
func TestParseMultiDoubleDelim(t *testing.T) {
t.Parallel()
setting := scanner.MultiValueSetting{
Mode: scanner.Delim,
Delim: `/`,
}
values := scanner.ParseMulti(setting, nil, `DON'T//BE//⚜⚜⚜`)
require.Len(t, values, 3)
require.Equal(t, `DON'T`, values[0])
require.Equal(t, `BE`, values[1])
require.Equal(t, `⚜⚜⚜`, values[2])
}
+8 -7
View File
@@ -7,13 +7,14 @@ import (
) )
type Track struct { type Track struct {
Track string Track string
Artist string Artist string
Album string Album string
AlbumArtist string AlbumArtist string
TrackNumber uint TrackNumber uint
Duration time.Duration Duration time.Duration
MusicBrainzID string MusicBrainzID string
MusicBrainzReleaseID string
} }
type Scrobbler interface { type Scrobbler interface {
+2 -2
View File
@@ -60,8 +60,8 @@
{{ end }} {{ end }}
{{ range $folder := .RecentFolders }} {{ range $folder := .RecentFolders }}
<div class="text-left ellipsis">{{ $folder.RightPath }}</div> <div class="text-left ellipsis">{{ $folder.RightPath }}</div>
{{ if not $folder.ModifiedAt.IsZero }} {{ if not $folder.CreatedAt.IsZero }}
<div class="text-gray-500" title="{{ $folder.ModifiedAt }}">{{ $folder.ModifiedAt | dateHuman }}</div> <div class="text-gray-500" title="{{ $folder.CreatedAt }}">{{ $folder.CreatedAt | dateHuman }}</div>
{{ else }} {{ else }}
<span></span> <span></span>
{{ end }} {{ end }}
+1 -1
View File
@@ -113,7 +113,7 @@ func New(dbc *db.DB, scannr *scanner.Scanner, musicPaths []MusicPath, podcastsPa
c.Handle("/getUser", chain(resp(c.ServeGetUser))) c.Handle("/getUser", chain(resp(c.ServeGetUser)))
c.Handle("/getPlaylists", chain(resp(c.ServeGetPlaylists))) c.Handle("/getPlaylists", chain(resp(c.ServeGetPlaylists)))
c.Handle("/getPlaylist", chain(resp(c.ServeGetPlaylist))) c.Handle("/getPlaylist", chain(resp(c.ServeGetPlaylist)))
c.Handle("/createPlaylist", chain(resp(c.ServeCreatePlaylist))) c.Handle("/createPlaylist", chain(resp(c.ServeCreateOrUpdatePlaylist)))
c.Handle("/updatePlaylist", chain(resp(c.ServeUpdatePlaylist))) c.Handle("/updatePlaylist", chain(resp(c.ServeUpdatePlaylist)))
c.Handle("/deletePlaylist", chain(resp(c.ServeDeletePlaylist))) c.Handle("/deletePlaylist", chain(resp(c.ServeDeletePlaylist)))
c.Handle("/savePlayQueue", chain(resp(c.ServeSavePlayQueue))) c.Handle("/savePlayQueue", chain(resp(c.ServeSavePlayQueue)))
+2 -1
View File
@@ -222,7 +222,8 @@ func (c *Controller) ServeSearchTwo(r *http.Request) *spec.Response {
for _, s := range queries { for _, s := range queries {
q = q.Where(`right_path LIKE ? OR right_path_u_dec LIKE ?`, s, s) q = q.Where(`right_path LIKE ? OR right_path_u_dec LIKE ?`, s, s)
} }
q = q.Preload("AlbumStar", "user_id=?", user.ID). q = q.
Preload("AlbumStar", "user_id=?", user.ID).
Preload("AlbumRating", "user_id=?", user.ID). Preload("AlbumRating", "user_id=?", user.ID).
Offset(params.GetOrInt("artistOffset", 0)). Offset(params.GetOrInt("artistOffset", 0)).
Limit(params.GetOrInt("artistCount", 20)) Limit(params.GetOrInt("artistCount", 20))
+17 -7
View File
@@ -11,6 +11,7 @@ import (
"strings" "strings"
"time" "time"
"github.com/google/uuid"
"github.com/jinzhu/gorm" "github.com/jinzhu/gorm"
"go.senan.xyz/gonic/db" "go.senan.xyz/gonic/db"
@@ -116,10 +117,12 @@ func (c *Controller) ServeGetAlbum(r *http.Request) *spec.Response {
}). }).
Preload("AlbumStar", "user_id=?", user.ID). Preload("AlbumStar", "user_id=?", user.ID).
Preload("AlbumRating", "user_id=?", user.ID). Preload("AlbumRating", "user_id=?", user.ID).
Preload("AlbumRating", "user_id=?", user.ID).
Preload("Play", "user_id=?", user.ID).
First(album, id.Value). First(album, id.Value).
Error Error
if errors.Is(err, gorm.ErrRecordNotFound) { if errors.Is(err, gorm.ErrRecordNotFound) {
return spec.NewError(10, "couldn't find an album with that id") return spec.NewError(70, "couldn't find an album with that id")
} }
sub := spec.NewResponse() sub := spec.NewResponse()
sub.Album = spec.NewAlbumByTags(album, album.Artists) sub.Album = spec.NewAlbumByTags(album, album.Artists)
@@ -198,6 +201,7 @@ func (c *Controller) ServeGetAlbumListTwo(r *http.Request) *spec.Response {
Preload("Artists"). Preload("Artists").
Preload("AlbumStar", "user_id=?", user.ID). Preload("AlbumStar", "user_id=?", user.ID).
Preload("AlbumRating", "user_id=?", user.ID). Preload("AlbumRating", "user_id=?", user.ID).
Preload("Play", "user_id=?", user.ID).
Find(&albums) Find(&albums)
sub := spec.NewResponse() sub := spec.NewResponse()
sub.AlbumsTwo = &spec.Albums{ sub.AlbumsTwo = &spec.Albums{
@@ -255,7 +259,8 @@ func (c *Controller) ServeSearchThree(r *http.Request) *spec.Response {
Preload("Artists"). Preload("Artists").
Preload("Genres"). Preload("Genres").
Preload("AlbumStar", "user_id=?", user.ID). Preload("AlbumStar", "user_id=?", user.ID).
Preload("AlbumRating", "user_id=?", user.ID) Preload("AlbumRating", "user_id=?", user.ID).
Preload("Play", "user_id=?", user.ID)
for _, s := range queries { for _, s := range queries {
q = q.Where(`tag_title LIKE ? OR tag_title_u_dec LIKE ?`, s, s) q = q.Where(`tag_title LIKE ? OR tag_title_u_dec LIKE ?`, s, s)
} }
@@ -333,7 +338,7 @@ func (c *Controller) ServeGetArtistInfoTwo(r *http.Request) *spec.Response {
return sub return sub
} }
sub.ArtistInfoTwo.Biography = info.Biography sub.ArtistInfoTwo.Biography = spec.CleanExternalText(info.Biography)
sub.ArtistInfoTwo.MusicBrainzID = info.MusicBrainzID sub.ArtistInfoTwo.MusicBrainzID = info.MusicBrainzID
sub.ArtistInfoTwo.LastFMURL = info.LastFMURL sub.ArtistInfoTwo.LastFMURL = info.LastFMURL
@@ -409,10 +414,14 @@ func (c *Controller) ServeGetAlbumInfoTwo(r *http.Request) *spec.Response {
return sub return sub
} }
sub.AlbumInfo.Notes = info.Notes sub.AlbumInfo.Notes = spec.CleanExternalText(info.Notes)
sub.AlbumInfo.MusicBrainzID = info.MusicBrainzID sub.AlbumInfo.MusicBrainzID = info.MusicBrainzID
sub.AlbumInfo.LastFMURL = info.LastFMURL sub.AlbumInfo.LastFMURL = info.LastFMURL
if _, err := uuid.Parse(album.TagBrainzID); err == nil {
sub.AlbumInfo.MusicBrainzID = album.TagBrainzID // prefer db musicbrainz ID over lastfm's
}
return sub return sub
} }
@@ -512,7 +521,8 @@ func (c *Controller) ServeGetStarredTwo(r *http.Request) *spec.Response {
Order("album_stars.star_date DESC"). Order("album_stars.star_date DESC").
Preload("Artists"). Preload("Artists").
Preload("AlbumStar", "user_id=?", user.ID). Preload("AlbumStar", "user_id=?", user.ID).
Preload("AlbumRating", "user_id=?", user.ID) Preload("AlbumRating", "user_id=?", user.ID).
Preload("Play", "user_id=?", user.ID)
if m := getMusicFolder(c.musicPaths, params); m != "" { if m := getMusicFolder(c.musicPaths, params); m != "" {
q = q.Where("albums.root_dir=?", m) q = q.Where("albums.root_dir=?", m)
} }
@@ -644,7 +654,7 @@ func (c *Controller) ServeGetSimilarSongs(r *http.Request) *spec.Response {
First(&track). First(&track).
Error Error
if errors.Is(err, gorm.ErrRecordNotFound) { if errors.Is(err, gorm.ErrRecordNotFound) {
return spec.NewError(10, "couldn't find a track with that id") return spec.NewError(70, "couldn't find a track with that id")
} }
similarTracks, err := c.lastFMClient.TrackGetSimilarTracks(track.TagTrackArtist, track.TagTitle) similarTracks, err := c.lastFMClient.TrackGetSimilarTracks(track.TagTrackArtist, track.TagTitle)
@@ -710,7 +720,7 @@ func (c *Controller) ServeGetSimilarSongsTwo(r *http.Request) *spec.Response {
First(&artist). First(&artist).
Error Error
if errors.Is(err, gorm.ErrRecordNotFound) { if errors.Is(err, gorm.ErrRecordNotFound) {
return spec.NewError(0, "artist with id %q not found", id) return spec.NewError(70, "artist with id %q not found", id)
} }
similarArtists, err := c.lastFMClient.ArtistGetSimilar(artist.Name) similarArtists, err := c.lastFMClient.ArtistGetSimilar(artist.Name)
+9 -2
View File
@@ -78,6 +78,9 @@ func (c *Controller) ServeScrobble(r *http.Request) *spec.Response {
if _, err := uuid.Parse(track.TagBrainzID); err == nil { if _, err := uuid.Parse(track.TagBrainzID); err == nil {
scrobbleTrack.MusicBrainzID = track.TagBrainzID scrobbleTrack.MusicBrainzID = track.TagBrainzID
} }
if _, err := uuid.Parse(track.Album.TagBrainzID); err == nil {
scrobbleTrack.MusicBrainzReleaseID = track.Album.TagBrainzID
}
if err := scrobbleStatsUpdateTrack(c.dbc, &track, user.ID, optStamp); err != nil { if err := scrobbleStatsUpdateTrack(c.dbc, &track, user.ID, optStamp); err != nil {
return spec.NewError(0, "error updating stats: %v", err) return spec.NewError(0, "error updating stats: %v", err)
@@ -275,7 +278,7 @@ func (c *Controller) ServeGetSong(r *http.Request) *spec.Response {
First(&track). First(&track).
Error Error
if errors.Is(err, gorm.ErrRecordNotFound) { if errors.Is(err, gorm.ErrRecordNotFound) {
return spec.NewError(10, "couldn't find a track with that id") return spec.NewError(70, "couldn't find a track with that id")
} }
transcodeMeta := streamGetTranscodeMeta(c.dbc, user.ID, params.GetOr("c", "")) transcodeMeta := streamGetTranscodeMeta(c.dbc, user.ID, params.GetOr("c", ""))
@@ -515,7 +518,11 @@ func getMusicFolder(musicPaths []MusicPath, p params.Params) string {
} }
func lowerUDecOrHash(in string) string { func lowerUDecOrHash(in string) string {
lower := unicode.ToLower(rune(in[0])) inRunes := []rune(in)
if len(inRunes) == 0 {
return ""
}
lower := unicode.ToLower(inRunes[0])
if !unicode.IsLetter(lower) { if !unicode.IsLetter(lower) {
return "#" return "#"
} }
+5 -3
View File
@@ -67,7 +67,7 @@ func (c *Controller) ServeGetPlaylist(r *http.Request) *spec.Response {
return sub return sub
} }
func (c *Controller) ServeCreatePlaylist(r *http.Request) *spec.Response { func (c *Controller) ServeCreateOrUpdatePlaylist(r *http.Request) *spec.Response {
user := r.Context().Value(CtxUser).(*db.User) user := r.Context().Value(CtxUser).(*db.User)
params := r.Context().Value(CtxParams).(params.Params) params := r.Context().Value(CtxParams).(params.Params)
@@ -79,9 +79,8 @@ func (c *Controller) ServeCreatePlaylist(r *http.Request) *spec.Response {
playlist = *pl playlist = *pl
} }
// update meta info
if playlist.UserID != 0 && playlist.UserID != user.ID { if playlist.UserID != 0 && playlist.UserID != user.ID {
return spec.NewResponse() return spec.NewError(50, "you aren't allowed update that user's playlist")
} }
playlist.UserID = user.ID playlist.UserID = user.ID
@@ -103,7 +102,9 @@ func (c *Controller) ServeCreatePlaylist(r *http.Request) *spec.Response {
if playlistPath == "" { if playlistPath == "" {
playlistPath = playlistp.NewPath(user.ID, fmt.Sprint(time.Now().UnixMilli())) playlistPath = playlistp.NewPath(user.ID, fmt.Sprint(time.Now().UnixMilli()))
playlistID = playlistIDEncode(playlistPath)
} }
if err := c.playlistStore.Write(playlistPath, &playlist); err != nil { if err := c.playlistStore.Write(playlistPath, &playlist); err != nil {
return spec.NewError(0, "save playlist: %v", err) return spec.NewError(0, "save playlist: %v", err)
} }
@@ -197,6 +198,7 @@ func playlistRender(c *Controller, params params.Params, playlistID string, play
Name: playlist.Name, Name: playlist.Name,
Comment: playlist.Comment, Comment: playlist.Comment,
Created: playlist.UpdatedAt, Created: playlist.UpdatedAt,
Changed: playlist.UpdatedAt,
SongCount: len(playlist.Items), SongCount: len(playlist.Items),
Public: playlist.IsPublic, Public: playlist.IsPublic,
Owner: user.Name, Owner: user.Name,
+12 -4
View File
@@ -188,16 +188,24 @@ func (c *Controller) ServeStream(w http.ResponseWriter, r *http.Request) *spec.R
format, _ := params.Get("format") format, _ := params.Get("format")
timeOffset, _ := params.GetInt("timeOffset") timeOffset, _ := params.GetInt("timeOffset")
if format == "raw" || maxBitRate >= audioFile.AudioBitrate() { if format == "raw" {
http.ServeFile(w, r, file.AbsPath()) http.ServeFile(w, r, file.AbsPath())
return nil return nil
} }
pref, err := streamGetTransodePreference(c.dbc, user.ID, params.GetOr("c", "")) client, _ := params.Get("c")
pref, err := streamGetTransodePreference(c.dbc, user.ID, client)
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
return spec.NewError(0, "couldn't find transcode preference: %v", err) return spec.NewError(0, "couldn't find transcode preference: %v", err)
} }
if pref == nil { if pref == nil {
log.Printf("serving raw file, no user transcode preferences found for user %q and client %q", user.Name, client)
http.ServeFile(w, r, file.AbsPath())
return nil
}
if maxBitRate >= audioFile.AudioBitrate() {
log.Printf("serving raw file, requested max bitrate %d is greater or equal to %d", maxBitRate, audioFile.AudioBitrate())
http.ServeFile(w, r, file.AbsPath()) http.ServeFile(w, r, file.AbsPath())
return nil return nil
} }
@@ -213,7 +221,7 @@ func (c *Controller) ServeStream(w http.ResponseWriter, r *http.Request) *spec.R
profile = transcode.WithSeek(profile, time.Second*time.Duration(timeOffset)) profile = transcode.WithSeek(profile, time.Second*time.Duration(timeOffset))
} }
log.Printf("trancoding to %q with max bitrate %dk", profile.MIME(), profile.BitRate()) log.Printf("trancoding to %q with at bitrate %d", profile.MIME(), profile.BitRate())
w.Header().Set("Content-Type", profile.MIME()) w.Header().Set("Content-Type", profile.MIME())
if err := c.transcoder.Transcode(r.Context(), profile, file.AbsPath(), w); err != nil && !errors.Is(err, transcode.ErrFFmpegKilled) { if err := c.transcoder.Transcode(r.Context(), profile, file.AbsPath(), w); err != nil && !errors.Is(err, transcode.ErrFFmpegKilled) {
@@ -234,7 +242,7 @@ func (c *Controller) ServeGetAvatar(w http.ResponseWriter, r *http.Request) *spe
return spec.NewError(10, "please provide an `username` parameter") return spec.NewError(10, "please provide an `username` parameter")
} }
reqUser := c.dbc.GetUserByName(username) reqUser := c.dbc.GetUserByName(username)
if (user != reqUser) && !user.IsAdmin { if (user.ID != reqUser.ID) && !user.IsAdmin {
return spec.NewError(50, "user not admin") return spec.NewError(50, "user not admin")
} }
http.ServeContent(w, r, "", time.Now(), bytes.NewReader(reqUser.Avatar)) http.ServeContent(w, r, "", time.Now(), bytes.NewReader(reqUser.Avatar))
@@ -51,6 +51,9 @@ func NewAlbumByTags(a *db.Album, artists []*db.Artist) *Album {
for _, g := range a.Genres { for _, g := range a.Genres {
ret.Genres = append(ret.Genres, &GenreRef{Name: g.Name}) ret.Genres = append(ret.Genres, &GenreRef{Name: g.Name})
} }
if a.Play != nil {
ret.PlayCount = a.Play.Count
}
return ret return ret
} }
+2 -11
View File
@@ -2,19 +2,14 @@ package spec
import ( import (
"go.senan.xyz/gonic/db" "go.senan.xyz/gonic/db"
"jaytaylor.com/html2text"
) )
func NewPodcastChannel(p *db.Podcast) *PodcastChannel { func NewPodcastChannel(p *db.Podcast) *PodcastChannel {
desc, err := html2text.FromString(p.Description, html2text.Options{TextOnly: true})
if err != nil {
desc = ""
}
ret := &PodcastChannel{ ret := &PodcastChannel{
ID: p.SID(), ID: p.SID(),
OriginalImageURL: p.ImageURL, OriginalImageURL: p.ImageURL,
Title: p.Title, Title: p.Title,
Description: desc, Description: CleanExternalText(p.Description),
URL: p.URL, URL: p.URL,
CoverArt: p.SID(), CoverArt: p.SID(),
Status: "skipped", Status: "skipped",
@@ -30,17 +25,13 @@ func NewPodcastEpisode(pe *db.PodcastEpisode) *PodcastEpisode {
if pe == nil { if pe == nil {
return nil return nil
} }
desc, err := html2text.FromString(pe.Description, html2text.Options{TextOnly: true})
if err != nil {
desc = ""
}
r := &PodcastEpisode{ r := &PodcastEpisode{
ID: pe.SID(), ID: pe.SID(),
StreamID: pe.SID(), StreamID: pe.SID(),
ContentType: pe.MIME(), ContentType: pe.MIME(),
ChannelID: pe.PodcastSID(), ChannelID: pe.PodcastSID(),
Title: pe.Title, Title: pe.Title,
Description: desc, Description: CleanExternalText(pe.Description),
Status: string(pe.Status), Status: string(pe.Status),
CoverArt: pe.PodcastSID(), CoverArt: pe.PodcastSID(),
PublishDate: *pe.PublishDate, PublishDate: *pe.PublishDate,
+20 -1
View File
@@ -2,11 +2,13 @@ package spec
import ( import (
"fmt" "fmt"
"regexp"
"strings" "strings"
"time" "time"
"go.senan.xyz/gonic" "go.senan.xyz/gonic"
"go.senan.xyz/gonic/server/ctrlsubsonic/specid" "go.senan.xyz/gonic/server/ctrlsubsonic/specid"
"jaytaylor.com/html2text"
) )
// https://web.archive.org/web/20220707025402/https://www.subsonic.org/pages/api.jsp // https://web.archive.org/web/20220707025402/https://www.subsonic.org/pages/api.jsp
@@ -142,6 +144,7 @@ type Album struct {
Name string `xml:"name,attr" json:"name"` Name string `xml:"name,attr" json:"name"`
TrackCount int `xml:"songCount,attr" json:"songCount"` TrackCount int `xml:"songCount,attr" json:"songCount"`
Duration int `xml:"duration,attr" json:"duration"` Duration int `xml:"duration,attr" json:"duration"`
PlayCount int `xml:"playCount,attr" json:"playCount"`
Genre string `xml:"genre,attr,omitempty" json:"genre,omitempty"` Genre string `xml:"genre,attr,omitempty" json:"genre,omitempty"`
Genres []*GenreRef `xml:"genres,omitempty" json:"genres,omitempty"` Genres []*GenreRef `xml:"genres,omitempty" json:"genres,omitempty"`
Year int `xml:"year,attr,omitempty" json:"year,omitempty"` Year int `xml:"year,attr,omitempty" json:"year,omitempty"`
@@ -308,7 +311,8 @@ type Playlist struct {
Owner string `xml:"owner,attr" json:"owner"` Owner string `xml:"owner,attr" json:"owner"`
SongCount int `xml:"songCount,attr" json:"songCount"` SongCount int `xml:"songCount,attr" json:"songCount"`
Created time.Time `xml:"created,attr" json:"created"` Created time.Time `xml:"created,attr" json:"created"`
Duration int `xml:"duration,attr" json:"duration,omitempty"` Changed time.Time `xml:"changed,attr" json:"changed"`
Duration int `xml:"duration,attr" json:"duration"`
Public bool `xml:"public,attr" json:"public,omitempty"` Public bool `xml:"public,attr" json:"public,omitempty"`
List []*TrackChild `xml:"entry,omitempty" json:"entry,omitempty"` List []*TrackChild `xml:"entry,omitempty" json:"entry,omitempty"`
} }
@@ -472,3 +476,18 @@ func formatRating(rating float64) string {
func formatExt(ext string) string { func formatExt(ext string) string {
return strings.TrimPrefix(ext, ".") return strings.TrimPrefix(ext, ".")
} }
var doublePuncExpr = regexp.MustCompile(`\.\s+\.\s+`)
var licenceExpr = regexp.MustCompile(`(?i)\buser-contributed text.*`)
var readMoreExpr = regexp.MustCompile(`(?i)\bread more on.*`)
func CleanExternalText(text string) string {
text, _ = html2text.FromString(text, html2text.Options{TextOnly: true})
text = licenceExpr.ReplaceAllString(text, "")
text = readMoreExpr.ReplaceAllString(text, "")
text = doublePuncExpr.ReplaceAllString(text, ". ")
text = strings.ReplaceAll(text, " .", ".")
text = strings.Join(strings.Fields(text), " ")
text = strings.TrimSpace(text)
return text
}
@@ -6,6 +6,7 @@ import (
"strings" "strings"
"go.senan.xyz/gonic/db" "go.senan.xyz/gonic/db"
"go.senan.xyz/gonic/fileutil"
"go.senan.xyz/gonic/server/ctrlsubsonic/specid" "go.senan.xyz/gonic/server/ctrlsubsonic/specid"
) )
@@ -54,8 +55,9 @@ func Lookup(dbc *db.DB, musicPaths []string, podcastsPath string, path string) (
var musicPath string var musicPath string
for _, mp := range musicPaths { for _, mp := range musicPaths {
if strings.HasPrefix(path, mp) { if fileutil.HasPrefix(path, mp) {
musicPath = mp musicPath = mp
break
} }
} }
if musicPath == "" { if musicPath == "" {
@@ -20,7 +20,8 @@
"coverArt": "al-3", "coverArt": "al-3",
"name": "album-0", "name": "album-0",
"songCount": 3, "songCount": 3,
"duration": 300 "duration": 300,
"playCount": 0
}, },
{ {
"id": "al-4", "id": "al-4",
@@ -35,7 +36,8 @@
"coverArt": "al-4", "coverArt": "al-4",
"name": "album-1", "name": "album-1",
"songCount": 3, "songCount": 3,
"duration": 300 "duration": 300,
"playCount": 0
}, },
{ {
"id": "al-5", "id": "al-5",
@@ -50,7 +52,8 @@
"coverArt": "al-5", "coverArt": "al-5",
"name": "album-2", "name": "album-2",
"songCount": 3, "songCount": 3,
"duration": 300 "duration": 300,
"playCount": 0
}, },
{ {
"id": "al-7", "id": "al-7",
@@ -65,7 +68,8 @@
"coverArt": "al-7", "coverArt": "al-7",
"name": "album-0", "name": "album-0",
"songCount": 3, "songCount": 3,
"duration": 300 "duration": 300,
"playCount": 0
}, },
{ {
"id": "al-8", "id": "al-8",
@@ -80,7 +84,8 @@
"coverArt": "al-8", "coverArt": "al-8",
"name": "album-1", "name": "album-1",
"songCount": 3, "songCount": 3,
"duration": 300 "duration": 300,
"playCount": 0
}, },
{ {
"id": "al-9", "id": "al-9",
@@ -95,7 +100,8 @@
"coverArt": "al-9", "coverArt": "al-9",
"name": "album-2", "name": "album-2",
"songCount": 3, "songCount": 3,
"duration": 300 "duration": 300,
"playCount": 0
}, },
{ {
"id": "al-11", "id": "al-11",
@@ -110,7 +116,8 @@
"coverArt": "al-11", "coverArt": "al-11",
"name": "album-0", "name": "album-0",
"songCount": 3, "songCount": 3,
"duration": 300 "duration": 300,
"playCount": 0
}, },
{ {
"id": "al-12", "id": "al-12",
@@ -125,7 +132,8 @@
"coverArt": "al-12", "coverArt": "al-12",
"name": "album-1", "name": "album-1",
"songCount": 3, "songCount": 3,
"duration": 300 "duration": 300,
"playCount": 0
}, },
{ {
"id": "al-13", "id": "al-13",
@@ -140,7 +148,8 @@
"coverArt": "al-13", "coverArt": "al-13",
"name": "album-2", "name": "album-2",
"songCount": 3, "songCount": 3,
"duration": 300 "duration": 300,
"playCount": 0
} }
] ]
} }
+18 -9
View File
@@ -20,7 +20,8 @@
"coverArt": "al-3", "coverArt": "al-3",
"name": "album-0", "name": "album-0",
"songCount": 3, "songCount": 3,
"duration": 300 "duration": 300,
"playCount": 0
}, },
{ {
"id": "al-7", "id": "al-7",
@@ -35,7 +36,8 @@
"coverArt": "al-7", "coverArt": "al-7",
"name": "album-0", "name": "album-0",
"songCount": 3, "songCount": 3,
"duration": 300 "duration": 300,
"playCount": 0
}, },
{ {
"id": "al-11", "id": "al-11",
@@ -50,7 +52,8 @@
"coverArt": "al-11", "coverArt": "al-11",
"name": "album-0", "name": "album-0",
"songCount": 3, "songCount": 3,
"duration": 300 "duration": 300,
"playCount": 0
}, },
{ {
"id": "al-4", "id": "al-4",
@@ -65,7 +68,8 @@
"coverArt": "al-4", "coverArt": "al-4",
"name": "album-1", "name": "album-1",
"songCount": 3, "songCount": 3,
"duration": 300 "duration": 300,
"playCount": 0
}, },
{ {
"id": "al-8", "id": "al-8",
@@ -80,7 +84,8 @@
"coverArt": "al-8", "coverArt": "al-8",
"name": "album-1", "name": "album-1",
"songCount": 3, "songCount": 3,
"duration": 300 "duration": 300,
"playCount": 0
}, },
{ {
"id": "al-12", "id": "al-12",
@@ -95,7 +100,8 @@
"coverArt": "al-12", "coverArt": "al-12",
"name": "album-1", "name": "album-1",
"songCount": 3, "songCount": 3,
"duration": 300 "duration": 300,
"playCount": 0
}, },
{ {
"id": "al-5", "id": "al-5",
@@ -110,7 +116,8 @@
"coverArt": "al-5", "coverArt": "al-5",
"name": "album-2", "name": "album-2",
"songCount": 3, "songCount": 3,
"duration": 300 "duration": 300,
"playCount": 0
}, },
{ {
"id": "al-9", "id": "al-9",
@@ -125,7 +132,8 @@
"coverArt": "al-9", "coverArt": "al-9",
"name": "album-2", "name": "album-2",
"songCount": 3, "songCount": 3,
"duration": 300 "duration": 300,
"playCount": 0
}, },
{ {
"id": "al-13", "id": "al-13",
@@ -140,7 +148,8 @@
"coverArt": "al-13", "coverArt": "al-13",
"name": "album-2", "name": "album-2",
"songCount": 3, "songCount": 3,
"duration": 300 "duration": 300,
"playCount": 0
} }
] ]
} }
+18 -9
View File
@@ -20,7 +20,8 @@
"coverArt": "al-3", "coverArt": "al-3",
"name": "album-0", "name": "album-0",
"songCount": 3, "songCount": 3,
"duration": 300 "duration": 300,
"playCount": 0
}, },
{ {
"id": "al-4", "id": "al-4",
@@ -35,7 +36,8 @@
"coverArt": "al-4", "coverArt": "al-4",
"name": "album-1", "name": "album-1",
"songCount": 3, "songCount": 3,
"duration": 300 "duration": 300,
"playCount": 0
}, },
{ {
"id": "al-5", "id": "al-5",
@@ -50,7 +52,8 @@
"coverArt": "al-5", "coverArt": "al-5",
"name": "album-2", "name": "album-2",
"songCount": 3, "songCount": 3,
"duration": 300 "duration": 300,
"playCount": 0
}, },
{ {
"id": "al-7", "id": "al-7",
@@ -65,7 +68,8 @@
"coverArt": "al-7", "coverArt": "al-7",
"name": "album-0", "name": "album-0",
"songCount": 3, "songCount": 3,
"duration": 300 "duration": 300,
"playCount": 0
}, },
{ {
"id": "al-8", "id": "al-8",
@@ -80,7 +84,8 @@
"coverArt": "al-8", "coverArt": "al-8",
"name": "album-1", "name": "album-1",
"songCount": 3, "songCount": 3,
"duration": 300 "duration": 300,
"playCount": 0
}, },
{ {
"id": "al-9", "id": "al-9",
@@ -95,7 +100,8 @@
"coverArt": "al-9", "coverArt": "al-9",
"name": "album-2", "name": "album-2",
"songCount": 3, "songCount": 3,
"duration": 300 "duration": 300,
"playCount": 0
}, },
{ {
"id": "al-11", "id": "al-11",
@@ -110,7 +116,8 @@
"coverArt": "al-11", "coverArt": "al-11",
"name": "album-0", "name": "album-0",
"songCount": 3, "songCount": 3,
"duration": 300 "duration": 300,
"playCount": 0
}, },
{ {
"id": "al-12", "id": "al-12",
@@ -125,7 +132,8 @@
"coverArt": "al-12", "coverArt": "al-12",
"name": "album-1", "name": "album-1",
"songCount": 3, "songCount": 3,
"duration": 300 "duration": 300,
"playCount": 0
}, },
{ {
"id": "al-13", "id": "al-13",
@@ -140,7 +148,8 @@
"coverArt": "al-13", "coverArt": "al-13",
"name": "album-2", "name": "album-2",
"songCount": 3, "songCount": 3,
"duration": 300 "duration": 300,
"playCount": 0
} }
] ]
} }
+116 -107
View File
@@ -7,51 +7,6 @@
"openSubsonic": true, "openSubsonic": true,
"albumList": { "albumList": {
"album": [ "album": [
{
"id": "al-12",
"created": "2019-11-30T00:00:00Z",
"artist": "artist-2",
"artists": null,
"displayArtist": "",
"title": "album-1",
"album": "album-1",
"parent": "al-10",
"isDir": true,
"coverArt": "al-12",
"name": "album-1",
"songCount": 3,
"duration": 300
},
{
"id": "al-8",
"created": "2019-11-30T00:00:00Z",
"artist": "artist-1",
"artists": null,
"displayArtist": "",
"title": "album-1",
"album": "album-1",
"parent": "al-6",
"isDir": true,
"coverArt": "al-8",
"name": "album-1",
"songCount": 3,
"duration": 300
},
{
"id": "al-3",
"created": "2019-11-30T00:00:00Z",
"artist": "artist-0",
"artists": null,
"displayArtist": "",
"title": "album-0",
"album": "album-0",
"parent": "al-2",
"isDir": true,
"coverArt": "al-3",
"name": "album-0",
"songCount": 3,
"duration": 300
},
{ {
"id": "al-9", "id": "al-9",
"created": "2019-11-30T00:00:00Z", "created": "2019-11-30T00:00:00Z",
@@ -65,67 +20,8 @@
"coverArt": "al-9", "coverArt": "al-9",
"name": "album-2", "name": "album-2",
"songCount": 3, "songCount": 3,
"duration": 300 "duration": 300,
}, "playCount": 0
{
"id": "al-4",
"created": "2019-11-30T00:00:00Z",
"artist": "artist-0",
"artists": null,
"displayArtist": "",
"title": "album-1",
"album": "album-1",
"parent": "al-2",
"isDir": true,
"coverArt": "al-4",
"name": "album-1",
"songCount": 3,
"duration": 300
},
{
"id": "al-5",
"created": "2019-11-30T00:00:00Z",
"artist": "artist-0",
"artists": null,
"displayArtist": "",
"title": "album-2",
"album": "album-2",
"parent": "al-2",
"isDir": true,
"coverArt": "al-5",
"name": "album-2",
"songCount": 3,
"duration": 300
},
{
"id": "al-13",
"created": "2019-11-30T00:00:00Z",
"artist": "artist-2",
"artists": null,
"displayArtist": "",
"title": "album-2",
"album": "album-2",
"parent": "al-10",
"isDir": true,
"coverArt": "al-13",
"name": "album-2",
"songCount": 3,
"duration": 300
},
{
"id": "al-11",
"created": "2019-11-30T00:00:00Z",
"artist": "artist-2",
"artists": null,
"displayArtist": "",
"title": "album-0",
"album": "album-0",
"parent": "al-10",
"isDir": true,
"coverArt": "al-11",
"name": "album-0",
"songCount": 3,
"duration": 300
}, },
{ {
"id": "al-7", "id": "al-7",
@@ -140,7 +36,120 @@
"coverArt": "al-7", "coverArt": "al-7",
"name": "album-0", "name": "album-0",
"songCount": 3, "songCount": 3,
"duration": 300 "duration": 300,
"playCount": 0
},
{
"id": "al-4",
"created": "2019-11-30T00:00:00Z",
"artist": "artist-0",
"artists": null,
"displayArtist": "",
"title": "album-1",
"album": "album-1",
"parent": "al-2",
"isDir": true,
"coverArt": "al-4",
"name": "album-1",
"songCount": 3,
"duration": 300,
"playCount": 0
},
{
"id": "al-12",
"created": "2019-11-30T00:00:00Z",
"artist": "artist-2",
"artists": null,
"displayArtist": "",
"title": "album-1",
"album": "album-1",
"parent": "al-10",
"isDir": true,
"coverArt": "al-12",
"name": "album-1",
"songCount": 3,
"duration": 300,
"playCount": 0
},
{
"id": "al-5",
"created": "2019-11-30T00:00:00Z",
"artist": "artist-0",
"artists": null,
"displayArtist": "",
"title": "album-2",
"album": "album-2",
"parent": "al-2",
"isDir": true,
"coverArt": "al-5",
"name": "album-2",
"songCount": 3,
"duration": 300,
"playCount": 0
},
{
"id": "al-3",
"created": "2019-11-30T00:00:00Z",
"artist": "artist-0",
"artists": null,
"displayArtist": "",
"title": "album-0",
"album": "album-0",
"parent": "al-2",
"isDir": true,
"coverArt": "al-3",
"name": "album-0",
"songCount": 3,
"duration": 300,
"playCount": 0
},
{
"id": "al-8",
"created": "2019-11-30T00:00:00Z",
"artist": "artist-1",
"artists": null,
"displayArtist": "",
"title": "album-1",
"album": "album-1",
"parent": "al-6",
"isDir": true,
"coverArt": "al-8",
"name": "album-1",
"songCount": 3,
"duration": 300,
"playCount": 0
},
{
"id": "al-13",
"created": "2019-11-30T00:00:00Z",
"artist": "artist-2",
"artists": null,
"displayArtist": "",
"title": "album-2",
"album": "album-2",
"parent": "al-10",
"isDir": true,
"coverArt": "al-13",
"name": "album-2",
"songCount": 3,
"duration": 300,
"playCount": 0
},
{
"id": "al-11",
"created": "2019-11-30T00:00:00Z",
"artist": "artist-2",
"artists": null,
"displayArtist": "",
"title": "album-0",
"album": "album-0",
"parent": "al-10",
"isDir": true,
"coverArt": "al-11",
"name": "album-0",
"songCount": 3,
"duration": 300,
"playCount": 0
} }
] ]
} }
@@ -20,6 +20,7 @@
"name": "album-0", "name": "album-0",
"songCount": 3, "songCount": 3,
"duration": 300, "duration": 300,
"playCount": 0,
"year": 2021 "year": 2021
}, },
{ {
@@ -35,6 +36,7 @@
"name": "album-1", "name": "album-1",
"songCount": 3, "songCount": 3,
"duration": 300, "duration": 300,
"playCount": 0,
"year": 2021 "year": 2021
}, },
{ {
@@ -50,6 +52,7 @@
"name": "album-2", "name": "album-2",
"songCount": 3, "songCount": 3,
"duration": 300, "duration": 300,
"playCount": 0,
"year": 2021 "year": 2021
}, },
{ {
@@ -65,6 +68,7 @@
"name": "album-0", "name": "album-0",
"songCount": 3, "songCount": 3,
"duration": 300, "duration": 300,
"playCount": 0,
"year": 2021 "year": 2021
}, },
{ {
@@ -80,6 +84,7 @@
"name": "album-1", "name": "album-1",
"songCount": 3, "songCount": 3,
"duration": 300, "duration": 300,
"playCount": 0,
"year": 2021 "year": 2021
}, },
{ {
@@ -95,6 +100,7 @@
"name": "album-2", "name": "album-2",
"songCount": 3, "songCount": 3,
"duration": 300, "duration": 300,
"playCount": 0,
"year": 2021 "year": 2021
}, },
{ {
@@ -110,6 +116,7 @@
"name": "album-0", "name": "album-0",
"songCount": 3, "songCount": 3,
"duration": 300, "duration": 300,
"playCount": 0,
"year": 2021 "year": 2021
}, },
{ {
@@ -125,6 +132,7 @@
"name": "album-1", "name": "album-1",
"songCount": 3, "songCount": 3,
"duration": 300, "duration": 300,
"playCount": 0,
"year": 2021 "year": 2021
}, },
{ {
@@ -140,6 +148,7 @@
"name": "album-2", "name": "album-2",
"songCount": 3, "songCount": 3,
"duration": 300, "duration": 300,
"playCount": 0,
"year": 2021 "year": 2021
} }
] ]
@@ -20,6 +20,7 @@
"name": "album-0", "name": "album-0",
"songCount": 3, "songCount": 3,
"duration": 300, "duration": 300,
"playCount": 0,
"year": 2021 "year": 2021
}, },
{ {
@@ -35,6 +36,7 @@
"name": "album-0", "name": "album-0",
"songCount": 3, "songCount": 3,
"duration": 300, "duration": 300,
"playCount": 0,
"year": 2021 "year": 2021
}, },
{ {
@@ -50,6 +52,7 @@
"name": "album-0", "name": "album-0",
"songCount": 3, "songCount": 3,
"duration": 300, "duration": 300,
"playCount": 0,
"year": 2021 "year": 2021
}, },
{ {
@@ -65,6 +68,7 @@
"name": "album-1", "name": "album-1",
"songCount": 3, "songCount": 3,
"duration": 300, "duration": 300,
"playCount": 0,
"year": 2021 "year": 2021
}, },
{ {
@@ -80,6 +84,7 @@
"name": "album-1", "name": "album-1",
"songCount": 3, "songCount": 3,
"duration": 300, "duration": 300,
"playCount": 0,
"year": 2021 "year": 2021
}, },
{ {
@@ -95,6 +100,7 @@
"name": "album-1", "name": "album-1",
"songCount": 3, "songCount": 3,
"duration": 300, "duration": 300,
"playCount": 0,
"year": 2021 "year": 2021
}, },
{ {
@@ -110,6 +116,7 @@
"name": "album-2", "name": "album-2",
"songCount": 3, "songCount": 3,
"duration": 300, "duration": 300,
"playCount": 0,
"year": 2021 "year": 2021
}, },
{ {
@@ -125,6 +132,7 @@
"name": "album-2", "name": "album-2",
"songCount": 3, "songCount": 3,
"duration": 300, "duration": 300,
"playCount": 0,
"year": 2021 "year": 2021
}, },
{ {
@@ -140,6 +148,7 @@
"name": "album-2", "name": "album-2",
"songCount": 3, "songCount": 3,
"duration": 300, "duration": 300,
"playCount": 0,
"year": 2021 "year": 2021
} }
] ]
@@ -20,6 +20,7 @@
"name": "album-0", "name": "album-0",
"songCount": 3, "songCount": 3,
"duration": 300, "duration": 300,
"playCount": 0,
"year": 2021 "year": 2021
}, },
{ {
@@ -35,6 +36,7 @@
"name": "album-1", "name": "album-1",
"songCount": 3, "songCount": 3,
"duration": 300, "duration": 300,
"playCount": 0,
"year": 2021 "year": 2021
}, },
{ {
@@ -50,6 +52,7 @@
"name": "album-2", "name": "album-2",
"songCount": 3, "songCount": 3,
"duration": 300, "duration": 300,
"playCount": 0,
"year": 2021 "year": 2021
}, },
{ {
@@ -65,6 +68,7 @@
"name": "album-0", "name": "album-0",
"songCount": 3, "songCount": 3,
"duration": 300, "duration": 300,
"playCount": 0,
"year": 2021 "year": 2021
}, },
{ {
@@ -80,6 +84,7 @@
"name": "album-1", "name": "album-1",
"songCount": 3, "songCount": 3,
"duration": 300, "duration": 300,
"playCount": 0,
"year": 2021 "year": 2021
}, },
{ {
@@ -95,6 +100,7 @@
"name": "album-2", "name": "album-2",
"songCount": 3, "songCount": 3,
"duration": 300, "duration": 300,
"playCount": 0,
"year": 2021 "year": 2021
}, },
{ {
@@ -110,6 +116,7 @@
"name": "album-0", "name": "album-0",
"songCount": 3, "songCount": 3,
"duration": 300, "duration": 300,
"playCount": 0,
"year": 2021 "year": 2021
}, },
{ {
@@ -125,6 +132,7 @@
"name": "album-1", "name": "album-1",
"songCount": 3, "songCount": 3,
"duration": 300, "duration": 300,
"playCount": 0,
"year": 2021 "year": 2021
}, },
{ {
@@ -140,6 +148,7 @@
"name": "album-2", "name": "album-2",
"songCount": 3, "songCount": 3,
"duration": 300, "duration": 300,
"playCount": 0,
"year": 2021 "year": 2021
} }
] ]
+93 -84
View File
@@ -7,51 +7,6 @@
"openSubsonic": true, "openSubsonic": true,
"albumList2": { "albumList2": {
"album": [ "album": [
{
"id": "al-7",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-2",
"artist": "artist-1",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
"displayArtist": "artist-1",
"title": "album-0",
"album": "album-0",
"coverArt": "al-7",
"name": "album-0",
"songCount": 3,
"duration": 300,
"year": 2021
},
{
"id": "al-4",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-1",
"artist": "artist-0",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
"displayArtist": "artist-0",
"title": "album-1",
"album": "album-1",
"coverArt": "al-4",
"name": "album-1",
"songCount": 3,
"duration": 300,
"year": 2021
},
{
"id": "al-12",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-3",
"artist": "artist-2",
"artists": [{ "id": "ar-3", "name": "artist-2" }],
"displayArtist": "artist-2",
"title": "album-1",
"album": "album-1",
"coverArt": "al-12",
"name": "album-1",
"songCount": 3,
"duration": 300,
"year": 2021
},
{ {
"id": "al-3", "id": "al-3",
"created": "2019-11-30T00:00:00Z", "created": "2019-11-30T00:00:00Z",
@@ -65,36 +20,7 @@
"name": "album-0", "name": "album-0",
"songCount": 3, "songCount": 3,
"duration": 300, "duration": 300,
"year": 2021 "playCount": 0,
},
{
"id": "al-8",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-2",
"artist": "artist-1",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
"displayArtist": "artist-1",
"title": "album-1",
"album": "album-1",
"coverArt": "al-8",
"name": "album-1",
"songCount": 3,
"duration": 300,
"year": 2021
},
{
"id": "al-9",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-2",
"artist": "artist-1",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
"displayArtist": "artist-1",
"title": "album-2",
"album": "album-2",
"coverArt": "al-9",
"name": "album-2",
"songCount": 3,
"duration": 300,
"year": 2021 "year": 2021
}, },
{ {
@@ -110,21 +36,23 @@
"name": "album-2", "name": "album-2",
"songCount": 3, "songCount": 3,
"duration": 300, "duration": 300,
"playCount": 0,
"year": 2021 "year": 2021
}, },
{ {
"id": "al-13", "id": "al-8",
"created": "2019-11-30T00:00:00Z", "created": "2019-11-30T00:00:00Z",
"artistId": "ar-3", "artistId": "ar-2",
"artist": "artist-2", "artist": "artist-1",
"artists": [{ "id": "ar-3", "name": "artist-2" }], "artists": [{ "id": "ar-2", "name": "artist-1" }],
"displayArtist": "artist-2", "displayArtist": "artist-1",
"title": "album-2", "title": "album-1",
"album": "album-2", "album": "album-1",
"coverArt": "al-13", "coverArt": "al-8",
"name": "album-2", "name": "album-1",
"songCount": 3, "songCount": 3,
"duration": 300, "duration": 300,
"playCount": 0,
"year": 2021 "year": 2021
}, },
{ {
@@ -140,6 +68,87 @@
"name": "album-0", "name": "album-0",
"songCount": 3, "songCount": 3,
"duration": 300, "duration": 300,
"playCount": 0,
"year": 2021
},
{
"id": "al-12",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-3",
"artist": "artist-2",
"artists": [{ "id": "ar-3", "name": "artist-2" }],
"displayArtist": "artist-2",
"title": "album-1",
"album": "album-1",
"coverArt": "al-12",
"name": "album-1",
"songCount": 3,
"duration": 300,
"playCount": 0,
"year": 2021
},
{
"id": "al-7",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-2",
"artist": "artist-1",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
"displayArtist": "artist-1",
"title": "album-0",
"album": "album-0",
"coverArt": "al-7",
"name": "album-0",
"songCount": 3,
"duration": 300,
"playCount": 0,
"year": 2021
},
{
"id": "al-13",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-3",
"artist": "artist-2",
"artists": [{ "id": "ar-3", "name": "artist-2" }],
"displayArtist": "artist-2",
"title": "album-2",
"album": "album-2",
"coverArt": "al-13",
"name": "album-2",
"songCount": 3,
"duration": 300,
"playCount": 0,
"year": 2021
},
{
"id": "al-4",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-1",
"artist": "artist-0",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
"displayArtist": "artist-0",
"title": "album-1",
"album": "album-1",
"coverArt": "al-4",
"name": "album-1",
"songCount": 3,
"duration": 300,
"playCount": 0,
"year": 2021
},
{
"id": "al-9",
"created": "2019-11-30T00:00:00Z",
"artistId": "ar-2",
"artist": "artist-1",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
"displayArtist": "artist-1",
"title": "album-2",
"album": "album-2",
"coverArt": "al-9",
"name": "album-2",
"songCount": 3,
"duration": 300,
"playCount": 0,
"year": 2021 "year": 2021
} }
] ]
@@ -18,6 +18,7 @@
"name": "album-0", "name": "album-0",
"songCount": 3, "songCount": 3,
"duration": 300, "duration": 300,
"playCount": 0,
"genre": "Unknown Genre", "genre": "Unknown Genre",
"genres": [{ "name": "Unknown Genre" }], "genres": [{ "name": "Unknown Genre" }],
"year": 2021, "year": 2021,
+2 -1
View File
@@ -15,7 +15,8 @@
"album": "", "album": "",
"name": "", "name": "",
"songCount": 0, "songCount": 0,
"duration": 0 "duration": 0,
"playCount": 0
} }
} }
} }
+3
View File
@@ -23,6 +23,7 @@
"name": "album-0", "name": "album-0",
"songCount": 3, "songCount": 3,
"duration": 300, "duration": 300,
"playCount": 0,
"genre": "Unknown Genre", "genre": "Unknown Genre",
"genres": [{ "name": "Unknown Genre" }], "genres": [{ "name": "Unknown Genre" }],
"year": 2021 "year": 2021
@@ -40,6 +41,7 @@
"name": "album-1", "name": "album-1",
"songCount": 3, "songCount": 3,
"duration": 300, "duration": 300,
"playCount": 0,
"genre": "Unknown Genre", "genre": "Unknown Genre",
"genres": [{ "name": "Unknown Genre" }], "genres": [{ "name": "Unknown Genre" }],
"year": 2021 "year": 2021
@@ -57,6 +59,7 @@
"name": "album-2", "name": "album-2",
"songCount": 3, "songCount": 3,
"duration": 300, "duration": 300,
"playCount": 0,
"genre": "Unknown Genre", "genre": "Unknown Genre",
"genres": [{ "name": "Unknown Genre" }], "genres": [{ "name": "Unknown Genre" }],
"year": 2021 "year": 2021
+3
View File
@@ -23,6 +23,7 @@
"name": "album-0", "name": "album-0",
"songCount": 3, "songCount": 3,
"duration": 300, "duration": 300,
"playCount": 0,
"genre": "Unknown Genre", "genre": "Unknown Genre",
"genres": [{ "name": "Unknown Genre" }], "genres": [{ "name": "Unknown Genre" }],
"year": 2021 "year": 2021
@@ -40,6 +41,7 @@
"name": "album-1", "name": "album-1",
"songCount": 3, "songCount": 3,
"duration": 300, "duration": 300,
"playCount": 0,
"genre": "Unknown Genre", "genre": "Unknown Genre",
"genres": [{ "name": "Unknown Genre" }], "genres": [{ "name": "Unknown Genre" }],
"year": 2021 "year": 2021
@@ -57,6 +59,7 @@
"name": "album-2", "name": "album-2",
"songCount": 3, "songCount": 3,
"duration": 300, "duration": 300,
"playCount": 0,
"genre": "Unknown Genre", "genre": "Unknown Genre",
"genres": [{ "name": "Unknown Genre" }], "genres": [{ "name": "Unknown Genre" }],
"year": 2021 "year": 2021
+3
View File
@@ -23,6 +23,7 @@
"name": "album-0", "name": "album-0",
"songCount": 3, "songCount": 3,
"duration": 300, "duration": 300,
"playCount": 0,
"genre": "Unknown Genre", "genre": "Unknown Genre",
"genres": [{ "name": "Unknown Genre" }], "genres": [{ "name": "Unknown Genre" }],
"year": 2021 "year": 2021
@@ -40,6 +41,7 @@
"name": "album-1", "name": "album-1",
"songCount": 3, "songCount": 3,
"duration": 300, "duration": 300,
"playCount": 0,
"genre": "Unknown Genre", "genre": "Unknown Genre",
"genres": [{ "name": "Unknown Genre" }], "genres": [{ "name": "Unknown Genre" }],
"year": 2021 "year": 2021
@@ -57,6 +59,7 @@
"name": "album-2", "name": "album-2",
"songCount": 3, "songCount": 3,
"duration": 300, "duration": 300,
"playCount": 0,
"genre": "Unknown Genre", "genre": "Unknown Genre",
"genres": [{ "name": "Unknown Genre" }], "genres": [{ "name": "Unknown Genre" }],
"year": 2021 "year": 2021
+9
View File
@@ -20,6 +20,7 @@
"name": "album-0", "name": "album-0",
"songCount": 0, "songCount": 0,
"duration": 0, "duration": 0,
"playCount": 0,
"genre": "Unknown Genre", "genre": "Unknown Genre",
"genres": [{ "name": "Unknown Genre" }], "genres": [{ "name": "Unknown Genre" }],
"year": 2021 "year": 2021
@@ -37,6 +38,7 @@
"name": "album-1", "name": "album-1",
"songCount": 0, "songCount": 0,
"duration": 0, "duration": 0,
"playCount": 0,
"genre": "Unknown Genre", "genre": "Unknown Genre",
"genres": [{ "name": "Unknown Genre" }], "genres": [{ "name": "Unknown Genre" }],
"year": 2021 "year": 2021
@@ -54,6 +56,7 @@
"name": "album-2", "name": "album-2",
"songCount": 0, "songCount": 0,
"duration": 0, "duration": 0,
"playCount": 0,
"genre": "Unknown Genre", "genre": "Unknown Genre",
"genres": [{ "name": "Unknown Genre" }], "genres": [{ "name": "Unknown Genre" }],
"year": 2021 "year": 2021
@@ -71,6 +74,7 @@
"name": "album-0", "name": "album-0",
"songCount": 0, "songCount": 0,
"duration": 0, "duration": 0,
"playCount": 0,
"genre": "Unknown Genre", "genre": "Unknown Genre",
"genres": [{ "name": "Unknown Genre" }], "genres": [{ "name": "Unknown Genre" }],
"year": 2021 "year": 2021
@@ -88,6 +92,7 @@
"name": "album-1", "name": "album-1",
"songCount": 0, "songCount": 0,
"duration": 0, "duration": 0,
"playCount": 0,
"genre": "Unknown Genre", "genre": "Unknown Genre",
"genres": [{ "name": "Unknown Genre" }], "genres": [{ "name": "Unknown Genre" }],
"year": 2021 "year": 2021
@@ -105,6 +110,7 @@
"name": "album-2", "name": "album-2",
"songCount": 0, "songCount": 0,
"duration": 0, "duration": 0,
"playCount": 0,
"genre": "Unknown Genre", "genre": "Unknown Genre",
"genres": [{ "name": "Unknown Genre" }], "genres": [{ "name": "Unknown Genre" }],
"year": 2021 "year": 2021
@@ -122,6 +128,7 @@
"name": "album-0", "name": "album-0",
"songCount": 0, "songCount": 0,
"duration": 0, "duration": 0,
"playCount": 0,
"genre": "Unknown Genre", "genre": "Unknown Genre",
"genres": [{ "name": "Unknown Genre" }], "genres": [{ "name": "Unknown Genre" }],
"year": 2021 "year": 2021
@@ -139,6 +146,7 @@
"name": "album-1", "name": "album-1",
"songCount": 0, "songCount": 0,
"duration": 0, "duration": 0,
"playCount": 0,
"genre": "Unknown Genre", "genre": "Unknown Genre",
"genres": [{ "name": "Unknown Genre" }], "genres": [{ "name": "Unknown Genre" }],
"year": 2021 "year": 2021
@@ -156,6 +164,7 @@
"name": "album-2", "name": "album-2",
"songCount": 0, "songCount": 0,
"duration": 0, "duration": 0,
"playCount": 0,
"genre": "Unknown Genre", "genre": "Unknown Genre",
"genres": [{ "name": "Unknown Genre" }], "genres": [{ "name": "Unknown Genre" }],
"year": 2021 "year": 2021
+8 -2
View File
@@ -1,6 +1,7 @@
package taglib package taglib
import ( import (
"fmt"
"path/filepath" "path/filepath"
"strconv" "strconv"
"strings" "strings"
@@ -20,8 +21,13 @@ func (TagLib) CanRead(absPath string) bool {
} }
func (TagLib) Read(absPath string) (tagcommon.Info, error) { func (TagLib) Read(absPath string) (tagcommon.Info, error) {
raw, props, err := audiotags.Read(absPath) f, err := audiotags.Open(absPath)
return &info{raw, props}, err if err != nil {
return nil, fmt.Errorf("open: %w", err)
}
props := f.ReadAudioProperties()
raw := f.ReadTags()
return &info{raw, props}, nil
} }
type info struct { type info struct {