Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
998f320e31
|
||
|
|
3836e97ccb
|
No files matched your search
@@ -1,5 +1,4 @@
|
||||
*.db
|
||||
*.db.*.bak
|
||||
*db-wal
|
||||
*db-shm
|
||||
*.sql
|
||||
|
||||
@@ -24,7 +24,7 @@
|
||||
- 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)
|
||||
- newer salt and token auth
|
||||
- tested on [airsonic-refix](https://github.com/tamland/airsonic-refix), [amperfy](https://github.com/BLeeEZ/amperfy), [symfonium](https://symfonium.app), [dsub](https://f-droid.org/en/packages/github.daneren2005.dsub/), [jamstash](https://github.com/sqrlmstr5000/Jamstash), [subsonic.el](https://git.sr.ht/~amk/subsonic.el), [sublime music](https://github.com/sublime-music/sublime-music), [soundwaves](https://apps.apple.com/us/app/soundwaves/id736139596), [stmp](https://github.com/wildeyedskies/stmp), [termsonic](https://git.sixfoisneuf.fr/termsonic/), [tempus](https://github.com/eddyizm/tempus/), [strawberry](https://www.strawberrymusicplayer.org/), and [ultrasonic](https://gitlab.com/ultrasonic/ultrasonic)
|
||||
- tested on [airsonic-refix](https://github.com/tamland/airsonic-refix), [symfonium](https://symfonium.app), [dsub](https://f-droid.org/en/packages/github.daneren2005.dsub/), [jamstash](http://jamstash.com/), [subsonic.el](https://git.sr.ht/~amk/subsonic.el), [sublime music](https://github.com/sublime-music/sublime-music), [soundwaves](https://apps.apple.com/us/app/soundwaves/id736139596), [stmp](https://github.com/wildeyedskies/stmp), [termsonic](https://git.sixfoisneuf.fr/termsonic/), [tempus](https://github.com/eddyizm/tempus/), [strawberry](https://www.strawberrymusicplayer.org/), and [ultrasonic](https://gitlab.com/ultrasonic/ultrasonic)
|
||||
|
||||
## installation
|
||||
|
||||
@@ -52,6 +52,7 @@ password can then be changed from the web interface
|
||||
| env var | command line arg | description |
|
||||
| ----------------------------------- | ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `GONIC_MUSIC_PATH` | `-music-path` | path to your music collection (see also multi-folder support below) |
|
||||
| `GONIC_DEFAULT_MUSIC_PATH` | `-default-music-path` | default music path for when no folder is selected in client (useful for when client does not support choosing a folder) |
|
||||
| `GONIC_PODCAST_PATH` | `-podcast-path` | path to a podcasts directory |
|
||||
| `GONIC_PLAYLISTS_PATH` | `-playlists-path` | path to new or existing directory with m3u files for subsonic playlists. items in the directory should be in the format `<userid>/<name>.m3u`. for example the admin user could have `1/my-playlist.m3u`. gonic create and make changes to these playlists over the subsonic api. |
|
||||
| `GONIC_CACHE_PATH` | `-cache-path` | path to store audio transcodes, covers, etc |
|
||||
@@ -75,15 +76,6 @@ password can then be changed from the web interface
|
||||
| `GONIC_TRANSCODE_CACHE_SIZE` | `-transcode-cache-size` | **optional** size of the transcode cache in MB (0 = no limit) |
|
||||
| `GONIC_TRANSCODE_EJECT_INTERVAL` | `-transcode-eject-interval` | **optional** interval (in minutes) to eject transcode cache (0 = never) |
|
||||
| `GONIC_EXPVAR` | `-expvar` | **optional** enable the /debug/vars endpoint (exposes useful debugging attributes as well as database stats) |
|
||||
| `GONIC_LDAP_FQDN` | `-ldap-fqdn` | **optional** the name of the server to connect to (required for LDAP) |
|
||||
| `GONIC_LDAP_PORT` | `-ldap-port` | **optional** what port the LDAP server is hosted on (_default_ `389`) |
|
||||
| `GONIC_LDAP_TLS` | `-ldap-tls` | **optional** whether gonic will connect to the LDAP server using TLS (_default_ `false`) |
|
||||
| `GONIC_LDAP_BASE_DN` | `-ldap-base-dn` | **optional** the base DN for LDAP objects (required for LDAP, escaping the commas might be necessary if using environmental variable) |
|
||||
| `GONIC_LDAP_USERNAME_ATTR` | `-ldap-username-attr` | **optional** attribute used by the LDAP server for usernames, gets prepended to BaseDN (_default_ `uid`) |
|
||||
| `GONIC_LDAP_BIND_USER` | `-ldap-bind-user` | **optional** the bind user to bind to LDAP with (required for LDAP) |
|
||||
| `GONIC_LDAP_BIND_PASS` | `-ldap-bind-pass` | **optional** the password of the LDAP bind user (required for LDAP) |
|
||||
| `GONIC_LDAP_FILTER` | `-ldap-filter` | **optional** the filter to select LDAP objects with (escaping the commas might be necessary if using environmental variable) |
|
||||
| `GONIC_LDAP_ADMIN_FILTER` | `-ldap-admin-filter` | **optional** the filter to select LDAP admin objects with (escaping the commas might be necessary if using environmental variable) (_default_ `(memberof=cn=admin)`) |
|
||||
|
||||
## multi valued tags (v0.16+)
|
||||
|
||||
|
||||
+3
-23
@@ -39,7 +39,6 @@ import (
|
||||
"go.senan.xyz/gonic/infocache/artistinfocache"
|
||||
"go.senan.xyz/gonic/jukebox"
|
||||
"go.senan.xyz/gonic/lastfm"
|
||||
"go.senan.xyz/gonic/ldap"
|
||||
"go.senan.xyz/gonic/listenbrainz"
|
||||
"go.senan.xyz/gonic/playlist"
|
||||
"go.senan.xyz/gonic/podcast"
|
||||
@@ -63,6 +62,7 @@ func main() {
|
||||
|
||||
var confMusicPaths pathAliases
|
||||
flag.Var(&confMusicPaths, "music-path", "path to music")
|
||||
defaultMusicPath := flag.String("default-music-path", "", "interval (in minutes) to automatically scan music (optional)")
|
||||
|
||||
confPlaylistsPath := flag.String("playlists-path", "", "path to your list of new or existing m3u playlists that gonic can manage")
|
||||
|
||||
@@ -84,26 +84,6 @@ func main() {
|
||||
|
||||
confExcludePattern := flag.String("exclude-pattern", "", "regex pattern to exclude files from scan (optional)")
|
||||
|
||||
var ldapConfig ldap.Config
|
||||
var ldapStore = make(ldap.LDAPStore)
|
||||
flag.StringVar(&ldapConfig.BindUser, "ldap-bind-user", "", "the bind user to bind to LDAP with (required for LDAP)")
|
||||
flag.StringVar(&ldapConfig.BindPass, "ldap-bind-pass", "", "the password of the LDAP bind user (required for LDAP)")
|
||||
flag.StringVar(&ldapConfig.BaseDN, "ldap-base-dn", "", "the base DN for LDAP objects (required for LDAP)")
|
||||
flag.StringVar(&ldapConfig.UsernameAttr, "ldap-username-attr", "uid", "attribute used by the LDAP server for usernames, gets prepended to BaseDN (optional)")
|
||||
|
||||
flag.StringVar(&ldapConfig.Filter, "ldap-filter", "", "the filter to select LDAP objects with (optional)")
|
||||
flag.StringVar(&ldapConfig.AdminFilter, "ldap-admin-filter", "(memberof=cn=admin)", "the filter to select LDAP objects with (optional)")
|
||||
|
||||
flag.StringVar(&ldapConfig.FQDN, "ldap-fqdn", "", "the name of the server to connect to (required for LDAP)")
|
||||
flag.UintVar(&ldapConfig.Port, "ldap-port", 389, "what port the LDAP server is hosted on (optional)")
|
||||
flag.BoolVar(&ldapConfig.TLS, "ldap-tls", false, "whether gonic will connect to the LDAP server using TLS (optional)")
|
||||
|
||||
if ldapConfig.FQDN != "" {
|
||||
if ldapConfig.BindUser == "" || ldapConfig.BindPass == "" || ldapConfig.BaseDN == "" {
|
||||
log.Fatal("a server was provided for an LDAP connection, but configuration is incomplete")
|
||||
}
|
||||
}
|
||||
|
||||
var confMultiValueGenre, confMultiValueArtist, confMultiValueAlbumArtist multiValueSetting
|
||||
flag.Var(&confMultiValueGenre, "multi-value-genre", "setting for multi-valued genre scanning (optional)")
|
||||
flag.Var(&confMultiValueArtist, "multi-value-artist", "setting for multi-valued track artist scanning (optional)")
|
||||
@@ -273,11 +253,11 @@ func main() {
|
||||
return url.String()
|
||||
}
|
||||
|
||||
ctrlAdmin, err := ctrladmin.New(dbc, sessDB, scannr, podcast, lastfmClient, resolveProxyPath, ldapConfig, ldapStore)
|
||||
ctrlAdmin, err := ctrladmin.New(dbc, sessDB, scannr, podcast, lastfmClient, resolveProxyPath)
|
||||
if err != nil {
|
||||
log.Panicf("error creating admin controller: %v\n", err)
|
||||
}
|
||||
ctrlSubsonic, err := ctrlsubsonic.New(dbc, scannr, musicPaths, *confPodcastPath, cacheDirAudio, cacheDirCovers, jukebx, playlistStore, scrobblers, podcast, transcoder, lastfmClient, artistInfoCache, albumInfoCache, tagReader, resolveProxyPath, ldapConfig, ldapStore)
|
||||
ctrlSubsonic, err := ctrlsubsonic.New(dbc, scannr, musicPaths, *defaultMusicPath, *confPodcastPath, cacheDirAudio, cacheDirCovers, jukebx, playlistStore, scrobblers, podcast, transcoder, lastfmClient, artistInfoCache, albumInfoCache, tagReader, resolveProxyPath)
|
||||
if err != nil {
|
||||
log.Panicf("error creating subsonic controller: %v\n", err)
|
||||
}
|
||||
|
||||
@@ -224,7 +224,6 @@ type Track struct {
|
||||
TagDiscNumber int `sql:"default: null"`
|
||||
TagBrainzID string `sql:"default: null"`
|
||||
TagLyrics string `sql:"default: null"`
|
||||
TagYear int `sql:"default: null"`
|
||||
|
||||
ReplayGainTrackGain float32
|
||||
ReplayGainTrackPeak float32
|
||||
@@ -288,7 +287,7 @@ type User struct {
|
||||
ID int `gorm:"primary_key"`
|
||||
CreatedAt time.Time
|
||||
Name string `gorm:"not null; unique_index" sql:"default: null"`
|
||||
Password string `sql:"default: null"`
|
||||
Password string `gorm:"not null" sql:"default: null"`
|
||||
LastFMSession string `sql:"default: null"`
|
||||
ListenBrainzURL string `sql:"default: null"`
|
||||
ListenBrainzToken string `sql:"default: null"`
|
||||
|
||||
@@ -83,7 +83,6 @@ func (db *DB) Migrate(ctx MigrationContext) error {
|
||||
construct(ctx, "202509301448", migrateAddTrackEmbeddedCover),
|
||||
construct(ctx, "202512021147", migrateAlbumAddIndexOnCreatedAt),
|
||||
construct(ctx, "202601201000", migrateAddAlbumDiscTitles),
|
||||
construct(ctx, "202602061800", migrateAddTrackYear),
|
||||
}
|
||||
|
||||
return gormigrate.
|
||||
@@ -880,22 +879,3 @@ func migrateAlbumAddIndexOnCreatedAt(tx *gorm.DB, _ MigrationContext) error {
|
||||
func migrateAddAlbumDiscTitles(tx *gorm.DB, _ MigrationContext) error {
|
||||
return tx.AutoMigrate(AlbumDiscTitle{}).Error
|
||||
}
|
||||
|
||||
func migrateAddTrackYear(tx *gorm.DB, _ MigrationContext) error {
|
||||
step := tx.AutoMigrate(Track{})
|
||||
if err := step.Error; err != nil {
|
||||
return fmt.Errorf("step auto migrate: %w", err)
|
||||
}
|
||||
|
||||
step = tx.Exec(`
|
||||
UPDATE tracks
|
||||
SET tag_year=(SELECT tag_year
|
||||
FROM albums
|
||||
WHERE tracks.album_id = albums.id)
|
||||
`)
|
||||
if err := step.Error; err != nil {
|
||||
return fmt.Errorf("step set default track year based on album's : %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -13,7 +13,6 @@ require (
|
||||
github.com/env25/mpdlrc v0.7.4
|
||||
github.com/fatih/structs v1.1.0
|
||||
github.com/fsnotify/fsnotify v1.9.0
|
||||
github.com/go-ldap/ldap/v3 v3.4.6
|
||||
github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/gorilla/securecookie v1.1.2
|
||||
@@ -39,13 +38,11 @@ require (
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358 // indirect
|
||||
github.com/Masterminds/goutils v1.1.1 // indirect
|
||||
github.com/Masterminds/semver v1.5.0 // indirect
|
||||
github.com/PuerkitoBio/goquery v1.11.0 // indirect
|
||||
github.com/aymerick/douceur v0.2.0 // indirect
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
github.com/go-asn1-ber/asn1-ber v1.5.5 // indirect
|
||||
github.com/go-openapi/jsonpointer v0.22.4 // indirect
|
||||
github.com/go-openapi/swag/jsonname v0.25.4 // indirect
|
||||
github.com/gorilla/context v1.1.2 // indirect
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
cloud.google.com/go v0.33.1/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
|
||||
github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358 h1:mFRzDkZVAjdal+s7s0MwaRv9igoPqLRdzOLzw/8Xvq8=
|
||||
github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358/go.mod h1:chxPXzSsl7ZWRAuOIE23GDNzjWuZquvFlgA8xmpunjU=
|
||||
github.com/Masterminds/goutils v1.1.1 h1:5nUrii3FMTL5diU80unEVvNevw1nH4+ZV4DSLVJLSYI=
|
||||
github.com/Masterminds/goutils v1.1.1/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU=
|
||||
github.com/Masterminds/semver v1.5.0 h1:H65muMkzWKEuNDnfl9d70GUjFniHKHRbFPGBuZ3QEww=
|
||||
@@ -10,8 +8,6 @@ github.com/Masterminds/sprig v2.22.0+incompatible/go.mod h1:y6hNFY5UBTIWBxnzTeuN
|
||||
github.com/PuerkitoBio/goquery v1.5.1/go.mod h1:GsLWisAFVj4WgDibEWF4pvYnkVQBpKBKeU+7zCJoLcc=
|
||||
github.com/PuerkitoBio/goquery v1.11.0 h1:jZ7pwMQXIITcUXNH83LLk+txlaEy6NVOfTuP43xxfqw=
|
||||
github.com/PuerkitoBio/goquery v1.11.0/go.mod h1:wQHgxUOU3JGuj3oD/QFfxUdlzW6xPHfqyHre6VMY4DQ=
|
||||
github.com/alexbrainman/sspi v0.0.0-20210105120005-909beea2cc74 h1:Kk6a4nehpJ3UuJRqlA3JxYxBZEqCeOmATOvrbT4p9RA=
|
||||
github.com/alexbrainman/sspi v0.0.0-20210105120005-909beea2cc74/go.mod h1:cEWa1LVoE5KvSD9ONXsZrj0z6KqySlCCNKHlLzbqAt4=
|
||||
github.com/andybalholm/cascadia v1.1.0/go.mod h1:GsXiBklL0woXo1j/WYWtSYYC4ouU9PqHO0sqidkEA4Y=
|
||||
github.com/andybalholm/cascadia v1.3.3 h1:AG2YHrzJIm4BZ19iwJ/DAua6Btl3IwJX+VI4kktS1LM=
|
||||
github.com/andybalholm/cascadia v1.3.3/go.mod h1:xNd9bqTn98Ln4DwST8/nG+H0yuB8Hmgu1YHNnWw0GeA=
|
||||
@@ -41,10 +37,6 @@ github.com/fatih/structs v1.1.0 h1:Q7juDM0QtcnhCpeyLGQKyg4TOIghuNXrkL32pHAUMxo=
|
||||
github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M=
|
||||
github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
|
||||
github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
|
||||
github.com/go-asn1-ber/asn1-ber v1.5.5 h1:MNHlNMBDgEKD4TcKr36vQN68BA00aDfjIt3/bD50WnA=
|
||||
github.com/go-asn1-ber/asn1-ber v1.5.5/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0=
|
||||
github.com/go-ldap/ldap/v3 v3.4.6 h1:ert95MdbiG7aWo/oPYp9btL3KJlMPKnP58r09rI8T+A=
|
||||
github.com/go-ldap/ldap/v3 v3.4.6/go.mod h1:IGMQANNtxpsOzj7uUAMjpGBaOVTC4DYyIy8VsTdxmtc=
|
||||
github.com/go-openapi/jsonpointer v0.22.4 h1:dZtK82WlNpVLDW2jlA1YCiVJFVqkED1MegOUy9kR5T4=
|
||||
github.com/go-openapi/jsonpointer v0.22.4/go.mod h1:elX9+UgznpFhgBuaMQ7iu4lvvX1nvNsesQ3oxmYTw80=
|
||||
github.com/go-openapi/swag/jsonname v0.25.4 h1:bZH0+MsS03MbnwBXYhuTttMOqk+5KcQ9869Vye1bNHI=
|
||||
@@ -65,7 +57,6 @@ 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/shlex v0.0.0-20191202100458-e7afc7fbc510 h1:El6M4kTTCOh6aBiKaUGG7oYTSPP8MxqL4YI3kZKwcP4=
|
||||
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.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg=
|
||||
@@ -150,11 +141,8 @@ github.com/scylladb/termtables v0.0.0-20191203121021-c4c0b6d42ff4/go.mod h1:C1a7
|
||||
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/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/tetratelabs/wazero v1.11.0 h1:+gKemEuKCTevU4d7ZTzlsvgd1uaToIDtlQlmNbwqYhA=
|
||||
|
||||
-225
@@ -1,225 +0,0 @@
|
||||
package ldap
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"go.senan.xyz/gonic/db"
|
||||
|
||||
"github.com/go-ldap/ldap/v3"
|
||||
)
|
||||
|
||||
// LDAPStore maps users to a cached password
|
||||
type LDAPStore map[string]CachedLDAPpassword
|
||||
|
||||
// Add caches a password username set.
|
||||
func (store LDAPStore) Add(username, password string) {
|
||||
store[username] = CachedLDAPpassword{
|
||||
Password: password,
|
||||
ExpiresAt: time.Now().Add(time.Hour * 8), // Keep the password valid for 8 hours.
|
||||
}
|
||||
}
|
||||
|
||||
// IsValid checks if a user's password is stored in the cache and checks if a
|
||||
// given password is valid.
|
||||
func (store LDAPStore) IsValid(username, password string) bool {
|
||||
cached, ok := store[username]
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
|
||||
if cached.Password != password {
|
||||
return false
|
||||
}
|
||||
|
||||
return cached.IsValid()
|
||||
}
|
||||
|
||||
// CachedLDAPpassword stores an LDAP user's password and a time at which the
|
||||
// server should no longer accept it.
|
||||
type CachedLDAPpassword struct {
|
||||
Password string
|
||||
ExpiresAt time.Time
|
||||
}
|
||||
|
||||
func (password CachedLDAPpassword) IsValid() bool {
|
||||
return password.ExpiresAt.After(time.Now())
|
||||
}
|
||||
|
||||
// Cofig stores the user's LDAP server options.
|
||||
type Config struct {
|
||||
BindUser string
|
||||
BindPass string
|
||||
BaseDN string
|
||||
UsernameAttr string
|
||||
|
||||
Filter string
|
||||
AdminFilter string
|
||||
|
||||
FQDN string
|
||||
Port uint
|
||||
TLS bool
|
||||
}
|
||||
|
||||
func (c Config) IsSetup() bool {
|
||||
// This is basically checking if LDAP is setup, if ldapFQDN isn't set we can
|
||||
// assume that the user hasn't configured LDAP.
|
||||
return c.FQDN != ""
|
||||
}
|
||||
|
||||
func CheckLDAPcreds(username string, password string, dbc *db.DB, config Config, store LDAPStore) (bool, error) {
|
||||
if !config.IsSetup() {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
if store.IsValid(username, password) {
|
||||
log.Println("Password authenticated via cache!")
|
||||
return true, nil
|
||||
}
|
||||
|
||||
log.Println("Checking password against LDAP server ...")
|
||||
|
||||
// Now, we can try to connect to the LDAP server.
|
||||
l, err := createLDAPconnection(config)
|
||||
if err != nil {
|
||||
// Return a generic error.
|
||||
log.Println("Failed to connect to LDAP server:", err)
|
||||
return false, errors.New("failed to connect to LDAP server")
|
||||
}
|
||||
defer l.Close()
|
||||
|
||||
// Create the user if it doesn't exist on the database already.
|
||||
err = createUserFromLDAP(username, dbc, config, l)
|
||||
if err != nil {
|
||||
log.Println("Failed to create user from LDAP:", err)
|
||||
return false, err
|
||||
}
|
||||
|
||||
// After we have a connection, let's try binding
|
||||
_, err = l.SimpleBind(&ldap.SimpleBindRequest{
|
||||
Username: fmt.Sprintf("%s=%s,%s", config.UsernameAttr, username, config.BaseDN),
|
||||
Password: password,
|
||||
})
|
||||
|
||||
if err == nil {
|
||||
// Authentication was OK
|
||||
store.Add(username, password)
|
||||
return true, nil
|
||||
}
|
||||
|
||||
log.Println("Failed to bind to LDAP server:", err)
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// Creates a user from creds
|
||||
func createUserFromLDAP(username string, dbc *db.DB, config Config, l *ldap.Conn) error {
|
||||
user := dbc.GetUserByName(username)
|
||||
if user != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
if !config.IsSetup() {
|
||||
return nil
|
||||
}
|
||||
|
||||
isAdmin := doesLDAPAdminExist(username, config, l)
|
||||
log.Println(username, isAdmin)
|
||||
|
||||
if !doesLDAPUserExist(username, config, l) {
|
||||
return errors.New("no such user")
|
||||
}
|
||||
|
||||
newUser := db.User{
|
||||
Name: username,
|
||||
Password: "", // no password because we want auth to fail.
|
||||
IsAdmin: isAdmin,
|
||||
}
|
||||
|
||||
err := dbc.Create(&newUser).Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
log.Println("User created via LDAP:", username)
|
||||
return nil
|
||||
}
|
||||
|
||||
// doesLDAPAdminExist checks if an admin exists on the server.
|
||||
func doesLDAPAdminExist(username string, config Config, l *ldap.Conn) bool {
|
||||
filter := fmt.Sprintf("(&(%s=%s)%s)", config.UsernameAttr, ldap.EscapeFilter(username), config.AdminFilter)
|
||||
|
||||
searchReq := ldap.NewSearchRequest(
|
||||
config.BaseDN,
|
||||
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
|
||||
filter,
|
||||
[]string{"dn"},
|
||||
nil,
|
||||
)
|
||||
|
||||
result, err := l.Search(searchReq)
|
||||
if err != nil {
|
||||
log.Println("failed to query LDAP server:", err)
|
||||
return false
|
||||
}
|
||||
|
||||
if len(result.Entries) == 1 {
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// doesLDAPUserExist checks if a user exists on the server.
|
||||
func doesLDAPUserExist(username string, config Config, l *ldap.Conn) bool {
|
||||
filter := fmt.Sprintf("(&(%s=%s)%s)", config.UsernameAttr, ldap.EscapeFilter(username), config.Filter)
|
||||
|
||||
searchReq := ldap.NewSearchRequest(
|
||||
config.BaseDN,
|
||||
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
|
||||
filter,
|
||||
[]string{"dn"},
|
||||
nil,
|
||||
)
|
||||
|
||||
result, err := l.Search(searchReq)
|
||||
if err != nil {
|
||||
log.Println("failed to query LDAP server:", err)
|
||||
return false
|
||||
}
|
||||
|
||||
if len(result.Entries) == 1 {
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// Creates a connection to an LDAP server.
|
||||
func createLDAPconnection(config Config) (*ldap.Conn, error) {
|
||||
protocol := "ldap"
|
||||
if config.TLS {
|
||||
protocol = "ldaps"
|
||||
}
|
||||
|
||||
// Now, we can try to connect to the LDAP server.
|
||||
l, err := ldap.DialURL(fmt.Sprintf("%s://%s:%d", protocol, config.FQDN, config.Port))
|
||||
if err != nil {
|
||||
// Warn the server and return the error.
|
||||
log.Println("Failed to connect to LDAP server", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// After we have a connection, let's try binding
|
||||
_, err = l.SimpleBind(&ldap.SimpleBindRequest{
|
||||
Username: fmt.Sprintf("%s=%s,%s", config.UsernameAttr, config.BindUser, config.BaseDN),
|
||||
Password: config.BindPass,
|
||||
})
|
||||
if err != nil {
|
||||
log.Println("Failed to bind to LDAP:", err)
|
||||
return nil, errors.New("wrong username or password")
|
||||
}
|
||||
|
||||
return l, nil
|
||||
}
|
||||
@@ -2,7 +2,6 @@ package listenbrainz
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/tls"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -31,17 +30,7 @@ type Client struct {
|
||||
}
|
||||
|
||||
func NewClient() *Client {
|
||||
// disable post-quantum key exchange (Kyber) to avoid "connection reset by peer" errors.
|
||||
// listenbrainz's server can't handle the larger TLS ClientHello
|
||||
// https://github.com/golang/go/issues/70139
|
||||
return NewClientCustom(&http.Client{
|
||||
Transport: &http.Transport{
|
||||
TLSClientConfig: &tls.Config{
|
||||
MinVersion: tls.VersionTLS12,
|
||||
CurvePreferences: []tls.CurveID{tls.X25519, tls.CurveP256, tls.CurveP384},
|
||||
},
|
||||
},
|
||||
})
|
||||
return NewClientCustom(http.DefaultClient)
|
||||
}
|
||||
|
||||
func NewClientCustom(httpClient *http.Client) *Client {
|
||||
|
||||
@@ -134,9 +134,6 @@ func (s *Store) Read(relPath string) (*Playlist, error) {
|
||||
if strings.HasPrefix(line, "#") {
|
||||
continue
|
||||
}
|
||||
if !filepath.IsAbs(line) {
|
||||
line = filepath.Join(filepath.Dir(absPath), line)
|
||||
}
|
||||
playlist.Items = append(playlist.Items, line)
|
||||
}
|
||||
|
||||
@@ -189,9 +186,6 @@ func (s *Store) Write(relPath string, playlist *Playlist) error {
|
||||
fmt.Fprintln(file, encodeAttr(attrCommment, playlist.Comment))
|
||||
fmt.Fprintln(file, encodeAttr(attrIsPublic, fmt.Sprint(playlist.IsPublic)))
|
||||
for _, line := range playlist.Items {
|
||||
if rel, err := filepath.Rel(filepath.Dir(absPath), line); err == nil {
|
||||
line = rel
|
||||
}
|
||||
fmt.Fprintln(file, line)
|
||||
}
|
||||
|
||||
|
||||
@@ -32,9 +32,9 @@ Example comment
|
||||
It has multiple lines 👍
|
||||
`,
|
||||
Items: []string{
|
||||
"/music/item 1.flac",
|
||||
"/music/item 2.flac",
|
||||
"/music/item 3.flac",
|
||||
"item 1.flac",
|
||||
"item 2.flac",
|
||||
"item 3.flac",
|
||||
},
|
||||
IsPublic: true,
|
||||
}
|
||||
|
||||
+9
-17
@@ -81,17 +81,13 @@ func (p *Podcasts) AddNewPodcast(rssURL string, feed *gofeed.Feed) (*db.Podcast,
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("find unique podcast dir: %w", err)
|
||||
}
|
||||
var author string
|
||||
if feed.ITunesExt != nil {
|
||||
author = feed.ITunesExt.Author
|
||||
}
|
||||
podcast := db.Podcast{
|
||||
Description: feed.Description,
|
||||
ImageURL: "",
|
||||
Title: feed.Title,
|
||||
URL: rssURL,
|
||||
RootDir: rootDir,
|
||||
Author: author,
|
||||
Author: feed.ITunesExt.Author,
|
||||
}
|
||||
if feed.Image != nil {
|
||||
podcast.ImageURL = feed.Image.URL
|
||||
@@ -230,10 +226,6 @@ func (p *Podcasts) isAudio(rawItemURL string) (bool, error) {
|
||||
}
|
||||
|
||||
func itemToEpisode(podcast *db.Podcast, size, duration int, audio string, item *gofeed.Item) *db.PodcastEpisode {
|
||||
author := podcast.Author
|
||||
if item.ITunesExt != nil {
|
||||
author = cmp.Or(item.ITunesExt.Author, podcast.Author)
|
||||
}
|
||||
return &db.PodcastEpisode{
|
||||
PodcastID: podcast.ID,
|
||||
Description: item.Description,
|
||||
@@ -243,7 +235,7 @@ func itemToEpisode(podcast *db.Podcast, size, duration int, audio string, item *
|
||||
PublishDate: item.PublishedParsed,
|
||||
AudioURL: audio,
|
||||
Status: db.PodcastEpisodeStatusSkipped,
|
||||
Artist: cmp.Or(author),
|
||||
Artist: cmp.Or(item.ITunesExt.Author, podcast.Author),
|
||||
Album: podcast.Title,
|
||||
}
|
||||
}
|
||||
@@ -516,13 +508,6 @@ func (p *Podcasts) doPodcastDownload(podcast *db.Podcast, podcastEpisode *db.Pod
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
defer func() {
|
||||
if err != nil {
|
||||
podcastEpisode.Status = db.PodcastEpisodeStatusError
|
||||
_ = p.db.Save(podcastEpisode).Error
|
||||
}
|
||||
}()
|
||||
|
||||
if resp.StatusCode/100 != 2 {
|
||||
return fmt.Errorf("fetch podcast audio: unexpected status %s", resp.Status)
|
||||
}
|
||||
@@ -544,6 +529,13 @@ func (p *Podcasts) doPodcastDownload(podcast *db.Podcast, podcastEpisode *db.Pod
|
||||
}
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -188,7 +188,6 @@ func (s *Scanner) ExecuteWatch(ctx context.Context) error {
|
||||
case event := <-watcher.Events:
|
||||
if event.Op&(fsnotify.Remove) == fsnotify.Remove {
|
||||
batchClean = true
|
||||
batchT.Reset(batchInterval)
|
||||
break
|
||||
}
|
||||
if event.Op&(fsnotify.Create|fsnotify.Write) == 0 {
|
||||
@@ -570,7 +569,6 @@ func populateTrack(tx *db.DB, scanEmbeddedCover bool, album *db.Album, track *db
|
||||
track.TagTrackNumber = tags.ParseInt(normtag.Get(trags, normtag.TrackNumber))
|
||||
track.TagDiscNumber = tags.ParseInt(normtag.Get(trags, normtag.DiscNumber))
|
||||
track.TagBrainzID = normtag.Get(trags, normtag.MusicBrainzRecordingID)
|
||||
track.TagYear = tags.MustYear(trags)
|
||||
|
||||
track.ReplayGainTrackGain = tags.ParseDB(normtag.Get(trags, normtag.ReplayGainTrackGain))
|
||||
track.ReplayGainTrackPeak = tags.ParseFloat(normtag.Get(trags, normtag.ReplayGainTrackPeak))
|
||||
|
||||
@@ -27,7 +27,6 @@ import (
|
||||
"go.senan.xyz/gonic/db"
|
||||
"go.senan.xyz/gonic/handlerutil"
|
||||
"go.senan.xyz/gonic/lastfm"
|
||||
"go.senan.xyz/gonic/ldap"
|
||||
"go.senan.xyz/gonic/podcast"
|
||||
"go.senan.xyz/gonic/scanner"
|
||||
"go.senan.xyz/gonic/server/ctrladmin/adminui"
|
||||
@@ -49,13 +48,11 @@ type Controller struct {
|
||||
podcasts *podcast.Podcasts
|
||||
lastfmClient *lastfm.Client
|
||||
resolveProxyPath ProxyPathResolver
|
||||
ldapConfig ldap.Config
|
||||
ldapStore ldap.LDAPStore
|
||||
}
|
||||
|
||||
type ProxyPathResolver func(in string) string
|
||||
|
||||
func New(dbc *db.DB, sessDB *gormstore.Store, scanner *scanner.Scanner, podcasts *podcast.Podcasts, lastfmClient *lastfm.Client, resolveProxyPath ProxyPathResolver, ldapConfig ldap.Config, ldapStore ldap.LDAPStore) (*Controller, error) {
|
||||
func New(dbc *db.DB, sessDB *gormstore.Store, scanner *scanner.Scanner, podcasts *podcast.Podcasts, lastfmClient *lastfm.Client, resolveProxyPath ProxyPathResolver) (*Controller, error) {
|
||||
c := Controller{
|
||||
ServeMux: http.NewServeMux(),
|
||||
|
||||
@@ -65,8 +62,6 @@ func New(dbc *db.DB, sessDB *gormstore.Store, scanner *scanner.Scanner, podcasts
|
||||
podcasts: podcasts,
|
||||
lastfmClient: lastfmClient,
|
||||
resolveProxyPath: resolveProxyPath,
|
||||
ldapConfig: ldapConfig,
|
||||
ldapStore: ldapStore,
|
||||
}
|
||||
|
||||
resp := respHandler(adminui.TemplatesFS, resolveProxyPath)
|
||||
|
||||
@@ -1,48 +1,28 @@
|
||||
package ctrladmin
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"github.com/gorilla/sessions"
|
||||
"go.senan.xyz/gonic/ldap"
|
||||
)
|
||||
|
||||
func (c *Controller) ServeLoginDo(w http.ResponseWriter, r *http.Request) {
|
||||
session := r.Context().Value(CtxSession).(*sessions.Session)
|
||||
username := r.FormValue("username")
|
||||
password := r.FormValue("password")
|
||||
user := c.dbc.GetUserByName(username)
|
||||
if username == "" || password == "" {
|
||||
sessAddFlashW(session, []string{"please provide username and password"})
|
||||
sessLogSave(session, w, r)
|
||||
http.Redirect(w, r, r.Referer(), http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
|
||||
if c.ldapConfig.IsSetup() {
|
||||
ok, err := ldap.CheckLDAPcreds(username, password, c.dbc, c.ldapConfig, c.ldapStore)
|
||||
if err != nil {
|
||||
log.Println("Failed to check LDAP credentials:", err)
|
||||
sessAddFlashW(session, []string{"failed to check LDAP credentials"})
|
||||
sessLogSave(session, w, r)
|
||||
http.Redirect(w, r, r.Referer(), http.StatusSeeOther)
|
||||
return
|
||||
} else if !ok {
|
||||
user := c.dbc.GetUserByName(username)
|
||||
if user == nil || password != user.Password {
|
||||
sessAddFlashW(session, []string{"invalid username / password"})
|
||||
sessLogSave(session, w, r)
|
||||
http.Redirect(w, r, r.Referer(), http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
} else if user == nil || user.Password != password {
|
||||
sessAddFlashW(session, []string{"invalid username / password"})
|
||||
sessLogSave(session, w, r)
|
||||
http.Redirect(w, r, r.Referer(), http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
|
||||
user = c.dbc.GetUserByName(username)
|
||||
|
||||
// put the user name into the session. future endpoints after this one
|
||||
// are wrapped with WithUserSession() which will get the name from the
|
||||
// session and put the row into the request context
|
||||
|
||||
@@ -10,7 +10,6 @@ import (
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"go.senan.xyz/gonic/db"
|
||||
@@ -19,7 +18,6 @@ import (
|
||||
"go.senan.xyz/gonic/infocache/artistinfocache"
|
||||
"go.senan.xyz/gonic/jukebox"
|
||||
"go.senan.xyz/gonic/lastfm"
|
||||
"go.senan.xyz/gonic/ldap"
|
||||
"go.senan.xyz/gonic/playlist"
|
||||
"go.senan.xyz/gonic/podcast"
|
||||
"go.senan.xyz/gonic/scanner"
|
||||
@@ -58,6 +56,7 @@ type Controller struct {
|
||||
dbc *db.DB
|
||||
scanner *scanner.Scanner
|
||||
musicPaths []MusicPath
|
||||
defaultMusicPath string
|
||||
podcastsPath string
|
||||
cacheAudioPath string
|
||||
cacheCoverPath string
|
||||
@@ -74,13 +73,14 @@ type Controller struct {
|
||||
resolveProxyPath ProxyPathResolver
|
||||
}
|
||||
|
||||
func New(dbc *db.DB, scannr *scanner.Scanner, musicPaths []MusicPath, podcastsPath string, cacheAudioPath string, cacheCoverPath string, jukebox *jukebox.Jukebox, playlistStore *playlist.Store, scrobblers []scrobble.Scrobbler, podcasts *podcast.Podcasts, transcoder transcode.Transcoder, lastFMClient *lastfm.Client, artistInfoCache *artistinfocache.ArtistInfoCache, albumInfoCache *albuminfocache.AlbumInfoCache, tagReader tags.Reader, resolveProxyPath ProxyPathResolver, ldapConfig ldap.Config, ldapStore ldap.LDAPStore) (*Controller, error) {
|
||||
func New(dbc *db.DB, scannr *scanner.Scanner, musicPaths []MusicPath, defaultMusicPath string, podcastsPath string, cacheAudioPath string, cacheCoverPath string, jukebox *jukebox.Jukebox, playlistStore *playlist.Store, scrobblers []scrobble.Scrobbler, podcasts *podcast.Podcasts, transcoder transcode.Transcoder, lastFMClient *lastfm.Client, artistInfoCache *artistinfocache.ArtistInfoCache, albumInfoCache *albuminfocache.AlbumInfoCache, tagReader tags.Reader, resolveProxyPath ProxyPathResolver) (*Controller, error) {
|
||||
c := Controller{
|
||||
ServeMux: http.NewServeMux(),
|
||||
|
||||
dbc: dbc,
|
||||
scanner: scannr,
|
||||
musicPaths: musicPaths,
|
||||
defaultMusicPath: defaultMusicPath,
|
||||
podcastsPath: podcastsPath,
|
||||
cacheAudioPath: cacheAudioPath,
|
||||
cacheCoverPath: cacheCoverPath,
|
||||
@@ -100,7 +100,7 @@ func New(dbc *db.DB, scannr *scanner.Scanner, musicPaths []MusicPath, podcastsPa
|
||||
chain := handlerutil.Chain(
|
||||
withParams,
|
||||
withRequiredParams,
|
||||
withUser(dbc, ldapConfig, ldapStore),
|
||||
withUser(dbc),
|
||||
)
|
||||
chainRaw := handlerutil.Chain(
|
||||
chain,
|
||||
@@ -231,82 +231,39 @@ func withRequiredParams(next http.Handler) http.Handler {
|
||||
})
|
||||
}
|
||||
|
||||
func withUser(dbc *db.DB, ldapConfig ldap.Config, ldapStore ldap.LDAPStore) handlerutil.Middleware {
|
||||
func withUser(dbc *db.DB) handlerutil.Middleware {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
params := r.Context().Value(CtxParams).(params.Params)
|
||||
// ignoring errors here, a middleware has already ensured they exist
|
||||
username, _ := params.Get("u")
|
||||
passwordHex, _ := params.Get("p")
|
||||
password, _ := params.Get("p")
|
||||
token, _ := params.Get("t")
|
||||
salt, _ := params.Get("s")
|
||||
|
||||
passwordAuth := token == "" && salt == ""
|
||||
tokenAuth := passwordHex == ""
|
||||
tokenAuth := password == ""
|
||||
if tokenAuth == passwordAuth {
|
||||
_ = writeResp(w, r, spec.NewError(10,
|
||||
"please provide `t` and `s`, or just `p`"))
|
||||
return
|
||||
}
|
||||
|
||||
var password string
|
||||
if passwordAuth && passwordHex != "" {
|
||||
if strings.HasPrefix(passwordHex, "enc:") {
|
||||
raw := strings.TrimPrefix(passwordHex, "enc:")
|
||||
decoded, err := hex.DecodeString(raw)
|
||||
if err != nil {
|
||||
log.Println("Failed to decode hex password:", err)
|
||||
_ = writeResp(w, r, spec.NewError(40, "invalid password encoding"))
|
||||
return
|
||||
}
|
||||
password = string(decoded)
|
||||
} else {
|
||||
// if not prefixed with "enc:", treat as plain text
|
||||
password = passwordHex
|
||||
}
|
||||
}
|
||||
|
||||
user := dbc.GetUserByName(username)
|
||||
|
||||
if ldapConfig.IsSetup() {
|
||||
// Complete auth using LDAP
|
||||
log.Println("Authenticating using LDAP ...")
|
||||
|
||||
ok, err := ldap.CheckLDAPcreds(username, password, dbc, ldapConfig, ldapStore)
|
||||
if err != nil {
|
||||
log.Println("Failed to check LDAP creds:", err)
|
||||
_ = writeResp(w, r, spec.NewError(40, "invalid password"))
|
||||
return
|
||||
}
|
||||
|
||||
if !ok {
|
||||
_ = writeResp(w, r, spec.NewError(40, "invalid password"))
|
||||
return
|
||||
}
|
||||
|
||||
withUser := context.WithValue(r.Context(), CtxUser, user)
|
||||
next.ServeHTTP(w, r.WithContext(withUser))
|
||||
return
|
||||
}
|
||||
|
||||
log.Println("Authenticating using built-in ...")
|
||||
if user == nil {
|
||||
_ = writeResp(w, r, spec.NewError(40, "invalid password"))
|
||||
_ = writeResp(w, r, spec.NewError(40,
|
||||
"invalid username %q", username))
|
||||
return
|
||||
}
|
||||
|
||||
var credsOk bool
|
||||
if tokenAuth {
|
||||
credsOk = checkCredsToken(user.Password, token, salt)
|
||||
} else {
|
||||
credsOk = checkCredsBasic(user.Password, password)
|
||||
}
|
||||
|
||||
if !credsOk {
|
||||
_ = writeResp(w, r, spec.NewError(40, "invalid password"))
|
||||
return
|
||||
}
|
||||
|
||||
withUser := context.WithValue(r.Context(), CtxUser, user)
|
||||
next.ServeHTTP(w, r.WithContext(withUser))
|
||||
})
|
||||
|
||||
@@ -25,7 +25,7 @@ func (c *Controller) ServeGetIndexes(r *http.Request) *spec.Response {
|
||||
Select("id").
|
||||
Model(&db.Album{}).
|
||||
Where("parent_id IS NULL")
|
||||
if m := getMusicFolder(c.musicPaths, params); m != "" {
|
||||
if m := getMusicFolder(c, params); m != "" {
|
||||
rootQ = rootQ.
|
||||
Where("root_dir=?", m)
|
||||
}
|
||||
@@ -170,7 +170,7 @@ func (c *Controller) ServeGetAlbumList(r *http.Request) *spec.Response {
|
||||
return spec.NewError(10, "unknown value %q for parameter 'type'", v)
|
||||
}
|
||||
|
||||
if m := getMusicFolder(c.musicPaths, params); m != "" {
|
||||
if m := getMusicFolder(c, params); m != "" {
|
||||
q = q.Where("root_dir=?", m)
|
||||
}
|
||||
var folders []*db.Album
|
||||
@@ -220,7 +220,7 @@ func (c *Controller) ServeSearchTwo(r *http.Request) *spec.Response {
|
||||
Select("id").
|
||||
Model(&db.Album{}).
|
||||
Where("parent_id IS NULL")
|
||||
if m := getMusicFolder(c.musicPaths, params); m != "" {
|
||||
if m := getMusicFolder(c, params); m != "" {
|
||||
rootQ = rootQ.Where("root_dir=?", m)
|
||||
}
|
||||
|
||||
@@ -261,7 +261,7 @@ func (c *Controller) ServeSearchTwo(r *http.Request) *spec.Response {
|
||||
Preload("AlbumRating", "user_id=?", user.ID).
|
||||
Offset(params.GetOrInt("albumOffset", 0)).
|
||||
Limit(params.GetOrInt("albumCount", 20))
|
||||
if m := getMusicFolder(c.musicPaths, params); m != "" {
|
||||
if m := getMusicFolder(c, params); m != "" {
|
||||
q = q.Where("root_dir=?", m)
|
||||
}
|
||||
if err := q.Find(&albums).Error; err != nil {
|
||||
@@ -287,7 +287,7 @@ func (c *Controller) ServeSearchTwo(r *http.Request) *spec.Response {
|
||||
Preload("TrackRating", "user_id=?", user.ID).
|
||||
Offset(params.GetOrInt("songOffset", 0)).
|
||||
Limit(params.GetOrInt("songCount", 20))
|
||||
if m := getMusicFolder(c.musicPaths, params); m != "" {
|
||||
if m := getMusicFolder(c, params); m != "" {
|
||||
q = q.
|
||||
Joins("JOIN albums ON albums.id=tracks.album_id").
|
||||
Where("albums.root_dir=?", m)
|
||||
@@ -320,44 +320,56 @@ func (c *Controller) ServeGetStarred(r *http.Request) *spec.Response {
|
||||
results := &spec.Starred{}
|
||||
|
||||
// "artists"
|
||||
rootQ := c.dbc.
|
||||
Select("id").
|
||||
Model(&db.Album{}).
|
||||
Where("parent_id IS NULL")
|
||||
if m := getMusicFolder(c.musicPaths, params); m != "" {
|
||||
rootQ = rootQ.Where("root_dir=?", m)
|
||||
}
|
||||
|
||||
var artists []*db.Album
|
||||
var artists []*db.Artist
|
||||
q := c.dbc.
|
||||
Where(`parent_id IN ?`, rootQ.SubQuery()).
|
||||
Joins("JOIN album_stars ON albums.id=album_stars.album_id").
|
||||
Where("album_stars.user_id=?", user.ID).
|
||||
Preload("AlbumStar", "user_id=?", user.ID).
|
||||
Preload("AlbumRating", "user_id=?", user.ID)
|
||||
Select("artists.*, count(albums.id) album_count").
|
||||
Joins("JOIN artist_stars ON artist_stars.artist_id=artists.id").
|
||||
Where("artist_stars.user_id=?", user.ID).
|
||||
Joins("JOIN artist_appearances ON artist_appearances.artist_id=artists.id").
|
||||
Joins("JOIN albums ON albums.id=artist_appearances.album_id").
|
||||
Order("artist_stars.star_date DESC").
|
||||
Preload("ArtistStar", "user_id=?", user.ID).
|
||||
Preload("ArtistRating", "user_id=?", user.ID).
|
||||
Preload("Info").
|
||||
Group("artists.id")
|
||||
if m := getMusicFolder(c, params); m != "" {
|
||||
q = q.Where("albums.root_dir=?", m)
|
||||
}
|
||||
if err := q.Find(&artists).Error; err != nil {
|
||||
return spec.NewError(0, "find artists: %v", err)
|
||||
}
|
||||
for _, a := range artists {
|
||||
results.Artists = append(results.Artists, spec.NewDirectoryByFolder(a, nil))
|
||||
results.Artists = append(results.Artists, spec.NewArtistByTags(a))
|
||||
}
|
||||
|
||||
// "albums"
|
||||
var albums []*db.Album
|
||||
q = c.dbc.
|
||||
Joins("JOIN album_artists ON album_artists.album_id=albums.id").
|
||||
Joins("JOIN album_stars ON albums.id=album_stars.album_id").
|
||||
Where("album_stars.user_id=?", user.ID).
|
||||
q = c.dbc.Where("parent_id IS NOT NULL").
|
||||
Joins("JOIN album_stars ON albums.id=album_stars.album_id AND album_stars.user_id=?", user.ID)
|
||||
q = q.Order("album_stars.star_date DESC")
|
||||
|
||||
q = q.
|
||||
Preload("AlbumStar", "user_id=?", user.ID).
|
||||
Preload("AlbumRating", "user_id=?", user.ID)
|
||||
if m := getMusicFolder(c.musicPaths, params); m != "" {
|
||||
|
||||
if m := getMusicFolder(c, params); m != "" {
|
||||
q = q.Where("root_dir=?", m)
|
||||
}
|
||||
|
||||
q.
|
||||
Select("albums.*, count(tracks.id) child_count, sum(tracks.length) duration").
|
||||
Joins("LEFT JOIN tracks ON tracks.album_id=albums.id").
|
||||
Group("albums.id").
|
||||
Joins("JOIN album_artists ON album_artists.album_id=albums.id").
|
||||
Preload("Parent").
|
||||
Preload("AlbumStar", "user_id=?", user.ID).
|
||||
Preload("AlbumRating", "user_id=?", user.ID)
|
||||
|
||||
if err := q.Find(&albums).Error; err != nil {
|
||||
return spec.NewError(0, "find albums: %v", err)
|
||||
}
|
||||
for _, a := range albums {
|
||||
results.Albums = append(results.Albums, spec.NewTCAlbumByFolder(a))
|
||||
results.Albums = append(results.Albums, spec.NewAlbumByFolder(a))
|
||||
}
|
||||
|
||||
// tracks
|
||||
@@ -369,7 +381,7 @@ func (c *Controller) ServeGetStarred(r *http.Request) *spec.Response {
|
||||
Preload("Artists").
|
||||
Preload("TrackStar", "user_id=?", user.ID).
|
||||
Preload("TrackRating", "user_id=?", user.ID)
|
||||
if m := getMusicFolder(c.musicPaths, params); m != "" {
|
||||
if m := getMusicFolder(c, params); m != "" {
|
||||
q = q.
|
||||
Joins("JOIN albums ON albums.id=tracks.album_id").
|
||||
Where("albums.root_dir=?", m)
|
||||
|
||||
@@ -28,12 +28,13 @@ func (c *Controller) ServeGetArtists(r *http.Request) *spec.Response {
|
||||
q := c.dbc.
|
||||
Select("*, count(album_artists.album_id) album_count").
|
||||
Joins("JOIN album_artists ON album_artists.artist_id=artists.id").
|
||||
Joins("LEFT JOIN artist_stars ON artist_stars.artist_id=artists.id").
|
||||
Preload("ArtistStar", "user_id=?", user.ID).
|
||||
Preload("ArtistRating", "user_id=?", user.ID).
|
||||
Preload("Info").
|
||||
Group("artists.id").
|
||||
Order("artists.name COLLATE NOCASE")
|
||||
if m := getMusicFolder(c.musicPaths, params); m != "" {
|
||||
if m := getMusicFolder(c, params); m != "" {
|
||||
q = q.
|
||||
Joins("JOIN albums ON albums.id=album_artists.album_id").
|
||||
Where("albums.root_dir=?", m)
|
||||
@@ -186,7 +187,7 @@ func (c *Controller) ServeGetAlbumListTwo(r *http.Request) *spec.Response {
|
||||
default:
|
||||
return spec.NewError(10, "unknown value %q for parameter 'type'", listType)
|
||||
}
|
||||
if m := getMusicFolder(c.musicPaths, params); m != "" {
|
||||
if m := getMusicFolder(c, params); m != "" {
|
||||
q = q.Where("root_dir=?", m)
|
||||
}
|
||||
var albums []*db.Album
|
||||
@@ -254,7 +255,7 @@ func (c *Controller) ServeSearchThree(r *http.Request) *spec.Response {
|
||||
Preload("Info").
|
||||
Offset(params.GetOrInt("artistOffset", 0)).
|
||||
Limit(params.GetOrInt("artistCount", 20))
|
||||
if m := getMusicFolder(c.musicPaths, params); m != "" {
|
||||
if m := getMusicFolder(c, params); m != "" {
|
||||
q = q.Where("albums.root_dir=?", m)
|
||||
}
|
||||
if err := q.Find(&artists).Error; err != nil {
|
||||
@@ -283,7 +284,7 @@ func (c *Controller) ServeSearchThree(r *http.Request) *spec.Response {
|
||||
q = q.
|
||||
Offset(params.GetOrInt("albumOffset", 0)).
|
||||
Limit(params.GetOrInt("albumCount", 20))
|
||||
if m := getMusicFolder(c.musicPaths, params); m != "" {
|
||||
if m := getMusicFolder(c, params); m != "" {
|
||||
q = q.Where("root_dir=?", m)
|
||||
}
|
||||
if err := q.Find(&albums).Error; err != nil {
|
||||
@@ -311,7 +312,7 @@ func (c *Controller) ServeSearchThree(r *http.Request) *spec.Response {
|
||||
}
|
||||
q = q.Offset(params.GetOrInt("songOffset", 0)).
|
||||
Limit(params.GetOrInt("songCount", 20))
|
||||
if m := getMusicFolder(c.musicPaths, params); m != "" {
|
||||
if m := getMusicFolder(c, params); m != "" {
|
||||
q = q.
|
||||
Joins("JOIN albums ON albums.id=tracks.album_id").
|
||||
Where("albums.root_dir=?", m)
|
||||
@@ -482,7 +483,7 @@ func (c *Controller) ServeGetSongsByGenre(r *http.Request) *spec.Response {
|
||||
Preload("TrackRating", "user_id=?", user.ID).
|
||||
Offset(params.GetOrInt("offset", 0)).
|
||||
Limit(params.GetOrInt("count", 10))
|
||||
if m := getMusicFolder(c.musicPaths, params); m != "" {
|
||||
if m := getMusicFolder(c, params); m != "" {
|
||||
q = q.Where("albums.root_dir=?", m)
|
||||
}
|
||||
q = q.Group("tracks.id")
|
||||
@@ -523,7 +524,7 @@ func (c *Controller) ServeGetStarredTwo(r *http.Request) *spec.Response {
|
||||
Preload("ArtistRating", "user_id=?", user.ID).
|
||||
Preload("Info").
|
||||
Group("artists.id")
|
||||
if m := getMusicFolder(c.musicPaths, params); m != "" {
|
||||
if m := getMusicFolder(c, params); m != "" {
|
||||
q = q.Where("albums.root_dir=?", m)
|
||||
}
|
||||
if err := q.Find(&artists).Error; err != nil {
|
||||
@@ -544,7 +545,7 @@ func (c *Controller) ServeGetStarredTwo(r *http.Request) *spec.Response {
|
||||
Preload("AlbumStar", "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, params); m != "" {
|
||||
q = q.Where("albums.root_dir=?", m)
|
||||
}
|
||||
if err := q.Find(&albums).Error; err != nil {
|
||||
@@ -565,7 +566,7 @@ func (c *Controller) ServeGetStarredTwo(r *http.Request) *spec.Response {
|
||||
Preload("Artists").
|
||||
Preload("TrackStar", "user_id=?", user.ID).
|
||||
Preload("TrackRating", "user_id=?", user.ID)
|
||||
if m := getMusicFolder(c.musicPaths, params); m != "" {
|
||||
if m := getMusicFolder(c, params); m != "" {
|
||||
q = q.
|
||||
Joins("JOIN albums ON albums.id=tracks.album_id").
|
||||
Where("albums.root_dir=?", m)
|
||||
|
||||
@@ -100,7 +100,7 @@ func (c *Controller) ServeScrobble(r *http.Request) *spec.Response {
|
||||
return spec.NewError(0, "error updating stats: %v", err)
|
||||
}
|
||||
default:
|
||||
return spec.NewError(0, "can't scrobble type %s", id.Type)
|
||||
return spec.NewError(10, "can't scrobble type %s", id.Type)
|
||||
}
|
||||
|
||||
if scrobbleTrack.Track == "" {
|
||||
@@ -334,7 +334,7 @@ func (c *Controller) ServeGetRandomSongs(r *http.Request) *spec.Response {
|
||||
q = q.Joins("JOIN track_genres ON track_genres.track_id=tracks.id")
|
||||
q = q.Joins("JOIN genres ON genres.id=track_genres.genre_id AND genres.name=?", genre)
|
||||
}
|
||||
if m := getMusicFolder(c.musicPaths, params); m != "" {
|
||||
if m := getMusicFolder(c, params); m != "" {
|
||||
q = q.Where("albums.root_dir=?", m)
|
||||
}
|
||||
if err := q.Find(&tracks).Error; err != nil {
|
||||
@@ -777,10 +777,11 @@ func scrobbleStatsUpdatePodcastEpisode(dbc *db.DB, peID int) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func getMusicFolder(musicPaths []MusicPath, p params.Params) string {
|
||||
func getMusicFolder(c *Controller, p params.Params) string {
|
||||
musicPaths := c.musicPaths
|
||||
idx, err := p.GetInt("musicFolderId")
|
||||
if err != nil {
|
||||
return ""
|
||||
return c.defaultMusicPath
|
||||
}
|
||||
if idx < 0 || idx >= len(musicPaths) {
|
||||
return os.DevNull
|
||||
|
||||
@@ -14,13 +14,10 @@ import (
|
||||
func (c *Controller) ServeGetPodcasts(r *http.Request) *spec.Response {
|
||||
params := r.Context().Value(CtxParams).(params.Params)
|
||||
isIncludeEpisodes := params.GetOrBool("includeEpisodes", true)
|
||||
id, err := params.GetID("id")
|
||||
if err != nil {
|
||||
return spec.NewError(10, "failed get podcast(s): %s", err)
|
||||
}
|
||||
id, _ := params.GetID("id")
|
||||
podcasts, err := c.podcasts.GetPodcastOrAll(id.Value, isIncludeEpisodes)
|
||||
if err != nil {
|
||||
return spec.NewError(70, "failed get podcast(s): %s", err)
|
||||
return spec.NewError(10, "failed get podcast(s): %s", err)
|
||||
}
|
||||
sub := spec.NewResponse()
|
||||
sub.Podcasts = &spec.Podcasts{}
|
||||
@@ -36,7 +33,7 @@ func (c *Controller) ServeGetNewestPodcasts(r *http.Request) *spec.Response {
|
||||
count := params.GetOrInt("count", 10)
|
||||
episodes, err := c.podcasts.GetNewestPodcastEpisodes(count)
|
||||
if err != nil {
|
||||
return spec.NewError(0, "failed get podcast(s): %s", err)
|
||||
return spec.NewError(10, "failed get podcast(s): %s", err)
|
||||
}
|
||||
sub := spec.NewResponse()
|
||||
sub.NewestPodcasts = &spec.NewestPodcasts{}
|
||||
@@ -53,7 +50,7 @@ func (c *Controller) ServeDownloadPodcastEpisode(r *http.Request) *spec.Response
|
||||
return spec.NewError(10, "please provide a valid podcast episode id")
|
||||
}
|
||||
if err := c.podcasts.DownloadEpisode(id.Value); err != nil {
|
||||
return spec.NewError(0, "failed to download episode: %s", err)
|
||||
return spec.NewError(10, "failed to download episode: %s", err)
|
||||
}
|
||||
return spec.NewResponse()
|
||||
}
|
||||
@@ -68,10 +65,10 @@ func (c *Controller) ServeCreatePodcastChannel(r *http.Request) *spec.Response {
|
||||
fp := gofeed.NewParser()
|
||||
feed, err := fp.ParseURL(rssURL)
|
||||
if err != nil {
|
||||
return spec.NewError(0, "failed to parse feed: %s", err)
|
||||
return spec.NewError(10, "failed to parse feed: %s", err)
|
||||
}
|
||||
if _, err = c.podcasts.AddNewPodcast(rssURL, feed); err != nil {
|
||||
return spec.NewError(0, "failed to add feed: %s", err)
|
||||
return spec.NewError(10, "failed to add feed: %s", err)
|
||||
}
|
||||
return spec.NewResponse()
|
||||
}
|
||||
@@ -82,7 +79,7 @@ func (c *Controller) ServeRefreshPodcasts(r *http.Request) *spec.Response {
|
||||
return spec.NewError(50, "user not admin")
|
||||
}
|
||||
if err := c.podcasts.RefreshPodcasts(); err != nil {
|
||||
return spec.NewError(0, "failed to refresh feeds: %s", err)
|
||||
return spec.NewError(10, "failed to refresh feeds: %s", err)
|
||||
}
|
||||
return spec.NewResponse()
|
||||
}
|
||||
@@ -98,7 +95,7 @@ func (c *Controller) ServeDeletePodcastChannel(r *http.Request) *spec.Response {
|
||||
return spec.NewError(10, "please provide a valid podcast id")
|
||||
}
|
||||
if err := c.podcasts.DeletePodcast(id.Value); err != nil {
|
||||
return spec.NewError(70, "failed to delete podcast: %s", err)
|
||||
return spec.NewError(10, "failed to delete podcast: %s", err)
|
||||
}
|
||||
return spec.NewResponse()
|
||||
}
|
||||
@@ -114,7 +111,7 @@ func (c *Controller) ServeDeletePodcastEpisode(r *http.Request) *spec.Response {
|
||||
return spec.NewError(10, "please provide a valid podcast episode id")
|
||||
}
|
||||
if err := c.podcasts.DeletePodcastEpisode(id.Value); err != nil {
|
||||
return spec.NewError(70, "failed to delete podcast: %s", err)
|
||||
return spec.NewError(10, "failed to delete podcast: %s", err)
|
||||
}
|
||||
return spec.NewResponse()
|
||||
}
|
||||
@@ -82,7 +82,7 @@ func (c *Controller) ServeGetCoverArt(w http.ResponseWriter, r *http.Request) *s
|
||||
|
||||
reader, err := coverFor(c.dbc, c.artistInfoCache, c.playlistStore, c.tagReader, id)
|
||||
if err != nil {
|
||||
return spec.NewError(70, "couldn't find cover %q: %v", id, err)
|
||||
return spec.NewError(10, "couldn't find cover %q: %v", id, err)
|
||||
}
|
||||
defer reader.Close()
|
||||
|
||||
@@ -107,7 +107,7 @@ func (c *Controller) ServeGetCoverArt(w http.ResponseWriter, r *http.Request) *s
|
||||
resized := imaging.Fit(img, minSize, minSize, imaging.Lanczos)
|
||||
|
||||
if err := imaging.Save(resized, cachePath); err != nil {
|
||||
return spec.NewError(0, "saving cover %q: %v", id, err)
|
||||
return spec.NewError(10, "saving cover %q: %v", id, err)
|
||||
}
|
||||
|
||||
serve(cachePath)
|
||||
|
||||
@@ -6,14 +6,22 @@ import (
|
||||
"sort"
|
||||
|
||||
"go.senan.xyz/gonic/db"
|
||||
"go.senan.xyz/gonic/server/ctrlsubsonic/specid"
|
||||
)
|
||||
|
||||
func NewAlbumByFolder(f *db.Album) *Album {
|
||||
artist := ""
|
||||
var parentSID *specid.ID
|
||||
if f.Parent != nil {
|
||||
artist = f.Parent.RightPath
|
||||
parentSID = f.ParentSID()
|
||||
}
|
||||
|
||||
a := &Album{
|
||||
Artist: f.Parent.RightPath,
|
||||
Artist: artist,
|
||||
ID: f.SID(),
|
||||
IsDir: true,
|
||||
ParentID: f.ParentSID(),
|
||||
ParentID: parentSID,
|
||||
Album: f.RightPath,
|
||||
Name: f.RightPath,
|
||||
Title: f.RightPath,
|
||||
@@ -79,13 +87,13 @@ func NewTCTrackByFolder(t *db.Track, parent *db.Album) *TrackChild {
|
||||
),
|
||||
ParentID: parent.SID(),
|
||||
Duration: t.Length,
|
||||
Year: parent.TagYear,
|
||||
Bitrate: t.Bitrate,
|
||||
IsDir: false,
|
||||
Type: "music",
|
||||
MusicBrainzID: t.TagBrainzID,
|
||||
CreatedAt: t.CreatedAt,
|
||||
AverageRating: formatRating(t.AverageRating),
|
||||
Year: t.TagYear,
|
||||
}
|
||||
if trCh.Title == "" {
|
||||
trCh.Title = t.Filename
|
||||
|
||||
@@ -97,9 +97,9 @@ func NewTrackByTags(t *db.Track, album *db.Album) *TrackChild {
|
||||
DiscNumber: t.TagDiscNumber,
|
||||
Type: "music",
|
||||
MusicBrainzID: t.TagBrainzID,
|
||||
Year: album.TagYear,
|
||||
AverageRating: formatRating(t.AverageRating),
|
||||
TranscodeMeta: TranscodeMeta{},
|
||||
Year: t.TagYear,
|
||||
}
|
||||
|
||||
switch {
|
||||
|
||||
@@ -442,8 +442,8 @@ type Bookmark struct {
|
||||
}
|
||||
|
||||
type Starred struct {
|
||||
Artists []*Directory `xml:"artist,omitempty" json:"artist,omitempty"`
|
||||
Albums []*TrackChild `xml:"album,omitempty" json:"album,omitempty"`
|
||||
Artists []*Artist `xml:"artist,omitempty" json:"artist,omitempty"`
|
||||
Albums []*Album `xml:"album,omitempty" json:"album,omitempty"`
|
||||
Tracks []*TrackChild `xml:"song,omitempty" json:"song,omitempty"`
|
||||
}
|
||||
|
||||
@@ -473,7 +473,7 @@ type InternetRadioStation struct {
|
||||
ID *specid.ID `xml:"id,attr" json:"id"`
|
||||
Name string `xml:"name,attr" json:"name"`
|
||||
StreamURL string `xml:"streamUrl,attr" json:"streamUrl"`
|
||||
HomepageURL string `xml:"homePageUrl,attr" json:"homePageUrl"`
|
||||
HomepageURL string `xml:"homepageUrl,attr" json:"homepageUrl"`
|
||||
}
|
||||
|
||||
type Lyrics struct {
|
||||
|
||||
Reference in New Issue
Block a user