diff --git a/.github/workflows/nightly-release.yaml b/.github/workflows/nightly-release.yaml
index 66535d7..d5bf63d 100644
--- a/.github/workflows/nightly-release.yaml
+++ b/.github/workflows/nightly-release.yaml
@@ -23,7 +23,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout
- uses: actions/checkout@v2
+ uses: actions/checkout@v3
- name: Setup Go
uses: actions/setup-go@v4
with:
diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml
index 290ad6b..5edd1ad 100644
--- a/.github/workflows/release.yaml
+++ b/.github/workflows/release.yaml
@@ -9,7 +9,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout
- uses: actions/checkout@v2
+ uses: actions/checkout@v3
- name: Setup Go
uses: actions/setup-go@v4
with:
@@ -80,3 +80,15 @@ jobs:
ghcr.io/${{ github.repository }}:latest
${{ github.repository }}:${{ needs.release-please.outputs.tag_name }}
${{ github.repository }}:latest
+ notify-irc:
+ needs: [release-please]
+ name: Notify IRC
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@v3
+ - name: Notify
+ run: |
+ set +x e
+ git log -1 --pretty="push to master (@%an) %s" | curl "${{ secrets.IRC_NOTIFY_URL }}" -F target=#gonic -F message=@- >/dev/null 2>&1
+ exit 0
diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml
index 5fbd661..bb25da4 100644
--- a/.github/workflows/test.yaml
+++ b/.github/workflows/test.yaml
@@ -10,7 +10,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout
- uses: actions/checkout@v2
+ uses: actions/checkout@v3
- name: Setup Go
uses: actions/setup-go@v4
with:
diff --git a/.gitignore b/.gitignore
index 9054528..ace40cd 100644
--- a/.gitignore
+++ b/.gitignore
@@ -2,17 +2,11 @@
*db-wal
*db-shm
*.sql
-cmd/scanner/scanner
-cmd/server/server
-cmd/scanner/main
-cmd/server/main
*_bytes.go
_test*
dist
*.sql
-gonic
-gonicscan
-gonicembed
+./gonic
.devcontainer
.vscode
*.swp
diff --git a/.golangci.yml b/.golangci.yml
index 35faffd..6e4119b 100644
--- a/.golangci.yml
+++ b/.golangci.yml
@@ -6,28 +6,72 @@ run:
linters:
disable-all: true
enable:
+ - asasalint
+ - asciicheck
+ - bidichk
- bodyclose
+ - containedctx
+ - decorder
- dogsled
+ - dupword
+ - durationcheck
- errcheck
+ - errchkjson
+ - errname
+ - errorlint
+ - execinquery
- exportloopref
+ - forbidigo
+ - ginkgolinter
+ - gocheckcompilerdirectives
- gochecknoglobals
- gochecknoinits
- goconst
- gocritic
- gocyclo
+ - gofmt
+ - gofumpt
+ - goheader
+ - goimports
+ - gomoddirectives
+ - gomodguard
- goprintffuncname
- gosec
- gosimple
+ - gosmopolitan
- govet
+ - grouper
+ - importas
- ineffassign
+ - loggercheck
+ - makezero
+ - mirror
- misspell
+ - musttag
- nakedret
+ - nestif
+ - nilerr
+ - nosprintfhostport
+ - paralleltest
+ - predeclared
+ - promlinter
+ - reassign
- revive
- rowserrcheck
+ - sqlclosecheck
- staticcheck
- stylecheck
+ - tenv
+ - testableexamples
+ - thelper
+ - tparallel
- typecheck
- unconvert
+ - unparam
+ - unused
+ - wastedassign
+ - whitespace
+ - zerologlint
issues:
exclude-rules:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2f5da42..48ebecf 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,95 @@
# Changelog
+### [0.16.1](https://www.github.com/sentriz/gonic/compare/v0.16.0...v0.16.1) (2023-11-08)
+
+
+### Features
+
+* add more and unify stats ([2fdc1f4](https://www.github.com/sentriz/gonic/commit/2fdc1f41a25435f2c543ea114dd366c3c3d8394f))
+* store and expose individual track artists ([c1a34dc](https://www.github.com/sentriz/gonic/commit/c1a34dc0219b83300b427e66ef388f27a6186c9f))
+* **subsonic:** add getAlbumInfo with cache ([cc1a99f](https://www.github.com/sentriz/gonic/commit/cc1a99f03381a5afcebdbe95aaa42fb969f98b9f))
+* **subsonic:** expose all of album "name"/"title"/"album" for browse by tag and browse by folder ([2df9052](https://www.github.com/sentriz/gonic/commit/2df9052bf9862258c81a69e362c23fa35e653831)), closes [#404](https://www.github.com/sentriz/gonic/issues/404)
+* **subsonic:** expose track/album displayArtist/displayAlbumArtist ([0718aab](https://www.github.com/sentriz/gonic/commit/0718aabbacd52b7737dea606238ba64f65f2c2c6)), closes [#406](https://www.github.com/sentriz/gonic/issues/406)
+* **subsonic:** support getAlbumList/getAlbumList2 `type=highest` ([a30ee3d](https://www.github.com/sentriz/gonic/commit/a30ee3d7f91ebf24f427e7f36b6b2830299935f9)), closes [#404](https://www.github.com/sentriz/gonic/issues/404)
+
+
+### Bug Fixes
+
+* add track count to /debug/vars metrics endpoint ([69c02e8](https://www.github.com/sentriz/gonic/commit/69c02e8352c10276697184d3c24d0f3253ec8c4d)), closes [#392](https://www.github.com/sentriz/gonic/issues/392)
+* **contrib:** update config example ([d03d2dc](https://www.github.com/sentriz/gonic/commit/d03d2dc760c6c14b6f79efeca8b0111ead8912af))
+* don't panic when scan on start fails ([37e826e](https://www.github.com/sentriz/gonic/commit/37e826e02b2cdcfc2d60bc860767f7dbd89a1dcd)), closes [#399](https://www.github.com/sentriz/gonic/issues/399)
+* **metrics:** have a distinction between folders and albums ([cae3725](https://www.github.com/sentriz/gonic/commit/cae37255d68cbf493aba0bbb35dae38ca18fc4b6)), closes [#396](https://www.github.com/sentriz/gonic/issues/396)
+* **scanner:** make sure we roll back invalid parents ([ddb686b](https://www.github.com/sentriz/gonic/commit/ddb686bddc5d040912812777829e6283d15c5343)), closes [#402](https://www.github.com/sentriz/gonic/issues/402)
+* store and scrobble with real album artist info string ([fe0567a](https://www.github.com/sentriz/gonic/commit/fe0567a995dc40daeffa0460f0272b6e3af783a8))
+* **subsonic:** don't return concatenated genres strings for song/trackchilds ([f18151b](https://www.github.com/sentriz/gonic/commit/f18151b75573e6f024529ec4a134ef213dd86a78))
+* **subsonic:** songCount and albumCount in genre objects is required ([#390](https://www.github.com/sentriz/gonic/issues/390)) ([b17e76e](https://www.github.com/sentriz/gonic/commit/b17e76ea730e213d99a164c8ddff2c4b951f7f1f))
+* use conf cache-path instead of XDG_CACHE_HOME for jukebox socket ([9818523](https://www.github.com/sentriz/gonic/commit/981852317572a8c6ab357e9ce81523780801d3fe)), closes [#391](https://www.github.com/sentriz/gonic/issues/391)
+
+## [0.16.0](https://www.github.com/sentriz/gonic/compare/v0.15.2...v0.16.0) (2023-10-09)
+
+
+### ⚠ BREAKING CHANGES
+
+* **build:** bump to go 1.21
+* **subsonic:** drop support for guessed artist covers in filesystem
+
+### Features
+
+* add .wav to list of supported audio types ([#322](https://www.github.com/sentriz/gonic/issues/322)) ([ab07b87](https://www.github.com/sentriz/gonic/commit/ab07b876b8686d2e2c792f2d422dd227d6f9d94b))
+* add option for /debug/vars endpoint to expose database and media stats ([2a7a455](https://www.github.com/sentriz/gonic/commit/2a7a455ce27c3f8007a6114f815ae8ae94648533)), closes [#372](https://www.github.com/sentriz/gonic/issues/372) [#150](https://www.github.com/sentriz/gonic/issues/150)
+* add support for wavpack ([#380](https://www.github.com/sentriz/gonic/issues/380)) ([827baf2](https://www.github.com/sentriz/gonic/commit/827baf2036dfe581bfddba1c5b88510c13b8bba6))
+* **admin:** sort transcode profile names ([ae5bc2e](https://www.github.com/sentriz/gonic/commit/ae5bc2e1494f983993be7a053c953ca2f8555fae)), closes [#288](https://www.github.com/sentriz/gonic/issues/288)
+* **admin:** support application/x-mpegurl playlist uploads ([6aa4c42](https://www.github.com/sentriz/gonic/commit/6aa4c42ce556f5a503bd9d5a4d1ee957c167dafa)), closes [#282](https://www.github.com/sentriz/gonic/issues/282)
+* **admin:** update stylesheet ([222256c](https://www.github.com/sentriz/gonic/commit/222256cccbeb791168070ba5fe04a3bc1632cb94))
+* allow multi valued tag modes to be configurable ([8f6610f](https://www.github.com/sentriz/gonic/commit/8f6610ff860ad18d56545b903d9edb6a1254ddec))
+* **ci:** add a bunch more linters ([e3dd812](https://www.github.com/sentriz/gonic/commit/e3dd812b6c13c5f74690a868d0a5c37f30e33053))
+* **ci:** update checkout and setup-go actions ([#326](https://www.github.com/sentriz/gonic/issues/326)) ([6144ac7](https://www.github.com/sentriz/gonic/commit/6144ac7979e03d704f8f721ba378eb612538d284))
+* **ci:** update golangci-lint and action ([#325](https://www.github.com/sentriz/gonic/issues/325)) ([85eeb86](https://www.github.com/sentriz/gonic/commit/85eeb860bf1f97091fbd101b3bc827ff6502ccdb))
+* **contrib:** improve system related contrib files ([ac74b35](https://www.github.com/sentriz/gonic/commit/ac74b354653b7353466eda3d81ca519bfa9f816e))
+* enable profile-guided optimization ([e842b89](https://www.github.com/sentriz/gonic/commit/e842b896ec5acde6acdefbf3ec66610bd6cf7e22))
+* **lastfm:** add user get loved tracks method ([9026c9e](https://www.github.com/sentriz/gonic/commit/9026c9e2c0463c467958b7032e4e6f7a889c3c76))
+* **podcast:** parse podcast episode descriptions from HTML to plain text ([#351](https://www.github.com/sentriz/gonic/issues/351)) ([7d2c4fb](https://www.github.com/sentriz/gonic/commit/7d2c4fbb5c4cec3e7bcb4852214c17999bf320bb))
+* **scanner:** add a new option for excluding paths based on a regexp ([1d38776](https://www.github.com/sentriz/gonic/commit/1d3877668f9bf925cae7c548b5d8e683d9676af2))
+* **scanner:** support more cover types ([906164a](https://www.github.com/sentriz/gonic/commit/906164a5de34047444efe75b52b014737c111bc4))
+* **scanner:** support non lowercase extensions like .Mp3 ([d83fe56](https://www.github.com/sentriz/gonic/commit/d83fe560d3df980c0bf99d03e026af9bce30e0c7))
+* store and use m3u files on filesystem for playlists ([7dc9575](https://www.github.com/sentriz/gonic/commit/7dc9575e52538cf4fd39715193b5c760e1cc477b)), closes [#306](https://www.github.com/sentriz/gonic/issues/306) [#307](https://www.github.com/sentriz/gonic/issues/307) [#66](https://www.github.com/sentriz/gonic/issues/66)
+* **subsonic:** add getOpenSubsonicExtensions endpoint and openSubsonic response key ([2caee44](https://www.github.com/sentriz/gonic/commit/2caee441ca49e7b2ca148f5b698365085db0cfc8))
+* **subsonic:** add support for multi-valued album artist tags ([3ac7782](https://www.github.com/sentriz/gonic/commit/3ac77823c3bdc2e2be543f18e7b78295a7eb2fb8))
+* **subsonic:** add support for podcast episodes in both playlists and play queues ([aecee3d](https://www.github.com/sentriz/gonic/commit/aecee3d2d859ca9e754db9f65bf031290d0ce4a5))
+* **subsonic:** cache and use lastfm responses for covers, bios, top songs ([c374577](https://www.github.com/sentriz/gonic/commit/c374577328c17b6c3c7b6edbf901585e1f6644ee))
+* **subsonic:** change frequent album list to use total time played per album instead of play count. ([#331](https://www.github.com/sentriz/gonic/issues/331)) ([7982ffc](https://www.github.com/sentriz/gonic/commit/7982ffc0b46bc3e14eb753cfb3791e183a75834b))
+* **subsonic:** drop support for guessed artist covers in filesystem ([657fb22](https://www.github.com/sentriz/gonic/commit/657fb221db002ffebbf2a8d603566191acb40d17))
+* **subsonic:** expose all album genres in a list of subsonic api ([749233d](https://www.github.com/sentriz/gonic/commit/749233db4effbdc7c3288f7cb8052784379be44f))
+* **subsonic:** fetch artist images from lastfm opengraph ([4757495](https://www.github.com/sentriz/gonic/commit/475749534f784eb803eec9cb83c72d49f30d1994)), closes [#295](https://www.github.com/sentriz/gonic/issues/295)
+* **subsonic:** gracefully handle missing podcast episode paths when returning playlists ([d5f8e23](https://www.github.com/sentriz/gonic/commit/d5f8e23a89cf1677e6ced124df4c0e07cdb7d114))
+* **subsonic:** improve search2 and search3 when there are multiple words searched on. ([#335](https://www.github.com/sentriz/gonic/issues/335)) ([cbab68b](https://www.github.com/sentriz/gonic/commit/cbab68b05700aeb8b1fc2192ae5263ead248baf4))
+* **subsonic:** make it easier to add more tag reading backends ([8382f61](https://www.github.com/sentriz/gonic/commit/8382f6123c2ac39d12b266730d76301faaf168f4))
+* **subsonic:** order results from getStarred reverse chronologically based on star date ([b3c863c](https://www.github.com/sentriz/gonic/commit/b3c863c386adb830cdb45f45644f4779a4b73e86))
+* **subsonic:** return artist cover ids for similar artists response ([c15349f](https://www.github.com/sentriz/gonic/commit/c15349f79667e71138c6088f52f8efbd9966c33a))
+* **subsonic:** scrobble to different scrobble backends in parallel ([1ea2402](https://www.github.com/sentriz/gonic/commit/1ea240255927986b90a39c9ea67736f1b6808441))
+* **subsonic:** support timeOffset in stream.view ([#384](https://www.github.com/sentriz/gonic/issues/384)) ([7eaf602](https://www.github.com/sentriz/gonic/commit/7eaf602e6990d6840f2fc5792599abb09bbef24b))
+* **subsonic:** update track play stats on scrobble instead of stream ([e0b1603](https://www.github.com/sentriz/gonic/commit/e0b1603c00f7c24ce9b57085f5447bc0d7b016d7))
+* **sunsonic:** expose type serverVersion in subsonic responses ([b8fceae](https://www.github.com/sentriz/gonic/commit/b8fceae3834d29f447fbb23eeb77f6216018e55a))
+* **tags:** support multi valued tags like albumartists ([623d5c3](https://www.github.com/sentriz/gonic/commit/623d5c370906784b3ba8b21b89e435eafd41771e))
+* **transcode:** add MP3 320 transcoding profile ([#363](https://www.github.com/sentriz/gonic/issues/363)) ([a644f0f](https://www.github.com/sentriz/gonic/commit/a644f0ff5c47c0f196c937dd76189de1e6099594))
+* **transcode:** add opus 192 profile ([5dcc8c1](https://www.github.com/sentriz/gonic/commit/5dcc8c18a1f0cedf1ce6772aafe6dbdec1ded03c))
+* **transcode:** lock the destination transcode cache path ([c9a2d2f](https://www.github.com/sentriz/gonic/commit/c9a2d2f9ce3fd7b9c724d8d2079abf43c2aa339b))
+
+
+### Bug Fixes
+
+* **admin:** continue on track match error ([16e6046](https://www.github.com/sentriz/gonic/commit/16e6046e85b99ebadc08f07b75404d7e67f6b77f))
+* **podcasts:** make sure we use safeFilename for podcast episodes too ([#339](https://www.github.com/sentriz/gonic/issues/339)) ([5fb9c49](https://www.github.com/sentriz/gonic/commit/5fb9c49ed2810a1b63fce8930320eb7de0356c33))
+* **podcasts:** remove query parameters from URL when getting the extension ([19be6f0](https://www.github.com/sentriz/gonic/commit/19be6f0881ed6c0c3311793c55dbbbe0a5571f51))
+* **scanner:** fix watcher panic ([78d0c52](https://www.github.com/sentriz/gonic/commit/78d0c52d2240671a1e529339727bd013b7feb5c6))
+* **scanner:** remove redundant mod time look up ([e0a8c18](https://www.github.com/sentriz/gonic/commit/e0a8c18b8df9b148053ed5dbe535f76c245e7df8)), closes [#293](https://www.github.com/sentriz/gonic/issues/293)
+* **subsonic:** only return one bookmark entry per row in getBookmarks ([efe72fc](https://www.github.com/sentriz/gonic/commit/efe72fc447a23f48f0a49d92a7b3ed3c68d03722)), closes [#310](https://www.github.com/sentriz/gonic/issues/310)
+
+
+### Miscellaneous Chores
+
+* **build:** bump to go 1.21 ([658bae2](https://www.github.com/sentriz/gonic/commit/658bae2b43d170fa249ef2a0e953a494e0b2061a))
+
### [0.15.2](https://www.github.com/sentriz/gonic/compare/v0.15.1...v0.15.2) (2022-12-27)
diff --git a/Dockerfile b/Dockerfile
index 29da8bd..aeb3728 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -21,7 +21,8 @@ RUN apk add -U --no-cache \
mpv \
ca-certificates \
tzdata \
- tini
+ tini \
+ shared-mime-info
COPY --from=builder \
/usr/lib/libgcc_s.so.1 \
diff --git a/Dockerfile.debug b/Dockerfile.debug
index 9adde2a..39f94ea 100644
--- a/Dockerfile.debug
+++ b/Dockerfile.debug
@@ -5,5 +5,6 @@ RUN apk add -U --no-cache \
git \
sqlite \
taglib-dev \
- zlib-dev
+ zlib-dev \
+ shared-mime-info
WORKDIR /src
diff --git a/Dockerfile.dev b/Dockerfile.dev
index 9735818..e9d915f 100644
--- a/Dockerfile.dev
+++ b/Dockerfile.dev
@@ -18,7 +18,8 @@ FROM alpine:3.18
RUN apk add -U --no-cache \
ffmpeg \
mpv \
- ca-certificates
+ ca-certificates \
+ shared-mime-info
COPY --from=builder \
/usr/lib/libgcc_s.so.1 \
/usr/lib/libstdc++.so.6 \
diff --git a/README.md b/README.md
index 89a9efb..397fa48 100644
--- a/README.md
+++ b/README.md
@@ -20,12 +20,12 @@
- on-the-fly audio transcoding and caching (requires [ffmpeg](https://ffmpeg.org/)) (thank you [spijet](https://github.com/spijet/))
- jukebox mode (thank you [lxea](https://github.com/lxea/))
- support for podcasts (thank you [lxea](https://github.com/lxea/))
-- pretty fast scanning (with my library of ~27k tracks, initial scan takes about 10m, and about 5s after incrementally)
+- pretty fast scanning (with my library of ~50k tracks, initial scan takes about 10m, and about 6s after incrementally)
- multiple users, each with their own transcoding preferences, playlists, top tracks, top artists, etc.
- [last.fm](https://www.last.fm/) scrobbling
- [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
-- 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))
- 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
- written in [go](https://golang.org/), so lightweight and suitable for a raspberry pi, etc. (see ARM images below)
@@ -77,10 +77,11 @@ password can then be changed from the web interface
| `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_MULTI_VALUE_GENRE` | `-multi-value-genre` | **optional** setting for multi-valued genre 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)) |
| `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_EXPVAR` | `-expvar` | **optional** enable the /debug/vars endpoint (exposes useful debugging attributes as well as database stats) |
-## multi valued tags
+## 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.
diff --git a/cmd/gonic/default.pgo b/cmd/gonic/default.pgo
new file mode 100644
index 0000000..a3fb704
Binary files /dev/null and b/cmd/gonic/default.pgo differ
diff --git a/cmd/gonic/gonic.go b/cmd/gonic/gonic.go
index 60be307..8816789 100644
--- a/cmd/gonic/gonic.go
+++ b/cmd/gonic/gonic.go
@@ -1,9 +1,8 @@
-// Package main is the gonic server entrypoint
-//
-//nolint:lll,gocyclo
+//nolint:lll,gocyclo,forbidigo,nilerr
package main
import (
+ "context"
"errors"
"expvar"
"flag"
@@ -11,34 +10,41 @@ import (
"log"
"net/http"
"os"
+ "os/signal"
"path"
"path/filepath"
"regexp"
"strings"
+ "syscall"
"time"
+ // avatar encode/decode
+ _ "image/gif"
+ _ "image/png"
+
"github.com/google/shlex"
- "github.com/gorilla/mux"
"github.com/gorilla/securecookie"
_ "github.com/jinzhu/gorm/dialects/sqlite"
- "github.com/oklog/run"
"github.com/peterbourgon/ff"
"github.com/sentriz/gormstore"
+ "golang.org/x/sync/errgroup"
"go.senan.xyz/gonic"
"go.senan.xyz/gonic/db"
+ "go.senan.xyz/gonic/handlerutil"
+ "go.senan.xyz/gonic/infocache/albuminfocache"
+ "go.senan.xyz/gonic/infocache/artistinfocache"
"go.senan.xyz/gonic/jukebox"
+ "go.senan.xyz/gonic/lastfm"
+ "go.senan.xyz/gonic/listenbrainz"
"go.senan.xyz/gonic/playlist"
- "go.senan.xyz/gonic/podcasts"
+ "go.senan.xyz/gonic/podcast"
"go.senan.xyz/gonic/scanner"
- "go.senan.xyz/gonic/scanner/tags"
"go.senan.xyz/gonic/scrobble"
- "go.senan.xyz/gonic/scrobble/lastfm"
- "go.senan.xyz/gonic/scrobble/listenbrainz"
"go.senan.xyz/gonic/server/ctrladmin"
- "go.senan.xyz/gonic/server/ctrlbase"
"go.senan.xyz/gonic/server/ctrlsubsonic"
- "go.senan.xyz/gonic/server/ctrlsubsonic/artistinfocache"
+ "go.senan.xyz/gonic/tags/tagcommon"
+ "go.senan.xyz/gonic/tags/taglib"
"go.senan.xyz/gonic/transcode"
)
@@ -49,7 +55,7 @@ func main() {
confTLSCert := set.String("tls-cert", "", "path to TLS certificate (optional)")
confTLSKey := set.String("tls-key", "", "path to TLS private key (optional)")
- confPodcastPurgeAgeDays := set.Int("podcast-purge-age", 0, "age (in days) to purge podcast episodes if not accessed (optional)")
+ confPodcastPurgeAgeDays := set.Uint("podcast-purge-age", 0, "age (in days) to purge podcast episodes if not accessed (optional)")
confPodcastPath := set.String("podcast-path", "", "path to podcasts")
confCachePath := set.String("cache-path", "", "path to cache")
@@ -61,7 +67,7 @@ func main() {
confDBPath := set.String("db-path", "gonic.db", "path to database (optional)")
- confScanIntervalMins := set.Int("scan-interval", 0, "interval (in minutes) to automatically scan music (optional)")
+ confScanIntervalMins := set.Uint("scan-interval", 0, "interval (in minutes) to automatically scan music (optional)")
confScanAtStart := set.Bool("scan-at-start-enabled", false, "whether to perform an initial scan at startup (optional)")
confScanWatcher := set.Bool("scan-watcher-enabled", false, "whether to watch file system for new music and rescan (optional)")
@@ -74,17 +80,18 @@ func main() {
confShowVersion := set.Bool("version", false, "show gonic version")
_ = set.String("config-path", "", "path to config (optional)")
- confExcludePatterns := set.String("exclude-pattern", "", "regex pattern to exclude files from scan (optional)")
+ confExcludePattern := set.String("exclude-pattern", "", "regex pattern to exclude files from scan (optional)")
- var confMultiValueGenre, confMultiValueAlbumArtist multiValueSetting
+ var confMultiValueGenre, confMultiValueArtist, confMultiValueAlbumArtist multiValueSetting
set.Var(&confMultiValueGenre, "multi-value-genre", "setting for mutli-valued genre scanning (optional)")
+ set.Var(&confMultiValueArtist, "multi-value-artist", "setting for mutli-valued track artist scanning (optional)")
set.Var(&confMultiValueAlbumArtist, "multi-value-album-artist", "setting for mutli-valued album artist scanning (optional)")
confExpvar := set.Bool("expvar", false, "enable the /debug/vars endpoint (optional)")
deprecatedConfGenreSplit := set.String("genre-split", "", "(deprecated, see multi-value settings)")
- if _, err := regexp.Compile(*confExcludePatterns); err != nil {
+ if _, err := regexp.Compile(*confExcludePattern); err != nil {
log.Fatalf("invalid exclude pattern: %v\n", err)
}
@@ -138,6 +145,8 @@ func main() {
defer dbc.Close()
err = dbc.Migrate(db.MigrationContext{
+ Production: true,
+ DBPath: *confDBPath,
OriginalMusicPath: confMusicPaths[0].path,
PlaylistsPath: *confPlaylistsPath,
PodcastsPath: *confPodcastPath,
@@ -158,6 +167,13 @@ func main() {
confMultiValueGenre = multiValueSetting{Mode: scanner.Delim, Delim: *deprecatedConfGenreSplit}
*deprecatedConfGenreSplit = ""
}
+ if confMultiValueArtist.Mode == scanner.None && confMultiValueAlbumArtist.Mode > scanner.None {
+ confMultiValueArtist.Mode = confMultiValueAlbumArtist.Mode
+ confMultiValueArtist.Delim = confMultiValueAlbumArtist.Delim
+ }
+ if confMultiValueArtist.Mode != confMultiValueAlbumArtist.Mode {
+ log.Panic("differing multi artist and album artist modes have been tested yet. please set them to be the same")
+ }
log.Printf("starting gonic v%s\n", gonic.Version)
log.Printf("provided config\n")
@@ -166,23 +182,41 @@ func main() {
log.Printf(" %-25s %s\n", f.Name, value)
})
- tagger := &tags.TagReader{}
+ tagReader := tagcommon.ChainReader{
+ taglib.TagLib{},
+ // ffprobe reader?
+ // nfo reader?
+ }
+
scannr := scanner.New(
- ctrlsubsonic.PathsOf(musicPaths),
+ ctrlsubsonic.MusicPaths(musicPaths),
dbc,
map[scanner.Tag]scanner.MultiValueSetting{
scanner.Genre: scanner.MultiValueSetting(confMultiValueGenre),
+ scanner.Artist: scanner.MultiValueSetting(confMultiValueArtist),
scanner.AlbumArtist: scanner.MultiValueSetting(confMultiValueAlbumArtist),
},
- tagger,
- *confExcludePatterns,
+ tagReader,
+ *confExcludePattern,
)
- podcast := podcasts.New(dbc, *confPodcastPath, tagger)
+ podcast := podcast.New(dbc, *confPodcastPath, tagReader)
transcoder := transcode.NewCachingTranscoder(
transcode.NewFFmpegTranscoder(),
cacheDirAudio,
)
- lastfmClient := lastfm.NewClient()
+
+ lastfmClientKeySecretFunc := func() (string, string, error) {
+ apiKey, _ := dbc.GetSetting(db.LastFMAPIKey)
+ secret, _ := dbc.GetSetting(db.LastFMSecret)
+ if apiKey == "" || secret == "" {
+ return "", "", fmt.Errorf("not configured")
+ }
+ return apiKey, secret, nil
+ }
+
+ listenbrainzClient := listenbrainz.NewClient()
+ lastfmClient := lastfm.NewClient(lastfmClientKeySecretFunc)
+
playlistStore, err := playlist.NewStore(*confPlaylistsPath)
if err != nil {
log.Panicf("error creating playlists store: %v", err)
@@ -207,171 +241,212 @@ func main() {
sessDB.SessionOpts.SameSite = http.SameSiteLaxMode
artistInfoCache := artistinfocache.New(dbc, lastfmClient)
+ albumInfoCache := albuminfocache.New(dbc, lastfmClient)
- ctrlBase := &ctrlbase.Controller{
- DB: dbc,
- PlaylistStore: playlistStore,
- ProxyPrefix: *confProxyPrefix,
- Scanner: scannr,
+ scrobblers := []scrobble.Scrobbler{lastfmClient, listenbrainzClient}
+
+ resolveProxyPath := func(in string) string {
+ return path.Join(*confProxyPrefix, in)
}
- ctrlAdmin, err := ctrladmin.New(ctrlBase, sessDB, podcast, lastfmClient)
+
+ ctrlAdmin, err := ctrladmin.New(dbc, sessDB, scannr, podcast, lastfmClient, resolveProxyPath)
if err != nil {
log.Panicf("error creating admin controller: %v\n", err)
}
- ctrlSubsonic := &ctrlsubsonic.Controller{
- Controller: ctrlBase,
- MusicPaths: musicPaths,
- PodcastsPath: *confPodcastPath,
- CacheAudioPath: cacheDirAudio,
- CacheCoverPath: cacheDirCovers,
- LastFMClient: lastfmClient,
- ArtistInfoCache: artistInfoCache,
- Scrobblers: []scrobble.Scrobbler{
- lastfm.NewScrobbler(dbc, lastfmClient),
- listenbrainz.NewScrobbler(),
- },
- Podcasts: podcast,
- Transcoder: transcoder,
- Jukebox: jukebx,
+ ctrlSubsonic, err := ctrlsubsonic.New(dbc, scannr, musicPaths, *confPodcastPath, cacheDirAudio, cacheDirCovers, jukebx, playlistStore, scrobblers, podcast, transcoder, lastfmClient, artistInfoCache, albumInfoCache, resolveProxyPath)
+ if err != nil {
+ log.Panicf("error creating subsonic controller: %v\n", err)
}
- mux := mux.NewRouter()
- ctrlbase.AddRoutes(ctrlBase, mux, *confHTTPLog)
- ctrladmin.AddRoutes(ctrlAdmin, mux.PathPrefix("/admin").Subrouter())
- ctrlsubsonic.AddRoutes(ctrlSubsonic, mux.PathPrefix("/rest").Subrouter())
+ chain := handlerutil.Chain()
+ if *confHTTPLog {
+ chain = handlerutil.Chain(handlerutil.Log)
+ }
+ chain = handlerutil.Chain(
+ chain,
+ handlerutil.BasicCORS,
+ )
+ trim := handlerutil.TrimPathSuffix(".view") // /x.view and /x should match the same
+
+ mux := http.NewServeMux()
+ mux.Handle("/admin/", http.StripPrefix("/admin", chain(ctrlAdmin)))
+ mux.Handle("/rest/", http.StripPrefix("/rest", chain(trim(ctrlSubsonic))))
+ mux.Handle("/ping", chain(handlerutil.Message("ok")))
+ mux.Handle("/", chain(handlerutil.Redirect(resolveProxyPath("/admin/home"))))
if *confExpvar {
mux.Handle("/debug/vars", expvar.Handler())
expvar.Publish("stats", expvar.Func(func() any {
- var stats struct{ Albums, Tracks, Artists, InternetRadioStations, Podcasts uint }
- dbc.Model(db.Album{}).Count(&stats.Albums)
- dbc.Model(db.Track{}).Count(&stats.Tracks)
- dbc.Model(db.Artist{}).Count(&stats.Artists)
- dbc.Model(db.InternetRadioStation{}).Count(&stats.InternetRadioStations)
- dbc.Model(db.Podcast{}).Count(&stats.Podcasts)
+ stats, _ := dbc.Stats()
return stats
}))
}
- var g run.Group
- g.Add(func() error {
- log.Print("starting job 'http'\n")
- server := &http.Server{
- Addr: *confListenAddr,
- Handler: mux,
- ReadTimeout: 5 * time.Second,
- ReadHeaderTimeout: 5 * time.Second,
- WriteTimeout: 80 * time.Second,
- IdleTimeout: 60 * time.Second,
- }
+ errgrp, ctx := errgroup.WithContext(context.Background())
+
+ errgrp.Go(func() error {
+ defer logJob("http")()
+
+ server := &http.Server{Addr: *confListenAddr, Handler: mux, ReadHeaderTimeout: 5 * time.Second}
+ errgrp.Go(func() error {
+ <-ctx.Done()
+ return server.Shutdown(context.Background())
+ })
if *confTLSCert != "" && *confTLSKey != "" {
return server.ListenAndServeTLS(*confTLSCert, *confTLSKey)
}
return server.ListenAndServe()
- }, nil)
+ })
- g.Add(func() error {
- log.Printf("starting job 'session clean'\n")
- ticker := time.NewTicker(10 * time.Minute)
- for range ticker.C {
- sessDB.Cleanup()
+ errgrp.Go(func() error {
+ if !*confScanWatcher {
+ return nil
+ }
+
+ defer logJob("scan watcher")()
+
+ done := make(chan struct{})
+ errgrp.Go(func() error {
+ <-ctx.Done()
+ done <- struct{}{}
+ return nil
+ })
+ return scannr.ExecuteWatch(done)
+ })
+
+ errgrp.Go(func() error {
+ if jukebx == nil {
+ return nil
+ }
+
+ defer logJob("jukebox")()
+
+ extraArgs, _ := shlex.Split(*confJukeboxMPVExtraArgs)
+ jukeboxTempDir := filepath.Join(*confCachePath, "gonic-jukebox")
+ if err := os.RemoveAll(jukeboxTempDir); err != nil {
+ return fmt.Errorf("remove jubebox tmp dir: %w", err)
+ }
+ if err := os.MkdirAll(jukeboxTempDir, os.ModePerm); err != nil {
+ return fmt.Errorf("create tmp sock file: %w", err)
+ }
+ sockPath := filepath.Join(jukeboxTempDir, "sock")
+ if err := jukebx.Start(sockPath, extraArgs); err != nil {
+ return fmt.Errorf("start jukebox: %w", err)
+ }
+ errgrp.Go(func() error {
+ <-ctx.Done()
+ return jukebx.Quit()
+ })
+ if err := jukebx.Wait(); err != nil {
+ return fmt.Errorf("start jukebox: %w", err)
}
return nil
- }, nil)
+ })
- g.Add(func() error {
- log.Printf("starting job 'podcast refresher'\n")
- ticker := time.NewTicker(time.Hour)
- for range ticker.C {
+ errgrp.Go(func() error {
+ defer logJob("session clean")()
+
+ ctxTick(ctx, 10*time.Minute, func() {
+ sessDB.Cleanup()
+ })
+ return nil
+ })
+
+ errgrp.Go(func() error {
+ defer logJob("podcast refresh")()
+
+ ctxTick(ctx, 1*time.Hour, func() {
if err := podcast.RefreshPodcasts(); err != nil {
log.Printf("failed to refresh some feeds: %s", err)
}
- }
+ })
return nil
- }, nil)
+ })
- g.Add(func() error {
- log.Printf("starting job 'podcast purger'\n")
- ticker := time.NewTicker(24 * time.Hour)
- for range ticker.C {
+ errgrp.Go(func() error {
+ if *confPodcastPurgeAgeDays == 0 {
+ return nil
+ }
+
+ defer logJob("podcast purge")()
+
+ ctxTick(ctx, 24*time.Hour, func() {
if err := podcast.PurgeOldPodcasts(time.Duration(*confPodcastPurgeAgeDays) * 24 * time.Hour); err != nil {
log.Printf("error purging old podcasts: %v", err)
}
+ })
+ return nil
+ })
+
+ errgrp.Go(func() error {
+ if *confScanIntervalMins == 0 {
+ return nil
+ }
+
+ defer logJob("scan timer")()
+
+ ctxTick(ctx, time.Duration(*confScanIntervalMins)*time.Minute, func() {
+ if _, err := scannr.ScanAndClean(scanner.ScanOptions{}); err != nil {
+ log.Printf("error scanning: %v", err)
+ }
+ })
+ return nil
+ })
+
+ errgrp.Go(func() error {
+ if _, _, err := lastfmClientKeySecretFunc(); err != nil {
+ return nil
+ }
+
+ defer logJob("refresh artist info")()
+
+ ctxTick(ctx, 8*time.Second, func() {
+ if err := artistInfoCache.Refresh(); err != nil {
+ log.Printf("error in artist info cache: %v", err)
+ }
+ })
+ return nil
+ })
+
+ errgrp.Go(func() error {
+ if !*confScanAtStart {
+ return nil
+ }
+
+ defer logJob("scan at start")()
+
+ if _, err := scannr.ScanAndClean(scanner.ScanOptions{}); err != nil {
+ log.Printf("error scanning on start: %v", err)
}
return nil
- }, nil)
+ })
- if *confScanIntervalMins > 0 {
- g.Add(func() error {
- log.Printf("starting job 'scan timer'\n")
- ticker := time.NewTicker(time.Duration(*confScanIntervalMins) * time.Minute)
- for range ticker.C {
- if _, err := scannr.ScanAndClean(scanner.ScanOptions{}); err != nil {
- log.Printf("error scanning: %v", err)
- }
- }
+ errShutdown := errors.New("shutdown")
+
+ errgrp.Go(func() error {
+ sigChan := make(chan os.Signal, 1)
+ signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
+ select {
+ case <-ctx.Done():
return nil
- }, nil)
- }
-
- if *confScanWatcher {
- g.Add(func() error {
- log.Printf("starting job 'scan watcher'\n")
- return scannr.ExecuteWatch()
- }, func(_ error) {
- scannr.CancelWatch()
- })
- }
-
- if jukebx != nil {
- var jukeboxTempDir string
- g.Add(func() error {
- log.Printf("starting job 'jukebox'\n")
- extraArgs, _ := shlex.Split(*confJukeboxMPVExtraArgs)
- var err error
- jukeboxTempDir, err = os.MkdirTemp("", "gonic-jukebox-*")
- if err != nil {
- return fmt.Errorf("create tmp sock file: %w", err)
- }
- sockPath := filepath.Join(jukeboxTempDir, "sock")
- if err := jukebx.Start(sockPath, extraArgs); err != nil {
- return fmt.Errorf("start jukebox: %w", err)
- }
- if err := jukebx.Wait(); err != nil {
- return fmt.Errorf("start jukebox: %w", err)
- }
- return nil
- }, func(_ error) {
- if err := jukebx.Quit(); err != nil {
- log.Printf("error quitting jukebox: %v", err)
- }
- _ = os.RemoveAll(jukeboxTempDir)
- })
- }
-
- lastfmAPIKey, _ := dbc.GetSetting(db.LastFMAPIKey)
- if lastfmAPIKey != "" {
- g.Add(func() error {
- log.Printf("starting job 'refresh artist info'\n")
- return artistInfoCache.Refresh(lastfmAPIKey, 8*time.Second)
- }, nil)
- }
-
- if *confScanAtStart {
- if _, err := scannr.ScanAndClean(scanner.ScanOptions{}); err != nil {
- log.Panicf("error scanning at start: %v\n", err)
+ case <-sigChan:
+ return errShutdown
}
+ })
+
+ if err := errgrp.Wait(); err != nil && !errors.Is(err, errShutdown) {
+ log.Panic(err)
}
- if err := g.Run(); err != nil {
- log.Panicf("error in job: %v", err)
- }
+ fmt.Println("shutdown complete")
}
const pathAliasSep = "->"
-type pathAliases []pathAlias
-type pathAlias struct{ alias, path string }
+type (
+ pathAliases []pathAlias
+ pathAlias struct{ alias, path string }
+)
func (pa pathAliases) String() string {
var strs []string
@@ -438,3 +513,22 @@ func (mvs *multiValueSetting) Set(value string) error {
}
return nil
}
+
+func logJob(jobName string) func() {
+ log.Printf("starting job %q", jobName)
+ return func() { log.Printf("stopped job %q", jobName) }
+}
+
+func ctxTick(ctx context.Context, interval time.Duration, f func()) {
+ ticker := time.NewTicker(interval)
+ defer ticker.Stop()
+
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-ticker.C:
+ f()
+ }
+ }
+}
diff --git a/contrib/config b/contrib/config
index 29528af..9031113 100644
--- a/contrib/config
+++ b/contrib/config
@@ -1,5 +1,5 @@
# This is the gonic server system-wide configuration file. For other
-# administrative and per user settings go th the web UI.
+# administrative and per user settings go to the web UI.
#
# The strategy used for options in the default config shipped with gonic is to
# specify options with their default value where possible, and leave optional
@@ -15,9 +15,9 @@ listen-addr 127.0.0.1:4747
# URL path prefix to use if behind reverse proxy
#proxy-prefix
-# Secure connection settings. Recommended to set up unless gonic sits behing an
+# Secure connection settings. Recommended to set up unless gonic sits behind an
# SSL enabled reverse proxy server. Disabled by default.
-#tls-cert
+#tls-cert
#tls-key
# gonic's internal state database location
@@ -33,6 +33,14 @@ music-path
# podcast-path /var/cache/podcast
podcast-path
+# gonic manages playlists as m3u files. This way users can also edit these
+# playlists themselves or add custom ones via other tools. Items in the
+# directory should be placed in subdirectories matching user IDs in the
+# database, in the format `/.m3u`. For example the admin user could
+# have 1/my-playlist.m3u. E.g.:
+# playlists-path /srv/audio/playlists
+playlists-path
+
# Age (in days) to purge podcast episodes if not accessed. Disabled by default.
#podcast-purge-age 0
@@ -47,3 +55,16 @@ cache-path /var/cache/gonic
#scan-watcher-enabled false
#jukebox-enabled false
#jukebox-mpv-extra-args
+
+# Metadata multi-value handling
+# gonic supports parsing mult-valued tags in the metadata thus assigning a song
+# to several genres or album artists. This improves search and reduces clutter
+# in the artist/genre listing. Accepted options are:
+# multi: gonic will explicitly look for multi value fields the audio metadata
+# delim : gonic will look at the regular audio metadata
+# fields like "genre" or "album_artist", but split
+# them on a delimiter. For example to split on
+# semicolon set the option value to be "delim ;"
+# none: default setting, gonic won't attempt to do any multi value parsing
+#multi-value-genre none
+#multi-value-album-artist none
diff --git a/db/db.go b/db/db.go
index 4f6240e..a0d57ac 100644
--- a/db/db.go
+++ b/db/db.go
@@ -1,14 +1,22 @@
package db
import (
+ "context"
"errors"
"fmt"
"log"
+ "mime"
"net/url"
"os"
+ "path/filepath"
"strings"
+ "time"
"github.com/jinzhu/gorm"
+ "github.com/mattn/go-sqlite3"
+
+ // TODO: remove this dep
+ "go.senan.xyz/gonic/server/ctrlsubsonic/specid"
)
func DefaultOptions() url.Values {
@@ -72,6 +80,22 @@ func (db *DB) InsertBulkLeftMany(table string, head []string, left int, col []in
return db.Exec(q, values...).Error
}
+type Stats struct {
+ Folders, Albums, Artists, AlbumArtists, Tracks, InternetRadioStations, Podcasts uint
+}
+
+func (db *DB) Stats() (Stats, error) {
+ var stats Stats
+ db.Model(Album{}).Count(&stats.Folders)
+ db.Model(AlbumArtist{}).Group("album_id").Count(&stats.Albums)
+ db.Model(TrackArtist{}).Group("artist_id").Count(&stats.Artists)
+ db.Model(AlbumArtist{}).Group("artist_id").Count(&stats.AlbumArtists)
+ db.Model(Track{}).Count(&stats.Tracks)
+ db.Model(InternetRadioStation{}).Count(&stats.InternetRadioStations)
+ db.Model(Podcast{}).Count(&stats.Podcasts)
+ return stats, nil
+}
+
func (db *DB) GetUserByID(id int) *User {
var user User
err := db.
@@ -100,15 +124,19 @@ func (db *DB) Begin() *DB {
return &DB{DB: db.DB.Begin()}
}
-type ChunkFunc func(*gorm.DB, []int64) error
+func (db *DB) Transaction(cb func(*DB) error) error {
+ return db.DB.Transaction(func(tx *gorm.DB) error {
+ return cb(&DB{DB: tx})
+ })
+}
-func (db *DB) TransactionChunked(data []int64, cb ChunkFunc) error {
+func (db *DB) TransactionChunked(data []int64, cb func(*DB, []int64) error) error {
if len(data) == 0 {
return nil
}
// https://sqlite.org/limits.html
const size = 999
- return db.Transaction(func(tx *gorm.DB) error {
+ return db.Transaction(func(tx *DB) error {
for i := 0; i < len(data); i += size {
end := i + size
if end > len(data) {
@@ -145,3 +173,478 @@ func (db *DB) SetSetting(key SettingKey, value string) error {
FirstOrCreate(&Setting{}).
Error
}
+
+type Artist struct {
+ ID int `gorm:"primary_key"`
+ Name string `gorm:"not null; unique_index"`
+ NameUDec string `sql:"default: null"`
+ Albums []*Album `gorm:"many2many:album_artists"`
+ AlbumCount int `sql:"-"`
+ Appearances []*Album `gorm:"many2many:artist_appearances"`
+ AppearanceCount int `sql:"-"`
+ ArtistStar *ArtistStar
+ ArtistRating *ArtistRating
+ AverageRating float64 `sql:"default: null"`
+ Info *ArtistInfo `gorm:"foreignkey:id"`
+}
+
+func (a *Artist) SID() *specid.ID {
+ return &specid.ID{Type: specid.Artist, Value: a.ID}
+}
+
+func (a *Artist) IndexName() string {
+ if len(a.NameUDec) > 0 {
+ return a.NameUDec
+ }
+ return a.Name
+}
+
+type Genre struct {
+ ID int `gorm:"primary_key"`
+ Name string `gorm:"not null; unique_index"`
+ AlbumCount int `sql:"-"`
+ TrackCount int `sql:"-"`
+}
+
+// AudioFile is used to avoid some duplication in handlers_raw.go
+// between Track and Podcast
+type AudioFile interface {
+ Ext() string
+ MIME() string
+ AudioFilename() string
+ AudioBitrate() int
+ AudioLength() int
+}
+
+type Track struct {
+ ID int `gorm:"primary_key"`
+ CreatedAt time.Time
+ UpdatedAt time.Time
+ Filename string `gorm:"not null; unique_index:idx_folder_filename" sql:"default: null"`
+ FilenameUDec string `sql:"default: null"`
+ Album *Album
+ AlbumID int `gorm:"not null; unique_index:idx_folder_filename" sql:"default: null; type:int REFERENCES albums(id) ON DELETE CASCADE"`
+ Artists []*Artist `gorm:"many2many:track_artists"`
+ Genres []*Genre `gorm:"many2many:track_genres"`
+ Size int `sql:"default: null"`
+ Length int `sql:"default: null"`
+ Bitrate int `sql:"default: null"`
+ TagTitle string `sql:"default: null"`
+ TagTitleUDec string `sql:"default: null"`
+ TagTrackArtist string `sql:"default: null"`
+ TagTrackNumber int `sql:"default: null"`
+ TagDiscNumber int `sql:"default: null"`
+ TagBrainzID string `sql:"default: null"`
+ TrackStar *TrackStar
+ TrackRating *TrackRating
+ AverageRating float64 `sql:"default: null"`
+}
+
+func (t *Track) AudioLength() int { return t.Length }
+func (t *Track) AudioBitrate() int { return t.Bitrate }
+
+func (t *Track) SID() *specid.ID {
+ return &specid.ID{Type: specid.Track, Value: t.ID}
+}
+
+func (t *Track) AlbumSID() *specid.ID {
+ return &specid.ID{Type: specid.Album, Value: t.AlbumID}
+}
+
+func (t *Track) Ext() string {
+ return filepath.Ext(t.Filename)
+}
+
+func (t *Track) AudioFilename() string {
+ return t.Filename
+}
+
+func (t *Track) MIME() string {
+ return mime.TypeByExtension(filepath.Ext(t.Filename))
+}
+
+func (t *Track) AbsPath() string {
+ if t.Album == nil {
+ return ""
+ }
+ return filepath.Join(
+ t.Album.RootDir,
+ t.Album.LeftPath,
+ t.Album.RightPath,
+ t.Filename,
+ )
+}
+
+func (t *Track) RelPath() string {
+ if t.Album == nil {
+ return ""
+ }
+ return filepath.Join(
+ t.Album.LeftPath,
+ t.Album.RightPath,
+ t.Filename,
+ )
+}
+
+type User struct {
+ ID int `gorm:"primary_key"`
+ CreatedAt time.Time
+ Name string `gorm:"not null; unique_index" 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"`
+ IsAdmin bool `sql:"default: null"`
+ Avatar []byte `sql:"default: null"`
+}
+
+type Setting struct {
+ Key SettingKey `gorm:"not null; primary_key; auto_increment:false" sql:"default: null"`
+ Value string `sql:"default: null"`
+}
+
+type Play struct {
+ ID int `gorm:"primary_key"`
+ User *User
+ UserID int `gorm:"not null; index" sql:"default: null; type:int REFERENCES users(id) ON DELETE CASCADE"`
+ Album *Album
+ AlbumID int `gorm:"not null; index" sql:"default: null; type:int REFERENCES albums(id) ON DELETE CASCADE"`
+ Time time.Time `sql:"default: null"`
+ Count int
+ Length int
+}
+
+type Album struct {
+ ID int `gorm:"primary_key"`
+ CreatedAt time.Time
+ UpdatedAt time.Time
+ ModifiedAt time.Time
+ LeftPath string `gorm:"unique_index:idx_album_abs_path"`
+ RightPath string `gorm:"not null; unique_index:idx_album_abs_path" sql:"default: null"`
+ RightPathUDec string `sql:"default: null"`
+ Parent *Album
+ ParentID int `sql:"default: null; type:int REFERENCES albums(id) ON DELETE CASCADE"`
+ RootDir string `gorm:"unique_index:idx_album_abs_path" sql:"default: null"`
+ Genres []*Genre `gorm:"many2many:album_genres"`
+ Cover string `sql:"default: null"`
+ Artists []*Artist `gorm:"many2many:album_artists"`
+ TagTitle string `sql:"default: null"`
+ TagAlbumArtist string // display purposes only
+ TagTitleUDec string `sql:"default: null"`
+ TagBrainzID string `sql:"default: null"`
+ TagYear int `sql:"default: null"`
+ Tracks []*Track
+ ChildCount int `sql:"-"`
+ Duration int `sql:"-"`
+ AlbumStar *AlbumStar
+ AlbumRating *AlbumRating
+ AverageRating float64 `sql:"default: null"`
+}
+
+func (a *Album) SID() *specid.ID {
+ return &specid.ID{Type: specid.Album, Value: a.ID}
+}
+
+func (a *Album) ParentSID() *specid.ID {
+ return &specid.ID{Type: specid.Album, Value: a.ParentID}
+}
+
+func (a *Album) IndexRightPath() string {
+ if len(a.RightPathUDec) > 0 {
+ return a.RightPathUDec
+ }
+ return a.RightPath
+}
+
+type PlayQueue struct {
+ ID int `gorm:"primary_key"`
+ CreatedAt time.Time
+ UpdatedAt time.Time
+ User *User
+ UserID int `sql:"default: null; type:int REFERENCES users(id) ON DELETE CASCADE"`
+ Current string
+ Position int
+ ChangedBy string
+ Items string
+}
+
+func (p *PlayQueue) CurrentSID() *specid.ID {
+ id, _ := specid.New(p.Current)
+ return &id
+}
+
+func (p *PlayQueue) GetItems() []specid.ID {
+ return splitIDs(p.Items, ",")
+}
+
+func (p *PlayQueue) SetItems(items []specid.ID) {
+ p.Items = join(items, ",")
+}
+
+type TranscodePreference struct {
+ UserID int `gorm:"not null; unique_index:idx_user_id_client" sql:"default: null; type:int REFERENCES users(id) ON DELETE CASCADE"`
+ Client string `gorm:"not null; unique_index:idx_user_id_client" sql:"default: null"`
+ Profile string `gorm:"not null" sql:"default: null"`
+}
+
+type AlbumArtist struct {
+ AlbumID int `gorm:"not null; unique_index:idx_album_id_artist_id" sql:"default: null; type:int REFERENCES albums(id) ON DELETE CASCADE"`
+ ArtistID int `gorm:"not null; unique_index:idx_album_id_artist_id" sql:"default: null; type:int REFERENCES artists(id) ON DELETE CASCADE"`
+}
+
+type TrackArtist struct {
+ TrackID int `gorm:"not null; unique_index:idx_track_id_artist_id" sql:"default: null; type:int REFERENCES tracks(id) ON DELETE CASCADE"`
+ ArtistID int `gorm:"not null; unique_index:idx_track_id_artist_id" sql:"default: null; type:int REFERENCES artists(id) ON DELETE CASCADE"`
+}
+
+type ArtistAppearances struct {
+ ArtistID int `gorm:"not null; unique_index:idx_artist_id_album_id" sql:"default: null; type:int REFERENCES artists(id) ON DELETE CASCADE"`
+ AlbumID int `gorm:"not null; unique_index:idx_artist_id_album_id" sql:"default: null; type:int REFERENCES albums(id) ON DELETE CASCADE"`
+}
+
+type TrackGenre struct {
+ TrackID int `gorm:"not null; unique_index:idx_track_id_genre_id" sql:"default: null; type:int REFERENCES tracks(id) ON DELETE CASCADE"`
+ GenreID int `gorm:"not null; unique_index:idx_track_id_genre_id" sql:"default: null; type:int REFERENCES genres(id) ON DELETE CASCADE"`
+}
+
+type AlbumGenre struct {
+ AlbumID int `gorm:"not null; unique_index:idx_album_id_genre_id" sql:"default: null; type:int REFERENCES albums(id) ON DELETE CASCADE"`
+ GenreID int `gorm:"not null; unique_index:idx_album_id_genre_id" sql:"default: null; type:int REFERENCES genres(id) ON DELETE CASCADE"`
+}
+
+type AlbumStar struct {
+ UserID int `gorm:"primary_key; not null" sql:"default: null; type:int REFERENCES users(id) ON DELETE CASCADE"`
+ AlbumID int `gorm:"primary_key; not null" sql:"default: null; type:int REFERENCES albums(id) ON DELETE CASCADE"`
+ StarDate time.Time
+}
+
+type AlbumRating struct {
+ UserID int `gorm:"primary_key; not null" sql:"default: null; type:int REFERENCES users(id) ON DELETE CASCADE"`
+ AlbumID int `gorm:"primary_key; not null" sql:"default: null; type:int REFERENCES albums(id) ON DELETE CASCADE"`
+ Rating int `gorm:"not null; check:(rating >= 1 AND rating <= 5)"`
+}
+
+type ArtistStar struct {
+ UserID int `gorm:"primary_key; not null" sql:"default: null; type:int REFERENCES users(id) ON DELETE CASCADE"`
+ ArtistID int `gorm:"primary_key; not null" sql:"default: null; type:int REFERENCES artists(id) ON DELETE CASCADE"`
+ StarDate time.Time
+}
+
+type ArtistRating struct {
+ UserID int `gorm:"primary_key; not null" sql:"default: null; type:int REFERENCES users(id) ON DELETE CASCADE"`
+ ArtistID int `gorm:"primary_key; not null" sql:"default: null; type:int REFERENCES artists(id) ON DELETE CASCADE"`
+ Rating int `gorm:"not null; check:(rating >= 1 AND rating <= 5)"`
+}
+
+type TrackStar struct {
+ UserID int `gorm:"primary_key; not null" sql:"default: null; type:int REFERENCES users(id) ON DELETE CASCADE"`
+ TrackID int `gorm:"primary_key; not null" sql:"default: null; type:int REFERENCES tracks(id) ON DELETE CASCADE"`
+ StarDate time.Time
+}
+
+type TrackRating struct {
+ UserID int `gorm:"primary_key; not null" sql:"default: null; type:int REFERENCES users(id) ON DELETE CASCADE"`
+ TrackID int `gorm:"primary_key; not null" sql:"default: null; type:int REFERENCES tracks(id) ON DELETE CASCADE"`
+ Rating int `gorm:"not null; check:(rating >= 1 AND rating <= 5)"`
+}
+
+type PodcastAutoDownload string
+
+const (
+ PodcastAutoDownloadLatest PodcastAutoDownload = "latest"
+ PodcastAutoDownloadNone PodcastAutoDownload = "none"
+)
+
+type Podcast struct {
+ ID int `gorm:"primary_key"`
+ UpdatedAt time.Time
+ ModifiedAt time.Time
+ URL string
+ Title string
+ Description string
+ ImageURL string
+ Image string
+ Error string
+ Episodes []*PodcastEpisode
+ AutoDownload PodcastAutoDownload
+ RootDir string
+}
+
+func (p *Podcast) SID() *specid.ID {
+ return &specid.ID{Type: specid.Podcast, Value: p.ID}
+}
+
+type PodcastEpisodeStatus string
+
+const (
+ PodcastEpisodeStatusDownloading PodcastEpisodeStatus = "downloading"
+ PodcastEpisodeStatusSkipped PodcastEpisodeStatus = "skipped"
+ PodcastEpisodeStatusDeleted PodcastEpisodeStatus = "deleted"
+ PodcastEpisodeStatusCompleted PodcastEpisodeStatus = "completed"
+ PodcastEpisodeStatusError PodcastEpisodeStatus = "error"
+)
+
+type PodcastEpisode struct {
+ ID int `gorm:"primary_key"`
+ CreatedAt time.Time
+ UpdatedAt time.Time
+ ModifiedAt time.Time
+ PodcastID int `gorm:"not null" sql:"default: null; type:int REFERENCES podcasts(id) ON DELETE CASCADE"`
+ Title string
+ Description string
+ PublishDate *time.Time
+ AudioURL string
+ Bitrate int
+ Length int
+ Size int
+ Filename string
+ Status PodcastEpisodeStatus
+ Error string
+ Podcast *Podcast
+}
+
+func (pe *PodcastEpisode) AudioLength() int { return pe.Length }
+func (pe *PodcastEpisode) AudioBitrate() int { return pe.Bitrate }
+
+func (pe *PodcastEpisode) SID() *specid.ID {
+ return &specid.ID{Type: specid.PodcastEpisode, Value: pe.ID}
+}
+
+func (pe *PodcastEpisode) PodcastSID() *specid.ID {
+ return &specid.ID{Type: specid.Podcast, Value: pe.PodcastID}
+}
+
+func (pe *PodcastEpisode) AudioFilename() string {
+ return pe.Filename
+}
+
+func (pe *PodcastEpisode) Ext() string {
+ return filepath.Ext(pe.Filename)
+}
+
+func (pe *PodcastEpisode) MIME() string {
+ return mime.TypeByExtension(filepath.Ext(pe.Filename))
+}
+
+func (pe *PodcastEpisode) AbsPath() string {
+ if pe.Podcast == nil {
+ return ""
+ }
+ return filepath.Join(pe.Podcast.RootDir, pe.Filename)
+}
+
+type Bookmark struct {
+ ID int `gorm:"primary_key"`
+ User *User
+ UserID int `sql:"default: null; type:int REFERENCES users(id) ON DELETE CASCADE"`
+ Position int
+ Comment string
+ EntryIDType string
+ EntryID int
+ CreatedAt time.Time
+ UpdatedAt time.Time
+}
+
+type InternetRadioStation struct {
+ ID int `gorm:"primary_key"`
+ StreamURL string
+ Name string
+ HomepageURL string
+}
+
+func (ir *InternetRadioStation) SID() *specid.ID {
+ return &specid.ID{Type: specid.InternetRadioStation, Value: ir.ID}
+}
+
+type ArtistInfo struct {
+ ID int `gorm:"primary_key" sql:"type:int REFERENCES artists(id) ON DELETE CASCADE"`
+ CreatedAt time.Time
+ UpdatedAt time.Time `gorm:"index"`
+ Biography string
+ MusicBrainzID string
+ LastFMURL string
+ ImageURL string
+ SimilarArtists string
+ TopTracks string
+}
+
+func (p *ArtistInfo) GetSimilarArtists() []string { return strings.Split(p.SimilarArtists, ";") }
+func (p *ArtistInfo) SetSimilarArtists(items []string) { p.SimilarArtists = strings.Join(items, ";") }
+
+func (p *ArtistInfo) GetTopTracks() []string { return strings.Split(p.TopTracks, ";") }
+func (p *ArtistInfo) SetTopTracks(items []string) { p.TopTracks = strings.Join(items, ";") }
+
+type AlbumInfo struct {
+ ID int `gorm:"primary_key" sql:"type:int REFERENCES albums(id) ON DELETE CASCADE"`
+ CreatedAt time.Time
+ UpdatedAt time.Time `gorm:"index"`
+ Notes string
+ MusicBrainzID string
+ LastFMURL string
+}
+
+func splitIDs(in, sep string) []specid.ID {
+ if in == "" {
+ return []specid.ID{}
+ }
+ parts := strings.Split(in, sep)
+ ret := make([]specid.ID, 0, len(parts))
+ for _, p := range parts {
+ id, _ := specid.New(p)
+ ret = append(ret, id)
+ }
+ return ret
+}
+
+func join[T fmt.Stringer](in []T, sep string) string {
+ if in == nil {
+ return ""
+ }
+ strs := make([]string, 0, len(in))
+ for _, id := range in {
+ strs = append(strs, id.String())
+ }
+ return strings.Join(strs, sep)
+}
+
+func Dump(ctx context.Context, db *gorm.DB, to string) error {
+ dest, err := New(to, url.Values{})
+ if err != nil {
+ return fmt.Errorf("create dest db: %w", err)
+ }
+ defer dest.Close()
+
+ connSrc, err := db.DB().Conn(ctx)
+ if err != nil {
+ return fmt.Errorf("getting src raw conn: %w", err)
+ }
+ defer connSrc.Close()
+
+ connDest, err := dest.DB.DB().Conn(ctx)
+ if err != nil {
+ return fmt.Errorf("getting dest raw conn: %w", err)
+ }
+ defer connDest.Close()
+
+ err = connDest.Raw(func(connDest interface{}) error {
+ return connSrc.Raw(func(connSrc interface{}) error {
+ connDestq := connDest.(*sqlite3.SQLiteConn)
+ connSrcq := connSrc.(*sqlite3.SQLiteConn)
+ bk, err := connDestq.Backup("main", connSrcq, "main")
+ if err != nil {
+ return fmt.Errorf("create backup db: %w", err)
+ }
+ for done, _ := bk.Step(-1); !done; { //nolint: revive
+ }
+ if err := bk.Finish(); err != nil {
+ return fmt.Errorf("finishing dump: %w", err)
+ }
+ return nil
+ })
+ })
+ if err != nil {
+ return fmt.Errorf("backing up: %w", err)
+ }
+
+ return nil
+}
diff --git a/db/db_test.go b/db/db_test.go
index d28e00c..0fb2bf1 100644
--- a/db/db_test.go
+++ b/db/db_test.go
@@ -11,21 +11,17 @@ import (
"github.com/stretchr/testify/require"
)
-func randKey() string {
- letters := []rune("abcdef0123456789")
- b := make([]rune, 16)
- for i := range b {
- b[i] = letters[rand.Intn(len(letters))]
- }
- return string(b)
+func TestMain(m *testing.M) {
+ log.SetOutput(io.Discard)
+ os.Exit(m.Run())
}
func TestGetSetting(t *testing.T) {
+ t.Parallel()
+
key := SettingKey(randKey())
value := "howdy"
- require := require.New(t)
-
testDB, err := NewMock()
if err != nil {
t.Fatalf("error creating db: %v", err)
@@ -34,19 +30,23 @@ func TestGetSetting(t *testing.T) {
t.Fatalf("error migrating db: %v", err)
}
- require.NoError(testDB.SetSetting(key, value))
+ require.NoError(t, testDB.SetSetting(key, value))
actual, err := testDB.GetSetting(key)
- require.NoError(err)
- require.Equal(value, actual)
+ require.NoError(t, err)
+ require.Equal(t, value, actual)
- require.NoError(testDB.SetSetting(key, value))
+ require.NoError(t, testDB.SetSetting(key, value))
actual, err = testDB.GetSetting(key)
- require.NoError(err)
- require.Equal(value, actual)
+ require.NoError(t, err)
+ require.Equal(t, value, actual)
}
-func TestMain(m *testing.M) {
- log.SetOutput(io.Discard)
- os.Exit(m.Run())
+func randKey() string {
+ letters := []rune("abcdef0123456789")
+ b := make([]rune, 16)
+ for i := range b {
+ b[i] = letters[rand.Intn(len(letters))]
+ }
+ return string(b)
}
diff --git a/db/migrations.go b/db/migrations.go
index 763cec8..401d4ae 100644
--- a/db/migrations.go
+++ b/db/migrations.go
@@ -2,20 +2,25 @@
package db
import (
+ "context"
"errors"
"fmt"
"log"
+ "os"
"path/filepath"
"strings"
"time"
"github.com/jinzhu/gorm"
+ "go.senan.xyz/gonic/fileutil"
"go.senan.xyz/gonic/playlist"
"go.senan.xyz/gonic/server/ctrlsubsonic/specid"
"gopkg.in/gormigrate.v1"
)
type MigrationContext struct {
+ Production bool
+ DBPath string
OriginalMusicPath string
PlaylistsPath string
PodcastsPath string
@@ -54,11 +59,18 @@ func (db *DB) Migrate(ctx MigrationContext) error {
construct(ctx, "202206101425", migrateUser),
construct(ctx, "202207251148", migrateStarRating),
construct(ctx, "202211111057", migratePlaylistsQueuesToFullID),
+ constructNoTx(ctx, "202212272312", backupDBPre016),
construct(ctx, "202304221528", migratePlaylistsToM3U),
construct(ctx, "202305301718", migratePlayCountToLength),
construct(ctx, "202307281628", migrateAlbumArtistsMany2Many),
construct(ctx, "202309070009", migrateDeleteArtistCoverField),
construct(ctx, "202309131743", migrateArtistInfo),
+ construct(ctx, "202309161411", migratePlaylistsPaths),
+ construct(ctx, "202310252205", migrateAlbumTagArtistString),
+ construct(ctx, "202310281803", migrateTrackArtists),
+ construct(ctx, "202311062259", migrateArtistAppearances),
+ construct(ctx, "202311072309", migrateAlbumInfo),
+ construct(ctx, "202311082304", migrateTemporaryDisplayAlbumArtist),
}
return gormigrate.
@@ -67,12 +79,18 @@ func (db *DB) Migrate(ctx MigrationContext) error {
}
func construct(ctx MigrationContext, id string, f func(*gorm.DB, MigrationContext) error) *gormigrate.Migration {
+ return constructNoTx(ctx, id, func(db *gorm.DB, ctx MigrationContext) error {
+ return db.Transaction(func(tx *gorm.DB) error {
+ return f(tx, ctx)
+ })
+ })
+}
+
+func constructNoTx(ctx MigrationContext, id string, f func(*gorm.DB, MigrationContext) error) *gormigrate.Migration {
return &gormigrate.Migration{
ID: id,
Migrate: func(db *gorm.DB) error {
- tx := db.Begin()
- defer tx.Commit()
- if err := f(tx, ctx); err != nil {
+ if err := f(db, ctx); err != nil {
return fmt.Errorf("%q: %w", id, err)
}
log.Printf("migration '%s' finished", id)
@@ -353,7 +371,7 @@ func migratePublicPlaylist(tx *gorm.DB, _ MigrationContext) error {
if !tx.HasTable("playlists") {
return nil
}
- return tx.AutoMigrate(_OldPlaylist{}).Error
+ return tx.AutoMigrate(__OldPlaylist{}).Error
}
func migratePodcastDropUserID(tx *gorm.DB, _ MigrationContext) error {
@@ -478,11 +496,11 @@ func migratePlaylistsToM3U(tx *gorm.DB, ctx MigrationContext) error {
return track.AbsPath()
case specid.PodcastEpisode:
var pe PodcastEpisode
- tx.Where("id=?", id.Value).Find(&pe)
- if pe.Path == "" {
+ tx.Where("id=?", id.Value).Preload("Podcast").Find(&pe)
+ if pe.Filename == "" {
return ""
}
- return filepath.Join(ctx.PodcastsPath, pe.Path)
+ return filepath.Join(ctx.PodcastsPath, fileutil.Safe(pe.Podcast.Title), pe.Filename)
}
return ""
}
@@ -492,7 +510,7 @@ func migratePlaylistsToM3U(tx *gorm.DB, ctx MigrationContext) error {
return fmt.Errorf("create playlists store: %w", err)
}
- var prevs []*_OldPlaylist
+ var prevs []*__OldPlaylist
if err := tx.Find(&prevs).Error; err != nil {
return fmt.Errorf("fetch old playlists: %w", err)
}
@@ -613,3 +631,174 @@ func migrateArtistInfo(tx *gorm.DB, _ MigrationContext) error {
).
Error
}
+
+func migratePlaylistsPaths(tx *gorm.DB, ctx MigrationContext) error {
+ if !tx.Dialect().HasColumn("podcast_episodes", "path") {
+ return nil
+ }
+ if !tx.Dialect().HasColumn("podcasts", "image_path") {
+ return nil
+ }
+
+ step := tx.Exec(`
+ ALTER TABLE podcasts RENAME COLUMN image_path TO image
+ `)
+ if err := step.Error; err != nil {
+ return fmt.Errorf("step drop podcast_episodes path: %w", err)
+ }
+
+ step = tx.AutoMigrate(
+ Podcast{},
+ PodcastEpisode{},
+ )
+ if err := step.Error; err != nil {
+ return fmt.Errorf("step auto migrate: %w", err)
+ }
+
+ var podcasts []*Podcast
+ if err := tx.Find(&podcasts).Error; err != nil {
+ return fmt.Errorf("step load: %w", err)
+ }
+
+ for _, p := range podcasts {
+ p.Image = filepath.Base(p.Image)
+ if err := tx.Save(p).Error; err != nil {
+ return fmt.Errorf("saving podcast for cover %d: %w", p.ID, err)
+ }
+
+ oldPath, err := fileutil.First(
+ filepath.Join(ctx.PodcastsPath, fileutil.Safe(p.Title)),
+ filepath.Join(ctx.PodcastsPath, strings.ReplaceAll(p.Title, string(filepath.Separator), "_")), // old safe func
+ filepath.Join(ctx.PodcastsPath, p.Title),
+ )
+ if err != nil {
+ log.Printf("error finding old podcast path: %v. ignoring", err)
+ continue
+ }
+ newPath := filepath.Join(ctx.PodcastsPath, fileutil.Safe(p.Title))
+ p.RootDir = newPath
+ if err := tx.Save(p).Error; err != nil {
+ return fmt.Errorf("saving podcast %d: %w", p.ID, err)
+ }
+ if oldPath == newPath {
+ continue
+ }
+ if err := os.Rename(oldPath, newPath); err != nil {
+ return fmt.Errorf("rename podcast path: %w", err)
+ }
+ }
+
+ var podcastEpisodes []*PodcastEpisode
+ if err := tx.Preload("Podcast").Find(&podcastEpisodes, "status=? OR status=?", PodcastEpisodeStatusCompleted, PodcastEpisodeStatusDownloading).Error; err != nil {
+ return fmt.Errorf("step load: %w", err)
+ }
+ for _, pe := range podcastEpisodes {
+ if pe.Filename == "" {
+ continue
+ }
+ oldPath, err := fileutil.First(
+ filepath.Join(pe.Podcast.RootDir, fileutil.Safe(pe.Filename)),
+ filepath.Join(pe.Podcast.RootDir, strings.ReplaceAll(pe.Filename, string(filepath.Separator), "_")), // old safe func
+ filepath.Join(pe.Podcast.RootDir, pe.Filename),
+ )
+ if err != nil {
+ log.Printf("error finding old podcast episode path: %v. ignoring", err)
+ continue
+ }
+ newName := fileutil.Safe(filepath.Base(oldPath))
+ pe.Filename = newName
+ if err := tx.Save(pe).Error; err != nil {
+ return fmt.Errorf("saving podcast episode %d: %w", pe.ID, err)
+ }
+ newPath := filepath.Join(pe.Podcast.RootDir, newName)
+ if oldPath == newPath {
+ continue
+ }
+ if err := os.Rename(oldPath, newPath); err != nil {
+ return fmt.Errorf("rename podcast episode path: %w", err)
+ }
+ }
+
+ step = tx.Exec(`
+ ALTER TABLE podcast_episodes DROP COLUMN path
+ `)
+ if err := step.Error; err != nil {
+ return fmt.Errorf("step drop podcast_episodes path: %w", err)
+ }
+ return nil
+}
+
+func backupDBPre016(tx *gorm.DB, ctx MigrationContext) error {
+ if !ctx.Production {
+ return nil
+ }
+ return Dump(context.Background(), tx, fmt.Sprintf("%s.%d.bak", ctx.DBPath, time.Now().Unix()))
+}
+
+func migrateAlbumTagArtistString(tx *gorm.DB, _ MigrationContext) error {
+ return tx.AutoMigrate(Album{}).Error
+}
+
+func migrateTrackArtists(tx *gorm.DB, _ MigrationContext) error {
+ // gorms seems to want to create the table automatically without ON DELETE rules
+ step := tx.DropTableIfExists(TrackArtist{})
+ if err := step.Error; err != nil {
+ return fmt.Errorf("step drop prev: %w", err)
+ }
+ return tx.AutoMigrate(TrackArtist{}).Error
+}
+
+func migrateArtistAppearances(tx *gorm.DB, _ MigrationContext) error {
+ // gorms seems to want to create the table automatically without ON DELETE rules
+ step := tx.DropTableIfExists(ArtistAppearances{})
+ if err := step.Error; err != nil {
+ return fmt.Errorf("step drop prev: %w", err)
+ }
+
+ step = tx.AutoMigrate(ArtistAppearances{})
+ if err := step.Error; err != nil {
+ return fmt.Errorf("step auto migrate: %w", err)
+ }
+
+ step = tx.Exec(`
+ INSERT INTO artist_appearances (artist_id, album_id)
+ SELECT artist_id, album_id
+ FROM album_artists
+ `)
+ if err := step.Error; err != nil {
+ return fmt.Errorf("step transfer album artists: %w", err)
+ }
+
+ step = tx.Exec(`
+ INSERT OR IGNORE INTO artist_appearances (artist_id, album_id)
+ SELECT track_artists.artist_id, tracks.album_id
+ FROM track_artists
+ JOIN tracks ON tracks.id=track_artists.track_id
+ `)
+ if err := step.Error; err != nil {
+ return fmt.Errorf("step transfer album artists: %w", err)
+ }
+
+ return nil
+}
+
+func migrateAlbumInfo(tx *gorm.DB, _ MigrationContext) error {
+ return tx.AutoMigrate(
+ AlbumInfo{},
+ ).
+ Error
+}
+
+func migrateTemporaryDisplayAlbumArtist(tx *gorm.DB, _ MigrationContext) error {
+ // keep some things working so that people have an album.tag_artist_id until their next full scan
+ return tx.Exec(`
+ UPDATE albums
+ SET tag_album_artist=(
+ SELECT group_concat(artists.name, ', ')
+ FROM artists
+ JOIN album_artists ON album_artists.artist_id=artists.id AND album_artists.album_id=albums.id
+ GROUP BY album_artists.album_id
+ )
+ WHERE tag_album_artist=''
+ `).Error
+}
diff --git a/db/migrations_old_models.go b/db/migrations_old_models.go
index ea727aa..7df9f45 100644
--- a/db/migrations_old_models.go
+++ b/db/migrations_old_models.go
@@ -2,7 +2,7 @@ package db
import "time"
-type _OldPlaylist struct {
+type __OldPlaylist struct { //nolint: revive,stylecheck
ID int `gorm:"primary_key"`
CreatedAt time.Time
UpdatedAt time.Time
@@ -15,6 +15,6 @@ type _OldPlaylist struct {
IsPublic bool `sql:"default: null"`
}
-func (_OldPlaylist) TableName() string {
+func (__OldPlaylist) TableName() string {
return "playlists"
}
diff --git a/db/model.go b/db/model.go
deleted file mode 100644
index 5b38821..0000000
--- a/db/model.go
+++ /dev/null
@@ -1,463 +0,0 @@
-// Package db provides database helpers and models
-//
-//nolint:lll // struct tags get very long and can't be split
-package db
-
-// see this db fiddle to mess around with the schema
-// https://www.db-fiddle.com/f/wJ7z8L7mu6ZKaYmWk1xr1p/5
-
-import (
- "fmt"
- "path"
- "path/filepath"
- "sort"
- "strings"
- "time"
-
- "go.senan.xyz/gonic/mime"
-
- // TODO: remove this dep
- "go.senan.xyz/gonic/server/ctrlsubsonic/specid"
-)
-
-func splitIDs(in, sep string) []specid.ID {
- if in == "" {
- return []specid.ID{}
- }
- parts := strings.Split(in, sep)
- ret := make([]specid.ID, 0, len(parts))
- for _, p := range parts {
- id, _ := specid.New(p)
- ret = append(ret, id)
- }
- return ret
-}
-
-func join[T fmt.Stringer](in []T, sep string) string {
- if in == nil {
- return ""
- }
- strs := make([]string, 0, len(in))
- for _, id := range in {
- strs = append(strs, id.String())
- }
- return strings.Join(strs, sep)
-}
-
-type Artist struct {
- ID int `gorm:"primary_key"`
- Name string `gorm:"not null; unique_index"`
- NameUDec string `sql:"default: null"`
- Albums []*Album `gorm:"many2many:album_artists"`
- AlbumCount int `sql:"-"`
- ArtistStar *ArtistStar
- ArtistRating *ArtistRating
- AverageRating float64 `sql:"default: null"`
- Info *ArtistInfo `gorm:"foreignkey:id"`
-}
-
-func (a *Artist) SID() *specid.ID {
- return &specid.ID{Type: specid.Artist, Value: a.ID}
-}
-
-func (a *Artist) IndexName() string {
- if len(a.NameUDec) > 0 {
- return a.NameUDec
- }
- return a.Name
-}
-
-type Genre struct {
- ID int `gorm:"primary_key"`
- Name string `gorm:"not null; unique_index"`
- AlbumCount int `sql:"-"`
- TrackCount int `sql:"-"`
-}
-
-// AudioFile is used to avoid some duplication in handlers_raw.go
-// between Track and Podcast
-type AudioFile interface {
- Ext() string
- MIME() string
- AudioFilename() string
- AudioBitrate() int
- AudioLength() int
-}
-
-type Track struct {
- ID int `gorm:"primary_key"`
- CreatedAt time.Time
- UpdatedAt time.Time
- Filename string `gorm:"not null; unique_index:idx_folder_filename" sql:"default: null"`
- FilenameUDec string `sql:"default: null"`
- Album *Album
- AlbumID int `gorm:"not null; unique_index:idx_folder_filename" sql:"default: null; type:int REFERENCES albums(id) ON DELETE CASCADE"`
- Genres []*Genre `gorm:"many2many:track_genres"`
- Size int `sql:"default: null"`
- Length int `sql:"default: null"`
- Bitrate int `sql:"default: null"`
- TagTitle string `sql:"default: null"`
- TagTitleUDec string `sql:"default: null"`
- TagTrackArtist string `sql:"default: null"`
- TagTrackNumber int `sql:"default: null"`
- TagDiscNumber int `sql:"default: null"`
- TagBrainzID string `sql:"default: null"`
- TrackStar *TrackStar
- TrackRating *TrackRating
- AverageRating float64 `sql:"default: null"`
-}
-
-func (t *Track) AudioLength() int { return t.Length }
-func (t *Track) AudioBitrate() int { return t.Bitrate }
-
-func (t *Track) SID() *specid.ID {
- return &specid.ID{Type: specid.Track, Value: t.ID}
-}
-
-func (t *Track) AlbumSID() *specid.ID {
- return &specid.ID{Type: specid.Album, Value: t.AlbumID}
-}
-
-func (t *Track) Ext() string {
- return filepath.Ext(t.Filename)
-}
-
-func (t *Track) AudioFilename() string {
- return t.Filename
-}
-
-func (t *Track) MIME() string {
- return mime.TypeByExtension(filepath.Ext(t.Filename))
-}
-
-func (t *Track) AbsPath() string {
- if t.Album == nil {
- return ""
- }
- return path.Join(
- t.Album.RootDir,
- t.Album.LeftPath,
- t.Album.RightPath,
- t.Filename,
- )
-}
-
-func (t *Track) RelPath() string {
- if t.Album == nil {
- return ""
- }
- return path.Join(
- t.Album.LeftPath,
- t.Album.RightPath,
- t.Filename,
- )
-}
-
-func (t *Track) GenreStrings() []string {
- strs := make([]string, 0, len(t.Genres))
- for _, genre := range t.Genres {
- strs = append(strs, genre.Name)
- }
- return strs
-}
-
-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"`
- LastFMSession string `sql:"default: null"`
- ListenBrainzURL string `sql:"default: null"`
- ListenBrainzToken string `sql:"default: null"`
- IsAdmin bool `sql:"default: null"`
- Avatar []byte `sql:"default: null"`
-}
-
-type Setting struct {
- Key SettingKey `gorm:"not null; primary_key; auto_increment:false" sql:"default: null"`
- Value string `sql:"default: null"`
-}
-
-type Play struct {
- ID int `gorm:"primary_key"`
- User *User
- UserID int `gorm:"not null; index" sql:"default: null; type:int REFERENCES users(id) ON DELETE CASCADE"`
- Album *Album
- AlbumID int `gorm:"not null; index" sql:"default: null; type:int REFERENCES albums(id) ON DELETE CASCADE"`
- Time time.Time `sql:"default: null"`
- Count int
- Length int
-}
-
-type Album struct {
- ID int `gorm:"primary_key"`
- CreatedAt time.Time
- UpdatedAt time.Time
- ModifiedAt time.Time
- LeftPath string `gorm:"unique_index:idx_album_abs_path"`
- RightPath string `gorm:"not null; unique_index:idx_album_abs_path" sql:"default: null"`
- RightPathUDec string `sql:"default: null"`
- Parent *Album
- ParentID int `sql:"default: null; type:int REFERENCES albums(id) ON DELETE CASCADE"`
- RootDir string `gorm:"unique_index:idx_album_abs_path" sql:"default: null"`
- Genres []*Genre `gorm:"many2many:album_genres"`
- Cover string `sql:"default: null"`
- Artists []*Artist `gorm:"many2many:album_artists"`
- TagTitle string `sql:"default: null"`
- TagTitleUDec string `sql:"default: null"`
- TagBrainzID string `sql:"default: null"`
- TagYear int `sql:"default: null"`
- Tracks []*Track
- ChildCount int `sql:"-"`
- Duration int `sql:"-"`
- AlbumStar *AlbumStar
- AlbumRating *AlbumRating
- AverageRating float64 `sql:"default: null"`
-}
-
-func (a *Album) SID() *specid.ID {
- return &specid.ID{Type: specid.Album, Value: a.ID}
-}
-
-func (a *Album) ParentSID() *specid.ID {
- return &specid.ID{Type: specid.Album, Value: a.ParentID}
-}
-
-func (a *Album) IndexRightPath() string {
- if len(a.RightPathUDec) > 0 {
- return a.RightPathUDec
- }
- return a.RightPath
-}
-
-func (a *Album) GenreStrings() []string {
- strs := make([]string, 0, len(a.Genres))
- for _, genre := range a.Genres {
- strs = append(strs, genre.Name)
- }
- return strs
-}
-
-func (a *Album) ArtistsStrings() []string {
- var artists = append([]*Artist(nil), a.Artists...)
- sort.Slice(artists, func(i, j int) bool {
- return artists[i].ID < artists[j].ID
- })
- strs := make([]string, 0, len(artists))
- for _, artist := range artists {
- strs = append(strs, artist.Name)
- }
- return strs
-}
-
-type PlayQueue struct {
- ID int `gorm:"primary_key"`
- CreatedAt time.Time
- UpdatedAt time.Time
- User *User
- UserID int `sql:"default: null; type:int REFERENCES users(id) ON DELETE CASCADE"`
- Current string
- Position int
- ChangedBy string
- Items string
-}
-
-func (p *PlayQueue) CurrentSID() *specid.ID {
- id, _ := specid.New(p.Current)
- return &id
-}
-
-func (p *PlayQueue) GetItems() []specid.ID {
- return splitIDs(p.Items, ",")
-}
-
-func (p *PlayQueue) SetItems(items []specid.ID) {
- p.Items = join(items, ",")
-}
-
-type TranscodePreference struct {
- User *User
- UserID int `gorm:"not null; unique_index:idx_user_id_client" sql:"default: null; type:int REFERENCES users(id) ON DELETE CASCADE"`
- Client string `gorm:"not null; unique_index:idx_user_id_client" sql:"default: null"`
- Profile string `gorm:"not null" sql:"default: null"`
-}
-
-type AlbumArtist struct {
- Album *Album
- AlbumID int `gorm:"not null; unique_index:idx_album_id_artist_id" sql:"default: null; type:int REFERENCES albums(id) ON DELETE CASCADE"`
- Artist *Artist
- ArtistID int `gorm:"not null; unique_index:idx_album_id_artist_id" sql:"default: null; type:int REFERENCES artists(id) ON DELETE CASCADE"`
-}
-
-type TrackGenre struct {
- Track *Track
- TrackID int `gorm:"not null; unique_index:idx_track_id_genre_id" sql:"default: null; type:int REFERENCES tracks(id) ON DELETE CASCADE"`
- Genre *Genre
- GenreID int `gorm:"not null; unique_index:idx_track_id_genre_id" sql:"default: null; type:int REFERENCES genres(id) ON DELETE CASCADE"`
-}
-
-type AlbumGenre struct {
- Album *Album
- AlbumID int `gorm:"not null; unique_index:idx_album_id_genre_id" sql:"default: null; type:int REFERENCES albums(id) ON DELETE CASCADE"`
- Genre *Genre
- GenreID int `gorm:"not null; unique_index:idx_album_id_genre_id" sql:"default: null; type:int REFERENCES genres(id) ON DELETE CASCADE"`
-}
-
-type AlbumStar struct {
- UserID int `gorm:"primary_key; not null" sql:"default: null; type:int REFERENCES users(id) ON DELETE CASCADE"`
- AlbumID int `gorm:"primary_key; not null" sql:"default: null; type:int REFERENCES albums(id) ON DELETE CASCADE"`
- StarDate time.Time
-}
-
-type AlbumRating struct {
- UserID int `gorm:"primary_key; not null" sql:"default: null; type:int REFERENCES users(id) ON DELETE CASCADE"`
- AlbumID int `gorm:"primary_key; not null" sql:"default: null; type:int REFERENCES albums(id) ON DELETE CASCADE"`
- Rating int `gorm:"not null; check:(rating >= 1 AND rating <= 5)"`
-}
-
-type ArtistStar struct {
- UserID int `gorm:"primary_key; not null" sql:"default: null; type:int REFERENCES users(id) ON DELETE CASCADE"`
- ArtistID int `gorm:"primary_key; not null" sql:"default: null; type:int REFERENCES artists(id) ON DELETE CASCADE"`
- StarDate time.Time
-}
-
-type ArtistRating struct {
- UserID int `gorm:"primary_key; not null" sql:"default: null; type:int REFERENCES users(id) ON DELETE CASCADE"`
- ArtistID int `gorm:"primary_key; not null" sql:"default: null; type:int REFERENCES artists(id) ON DELETE CASCADE"`
- Rating int `gorm:"not null; check:(rating >= 1 AND rating <= 5)"`
-}
-
-type TrackStar struct {
- UserID int `gorm:"primary_key; not null" sql:"default: null; type:int REFERENCES users(id) ON DELETE CASCADE"`
- TrackID int `gorm:"primary_key; not null" sql:"default: null; type:int REFERENCES tracks(id) ON DELETE CASCADE"`
- StarDate time.Time
-}
-
-type TrackRating struct {
- UserID int `gorm:"primary_key; not null" sql:"default: null; type:int REFERENCES users(id) ON DELETE CASCADE"`
- TrackID int `gorm:"primary_key; not null" sql:"default: null; type:int REFERENCES tracks(id) ON DELETE CASCADE"`
- Rating int `gorm:"not null; check:(rating >= 1 AND rating <= 5)"`
-}
-
-type PodcastAutoDownload string
-
-const (
- PodcastAutoDownloadLatest PodcastAutoDownload = "latest"
- PodcastAutoDownloadNone PodcastAutoDownload = "none"
-)
-
-type Podcast struct {
- ID int `gorm:"primary_key"`
- UpdatedAt time.Time
- ModifiedAt time.Time
- URL string
- Title string
- Description string
- ImageURL string
- ImagePath string
- Error string
- Episodes []*PodcastEpisode
- AutoDownload PodcastAutoDownload
-}
-
-func (p *Podcast) SID() *specid.ID {
- return &specid.ID{Type: specid.Podcast, Value: p.ID}
-}
-
-type PodcastEpisodeStatus string
-
-const (
- PodcastEpisodeStatusDownloading PodcastEpisodeStatus = "downloading"
- PodcastEpisodeStatusSkipped PodcastEpisodeStatus = "skipped"
- PodcastEpisodeStatusDeleted PodcastEpisodeStatus = "deleted"
- PodcastEpisodeStatusCompleted PodcastEpisodeStatus = "completed"
- PodcastEpisodeStatusError PodcastEpisodeStatus = "error"
-)
-
-type PodcastEpisode struct {
- ID int `gorm:"primary_key"`
- CreatedAt time.Time
- UpdatedAt time.Time
- ModifiedAt time.Time
- PodcastID int `gorm:"not null" sql:"default: null; type:int REFERENCES podcasts(id) ON DELETE CASCADE"`
- Title string
- Description string
- PublishDate *time.Time
- AudioURL string
- Bitrate int
- Length int
- Size int
- Path string
- Filename string
- Status PodcastEpisodeStatus
- Error string
- AbsP string `gorm:"-"` // TODO: not this. instead we need some consistent way to get the AbsPath for both tracks and podcast episodes. or just files in general
-}
-
-func (pe *PodcastEpisode) AudioLength() int { return pe.Length }
-func (pe *PodcastEpisode) AudioBitrate() int { return pe.Bitrate }
-
-func (pe *PodcastEpisode) SID() *specid.ID {
- return &specid.ID{Type: specid.PodcastEpisode, Value: pe.ID}
-}
-
-func (pe *PodcastEpisode) PodcastSID() *specid.ID {
- return &specid.ID{Type: specid.Podcast, Value: pe.PodcastID}
-}
-
-func (pe *PodcastEpisode) AudioFilename() string {
- return pe.Filename
-}
-
-func (pe *PodcastEpisode) Ext() string {
- return filepath.Ext(pe.Filename)
-}
-
-func (pe *PodcastEpisode) MIME() string {
- return mime.TypeByExtension(filepath.Ext(pe.Filename))
-}
-
-func (pe *PodcastEpisode) AbsPath() string {
- return pe.AbsP
-}
-
-type Bookmark struct {
- ID int `gorm:"primary_key"`
- User *User
- UserID int `sql:"default: null; type:int REFERENCES users(id) ON DELETE CASCADE"`
- Position int
- Comment string
- EntryIDType string
- EntryID int
- CreatedAt time.Time
- UpdatedAt time.Time
-}
-
-type InternetRadioStation struct {
- ID int `gorm:"primary_key"`
- StreamURL string
- Name string
- HomepageURL string
-}
-
-func (ir *InternetRadioStation) SID() *specid.ID {
- return &specid.ID{Type: specid.InternetRadioStation, Value: ir.ID}
-}
-
-type ArtistInfo struct {
- ID int `gorm:"primary_key" sql:"type:int REFERENCES artists(id) ON DELETE CASCADE"`
- CreatedAt time.Time
- UpdatedAt time.Time `gorm:"index"`
- Biography string
- MusicBrainzID string
- LastFMURL string
- ImageURL string
- SimilarArtists string
- TopTracks string
-}
-
-func (p *ArtistInfo) GetSimilarArtists() []string { return strings.Split(p.SimilarArtists, ";") }
-func (p *ArtistInfo) SetSimilarArtists(items []string) { p.SimilarArtists = strings.Join(items, ";") }
-
-func (p *ArtistInfo) GetTopTracks() []string { return strings.Split(p.TopTracks, ";") }
-func (p *ArtistInfo) SetTopTracks(items []string) { p.TopTracks = strings.Join(items, ";") }
diff --git a/fileutil/fileutil.go b/fileutil/fileutil.go
new file mode 100644
index 0000000..8ad23ff
--- /dev/null
+++ b/fileutil/fileutil.go
@@ -0,0 +1,56 @@
+// TODO: this package shouldn't really exist. we can usually just attempt our normal filesystem operations
+// and handle errors atomically. eg.
+// - Safe could instead be try create file, handle error
+// - Unique could be try create file, on err create file (1), etc
+package fileutil
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+ "regexp"
+ "strings"
+)
+
+var nonAlphaNumExpr = regexp.MustCompile("[^a-zA-Z0-9_.]+")
+
+func Safe(filename string) string {
+ filename = nonAlphaNumExpr.ReplaceAllString(filename, "")
+ return filename
+}
+
+// try to find a unqiue file (or dir) name. incrementing like "example (1)"
+func Unique(base, filename string) (string, error) {
+ return unique(base, filename, 0)
+}
+
+func unique(base, filename string, count uint) (string, error) {
+ var suffix string
+ if count > 0 {
+ suffix = fmt.Sprintf(" (%d)", count)
+ }
+ path := base + suffix
+ if filename != "" {
+ noExt := strings.TrimSuffix(filename, filepath.Ext(filename))
+ path = filepath.Join(base, noExt+suffix+filepath.Ext(filename))
+ }
+ _, err := os.Stat(path)
+ if os.IsNotExist(err) {
+ return path, nil
+ }
+ if err != nil {
+ return "", err
+ }
+ return unique(base, filename, count+1)
+}
+
+func First(path ...string) (string, error) {
+ var err error
+ for _, p := range path {
+ _, err = os.Stat(p)
+ if err == nil {
+ return p, nil
+ }
+ }
+ return "", err
+}
diff --git a/fileutil/fileutil_test.go b/fileutil/fileutil_test.go
new file mode 100644
index 0000000..a8cb480
--- /dev/null
+++ b/fileutil/fileutil_test.go
@@ -0,0 +1,59 @@
+package fileutil
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestUniquePath(t *testing.T) {
+ t.Parallel()
+
+ unq := func(base, filename string, count uint) string {
+ r, err := unique(base, filename, count)
+ require.NoError(t, err)
+ return r
+ }
+
+ require.Equal(t, "test/wow.mp3", unq("test", "wow.mp3", 0))
+ require.Equal(t, "test/wow (1).mp3", unq("test", "wow.mp3", 1))
+ require.Equal(t, "test/wow (2).mp3", unq("test", "wow.mp3", 2))
+
+ require.Equal(t, "test", unq("test", "", 0))
+ require.Equal(t, "test (1)", unq("test", "", 1))
+
+ base := filepath.Join(t.TempDir(), "a")
+
+ require.NoError(t, os.MkdirAll(base, os.ModePerm))
+
+ next := base + " (1)"
+ require.Equal(t, next, unq(base, "", 0))
+
+ require.NoError(t, os.MkdirAll(next, os.ModePerm))
+
+ next = base + " (2)"
+ require.Equal(t, next, unq(base, "", 0))
+
+ _, err := os.Create(filepath.Join(base, "test.mp3"))
+ require.NoError(t, err)
+ require.Equal(t, filepath.Join(base, "test (1).mp3"), unq(base, "test.mp3", 0))
+}
+
+func TestFirst(t *testing.T) {
+ t.Parallel()
+
+ base := t.TempDir()
+ name := filepath.Join(base, "test")
+ _, err := os.Create(name)
+ require.NoError(t, err)
+
+ p := func(name string) string {
+ return filepath.Join(base, name)
+ }
+
+ r, err := First(p("one"), p("two"), p("test"), p("four"))
+ require.NoError(t, err)
+ require.Equal(t, p("test"), r)
+}
diff --git a/go.mod b/go.mod
index 83284ef..41c6dc3 100644
--- a/go.mod
+++ b/go.mod
@@ -9,29 +9,26 @@ require (
github.com/disintegration/imaging v1.6.2
github.com/dustin/go-humanize v1.0.1
github.com/fatih/structs v1.1.0
- github.com/fsnotify/fsnotify v1.6.0
+ github.com/fsnotify/fsnotify v1.7.0
github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510
- github.com/google/uuid v1.3.1
- github.com/gorilla/handlers v1.5.1
- github.com/gorilla/mux v1.8.0
- github.com/gorilla/securecookie v1.1.1
- github.com/gorilla/sessions v1.2.1
+ github.com/google/uuid v1.4.0
+ github.com/gorilla/securecookie v1.1.2
+ github.com/gorilla/sessions v1.2.2
github.com/jinzhu/gorm v1.9.17-0.20211120011537-5c235b72a414
github.com/josephburnett/jd v1.5.2
- github.com/mattn/go-sqlite3 v1.14.17
+ github.com/mattn/go-sqlite3 v1.14.18
github.com/mitchellh/mapstructure v1.5.0
github.com/mmcdole/gofeed v1.2.1
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646
- github.com/oklog/run v1.1.0
- github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c
github.com/peterbourgon/ff v1.7.1
github.com/philippta/go-template v0.0.0-20220911145045-4556aca435e4
github.com/rainycape/unidecode v0.0.0-20150907023854-cb7f23ec59be
github.com/sentriz/audiotags v0.0.0-20230419125925-8886243b2137
github.com/sentriz/gormstore v0.0.0-20220105134332-64e31f7f6981
github.com/stretchr/testify v1.8.1
- golang.org/x/exp v0.0.0-20230905200255-921286631fa9
- golang.org/x/net v0.15.0
+ golang.org/x/exp v0.0.0-20231006140011-7918f672742d
+ golang.org/x/net v0.17.0
+ golang.org/x/sync v0.5.0
gopkg.in/gormigrate.v1 v1.6.0
jaytaylor.com/html2text v0.0.0-20230321000545-74c2419ad056
)
@@ -45,7 +42,7 @@ require (
github.com/go-ldap/ldap v3.0.3+incompatible // indirect
github.com/go-openapi/jsonpointer v0.19.5 // indirect
github.com/go-openapi/swag v0.21.1 // indirect
- github.com/gorilla/context v1.1.1 // indirect
+ github.com/gorilla/context v1.1.2 // indirect
github.com/huandu/xstrings v1.4.0 // indirect
github.com/imdario/mergo v0.3.16 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
@@ -65,10 +62,10 @@ require (
github.com/rivo/uniseg v0.4.4 // indirect
github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect
gopkg.in/asn1-ber.v1 v1.0.0-20181015200546-f715ec2f112d // indirect
- golang.org/x/crypto v0.13.0 // indirect
- golang.org/x/image v0.12.0 // indirect
- golang.org/x/sys v0.12.0 // indirect
- golang.org/x/text v0.13.0 // indirect
+ golang.org/x/crypto v0.14.0 // indirect
+ golang.org/x/image v0.13.0 // indirect
+ golang.org/x/sys 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/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
diff --git a/go.sum b/go.sum
index 5d0d312..df9ff4b 100644
--- a/go.sum
+++ b/go.sum
@@ -37,6 +37,8 @@ github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4
github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw=
github.com/go-ldap/ldap v3.0.3+incompatible h1:HTeSZO8hWMS1Rgb2Ziku6b8a7qRIZZMHjsvuZyatzwk=
github.com/go-ldap/ldap v3.0.3+incompatible/go.mod h1:qfd9rJvER9Q0/D/Sqn1DfHRoBp40uXYvFoEVrNEPqRc=
+github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA=
+github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM=
github.com/go-openapi/jsonpointer v0.19.5 h1:gZr+CIYByUqjcgeLXnQu2gHYQC9o73G2XUeOFYEICuY=
github.com/go-openapi/jsonpointer v0.19.5/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg=
github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk=
@@ -51,20 +53,21 @@ github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe/go.mod h1:8vg3r2V
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
+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 h1:KjJaJ9iWZ3jOFZIf1Lqf4laDRCasjl0BCmnEGxkdLb4=
-github.com/google/uuid v1.3.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
-github.com/gorilla/context v1.1.1 h1:AWwleXJkX/nhcU9bZSnZoi3h/qGYqQAGhq6zZe/aQW8=
+github.com/google/uuid v1.4.0 h1:MtMxsa51/r9yyhkyLsVeVt0B+BGQZzpQiTQ4eHZ8bc4=
+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/handlers v1.5.1 h1:9lRY6j8DEeeBT10CvO9hGW0gmky0BprnvDI5vfhUHH4=
-github.com/gorilla/handlers v1.5.1/go.mod h1:t8XrUpc4KVXb7HGyJ4/cEnwQiaxrX/hz1Zv/4g96P1Q=
-github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI=
-github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
-github.com/gorilla/securecookie v1.1.1 h1:miw7JPhV+b/lAHSXz4qd/nN9jRiAFV5FwjeKyCS8BvQ=
+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/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4=
-github.com/gorilla/sessions v1.2.1 h1:DHd3rPN5lE3Ts3D8rKkQ8x/0kqfeNmBAaiSi+o7FsgI=
+github.com/gorilla/securecookie v1.1.2 h1:YCIWL56dvtr73r6715mJs5ZvhtnY73hBvEF8kXD8ePA=
+github.com/gorilla/securecookie v1.1.2/go.mod h1:NfCASbcHqRSY+3a8tlWJwsQap2VX5pwzwo4h3eOamfo=
github.com/gorilla/sessions v1.2.1/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/zI+bUmuGM=
+github.com/gorilla/sessions v1.2.2 h1:lqzMYz6bOfvn2WriPUjNByzeXIlVzURcPmgMczkmTjY=
+github.com/gorilla/sessions v1.2.2/go.mod h1:ePLdVu+jbEgHH+KWw8I1z2wqd0BAdAQh/8LRvBeoNcQ=
github.com/huandu/xstrings v1.4.0 h1:D17IlohoQq4UcpqD7fDk80P7l+lwAmlFaBHgOipl2FU=
github.com/huandu/xstrings v1.4.0/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE=
github.com/imdario/mergo v0.3.16 h1:wwQJbIsHYGMUyLSPrEq1CT16AhnhNJQ51+4fdHUnCl4=
@@ -106,8 +109,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-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.17 h1:mCRHCLDUBXgpKAqIKsaAaAsrAlbkeomtRFKXh2L6YIM=
-github.com/mattn/go-sqlite3 v1.14.17/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg=
+github.com/mattn/go-sqlite3 v1.14.18 h1:JL0eqdCOq6DJVNPSvArO/bIV9/P7fbGrV00LZHc+5aI=
+github.com/mattn/go-sqlite3 v1.14.18/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg=
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/go-wordwrap v1.0.0/go.mod h1:ZXFpozHsX6DPmq2I0TCekCxypsnAUbP2oI0UX1GXzOo=
@@ -128,12 +131,8 @@ github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 h1:zYyBkD/k9seD2A7fsi6
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646/go.mod h1:jpp1/29i3P1S/RLdc7JQKbRpFeM1dOBd8T9ki5s+AY8=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
-github.com/oklog/run v1.1.0 h1:GEenZ1cK0+q0+wsJew9qUg/DyD8k3JzYsZAi5gYi2mA=
-github.com/oklog/run v1.1.0/go.mod h1:sVPdnTZT1zYwAJeCMu2Th4T21pA3FPOQRfWjQlk7DVU=
github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec=
github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY=
-github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c h1:rp5dCmg/yLR3mgFuSOe4oEnDDmGLROTvMragMUXpTQw=
-github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c/go.mod h1:X07ZCGwUbLaax7L0S3Tw4hpejzu63ZrrQiUe6W0hcy0=
github.com/pelletier/go-toml v1.6.0/go.mod h1:5N711Q9dKgbdkxHL+MEfF31hpT7l0S0s/t2kKREewys=
github.com/peterbourgon/ff v1.7.1 h1:xt1lxTG+Nr2+tFtysY7abFgPoH3Lug8CwYJMOmJRXhk=
github.com/peterbourgon/ff v1.7.1/go.mod h1:fYI5YA+3RDqQRExmFbHnBjEeWzh9TrS8rnRpEq7XIg0=
@@ -167,13 +166,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-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.13.0 h1:mvySKfSWJ+UKUii46M40LOvyWfN0s2U+46/jDd0e6Ck=
-golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc=
-golang.org/x/exp v0.0.0-20230905200255-921286631fa9 h1:GoHiUyI/Tp2nVkLI2mCxVkOjsbSXD66ic0XW0js0R9g=
-golang.org/x/exp v0.0.0-20230905200255-921286631fa9/go.mod h1:S2oDrQGGwySpoQPVqRShND87VCbxmc6bL1Yd2oYrm6k=
+golang.org/x/crypto v0.14.0 h1:wBqGXzWJW6m1XrIKlAH0Hs1JJ7+9KBwnIO8v66Q9cHc=
+golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4=
+golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI=
+golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo=
golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
-golang.org/x/image v0.12.0 h1:w13vZbU4o5rKOFFR8y7M+c4A5jXDC0uXTdHYRP8X2DQ=
-golang.org/x/image v0.12.0/go.mod h1:Lu90jvHG7GfemOIcldsh9A2hS01ocl6oNO7ype5mEnk=
+golang.org/x/image v0.13.0 h1:3cge/F/QTkNLauhf2QoE9zp+7sr+ZcL4HnoZmdwg9sg=
+golang.org/x/image v0.13.0/go.mod h1:6mmbMOeV28HuMTgA6OSRkdXKYw/t5W9Uwn2Yv1r3Yxk=
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/net v0.0.0-20180218175443-cbe0f9307d01/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
@@ -188,11 +187,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.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.15.0 h1:ugBLEUaxABaB5AJqW9enI0ACdci2RUd4eP51NTBvuJ8=
-golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk=
+golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM=
+golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE=
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.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sync v0.5.0 h1:60k92dhOjHxJkrqnwsfl8KuaHbn/5dl0lUPUklKo3qE=
+golang.org/x/sync v0.5.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-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
@@ -201,11 +202,10 @@ golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
-golang.org/x/sys v0.0.0-20220908164124-27713097b956/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.12.0 h1:CM0HF96J0hcLAwsHPJZjfdNzs0gftsLfgKt57wWHJ0o=
-golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.14.0 h1:Vz7Qs629MkJkGyHxUlRHizWJRG2j8fbQKjELVSNhy7Q=
+golang.org/x/sys v0.14.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-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
@@ -216,8 +216,8 @@ golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
-golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k=
-golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
+golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
+golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
diff --git a/handlerutil/handlerutil.go b/handlerutil/handlerutil.go
new file mode 100644
index 0000000..860f91d
--- /dev/null
+++ b/handlerutil/handlerutil.go
@@ -0,0 +1,133 @@
+package handlerutil
+
+import (
+ "fmt"
+ "log"
+ "net/http"
+ "strings"
+)
+
+type Middleware func(http.Handler) http.Handler
+
+func Chain(middlewares ...Middleware) Middleware {
+ return func(final http.Handler) http.Handler {
+ for i := len(middlewares) - 1; i >= 0; i-- {
+ final = middlewares[i](final)
+ }
+ return final
+ }
+}
+
+func TrimPathSuffix(suffix string) Middleware {
+ return func(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ r.URL.Path = strings.TrimSuffix(r.URL.Path, suffix)
+ next.ServeHTTP(w, r)
+ })
+ }
+}
+
+func Log(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ sw := &statusWriter{ResponseWriter: w}
+ next.ServeHTTP(sw, r)
+ log.Printf("response %s %s %v", statusToBlock(sw.status), r.Method, r.URL)
+ })
+}
+
+func BasicCORS(next http.Handler) http.Handler {
+ allowMethods := strings.Join(
+ []string{http.MethodPost, http.MethodGet, http.MethodOptions, http.MethodPut, http.MethodDelete},
+ ", ",
+ )
+ allowHeaders := strings.Join(
+ []string{"Accept", "Content-Type", "Content-Length", "Accept-Encoding", "X-CSRF-Token", "Authorization"},
+ ", ",
+ )
+
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Access-Control-Allow-Origin", "*")
+ w.Header().Set("Access-Control-Allow-Methods", allowMethods)
+ w.Header().Set("Access-Control-Allow-Headers", allowHeaders)
+ if r.Method == http.MethodOptions {
+ return
+ }
+ next.ServeHTTP(w, r)
+ })
+}
+
+func Redirect(to string) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ http.Redirect(w, r, to, http.StatusSeeOther)
+ })
+}
+
+func Message(message string) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ fmt.Fprintln(w, message)
+ })
+}
+
+func BaseURL(r *http.Request) string {
+ fallbackProtocoll := "http"
+ if r.TLS != nil {
+ fallbackProtocoll = "https"
+ }
+ fallbackHost := "localhost:4747"
+ scheme := first(
+ r.Header.Get("X-Forwarded-Proto"),
+ r.Header.Get("X-Forwarded-Scheme"),
+ r.URL.Scheme,
+ fallbackProtocoll,
+ )
+ host := first(
+ r.Header.Get("X-Forwarded-Host"),
+ r.Host,
+ fallbackHost,
+ )
+ return fmt.Sprintf("%s://%s", scheme, host)
+}
+
+type statusWriter struct {
+ http.ResponseWriter
+ status int
+}
+
+func (w *statusWriter) WriteHeader(status int) {
+ w.status = status
+ w.ResponseWriter.WriteHeader(status)
+}
+
+func (w *statusWriter) Write(b []byte) (int, error) {
+ if w.status == 0 {
+ w.status = 200
+ }
+ return w.ResponseWriter.Write(b)
+}
+
+func statusToBlock(code int) string {
+ var bg int
+ switch {
+ case code >= 500:
+ bg = 41 // bright red
+ case code >= 400:
+ bg = 43 // bright orange
+ case code >= 300:
+ bg = 46 // bright cyan
+ case code >= 200:
+ bg = 42 // bright green
+ default:
+ bg = 47 // bright white (grey)
+ }
+ return fmt.Sprintf("\u001b[%d;1m %d \u001b[0m", bg, code)
+}
+
+func first[T comparable](vs ...T) T {
+ var z T
+ for _, s := range vs {
+ if s != z {
+ return s
+ }
+ }
+ return z
+}
diff --git a/infocache/albuminfocache/albuminfocache.go b/infocache/albuminfocache/albuminfocache.go
new file mode 100644
index 0000000..f9c9677
--- /dev/null
+++ b/infocache/albuminfocache/albuminfocache.go
@@ -0,0 +1,81 @@
+//nolint:revive
+package albuminfocache
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "time"
+
+ "github.com/jinzhu/gorm"
+ "go.senan.xyz/gonic/db"
+ "go.senan.xyz/gonic/lastfm"
+)
+
+const keepFor = 30 * time.Hour * 24
+
+type AlbumInfoCache struct {
+ db *db.DB
+ lastfmClient *lastfm.Client
+}
+
+func New(db *db.DB, lastfmClient *lastfm.Client) *AlbumInfoCache {
+ return &AlbumInfoCache{db: db, lastfmClient: lastfmClient}
+}
+
+func (a *AlbumInfoCache) GetOrLookup(ctx context.Context, albumID int) (*db.AlbumInfo, error) {
+ var album db.Album
+ if err := a.db.Find(&album, "id=?", albumID).Error; err != nil {
+ return nil, fmt.Errorf("find album in db: %w", err)
+ }
+ if album.TagAlbumArtist == "" || album.TagTitle == "" {
+ return nil, fmt.Errorf("no metadata to look up")
+ }
+
+ var albumInfo db.AlbumInfo
+ if err := a.db.Find(&albumInfo, "id=?", albumID).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil, fmt.Errorf("find album info in db: %w", err)
+ }
+
+ if albumInfo.ID == 0 || time.Since(albumInfo.UpdatedAt) > keepFor {
+ return a.Lookup(ctx, &album)
+ }
+
+ return &albumInfo, nil
+}
+
+func (a *AlbumInfoCache) Get(ctx context.Context, albumID int) (*db.AlbumInfo, error) {
+ var albumInfo db.AlbumInfo
+ if err := a.db.Find(&albumInfo, "id=?", albumID).Error; err != nil {
+ return nil, fmt.Errorf("find album info in db: %w", err)
+ }
+ return &albumInfo, nil
+}
+
+func (a *AlbumInfoCache) Lookup(ctx context.Context, album *db.Album) (*db.AlbumInfo, error) {
+ var albumInfo db.AlbumInfo
+ albumInfo.ID = album.ID
+
+ if err := a.db.FirstOrCreate(&albumInfo, "id=?", albumInfo.ID).Error; err != nil {
+ return nil, fmt.Errorf("first or create album info: %w", err)
+ }
+ if err := a.db.Save(&albumInfo).Error; err != nil {
+ return nil, fmt.Errorf("bump updated_at time: %w", err)
+ }
+
+ info, err := a.lastfmClient.AlbumGetInfo(album.TagAlbumArtist, album.TagTitle)
+ if err != nil {
+ return nil, fmt.Errorf("get upstream info: %w", err)
+ }
+
+ albumInfo.ID = album.ID
+ albumInfo.Notes = info.Wiki.Content
+ albumInfo.MusicBrainzID = info.MBID
+ albumInfo.LastFMURL = info.URL
+
+ if err := a.db.Save(&albumInfo).Error; err != nil {
+ return nil, fmt.Errorf("save upstream info: %w", err)
+ }
+
+ return &albumInfo, nil
+}
diff --git a/server/ctrlsubsonic/artistinfocache/artistinfocache.go b/infocache/artistinfocache/artistinfocache.go
similarity index 65%
rename from server/ctrlsubsonic/artistinfocache/artistinfocache.go
rename to infocache/artistinfocache/artistinfocache.go
index a2630ea..f30c1cb 100644
--- a/server/ctrlsubsonic/artistinfocache/artistinfocache.go
+++ b/infocache/artistinfocache/artistinfocache.go
@@ -10,7 +10,7 @@ import (
"github.com/jinzhu/gorm"
"go.senan.xyz/gonic/db"
- "go.senan.xyz/gonic/scrobble/lastfm"
+ "go.senan.xyz/gonic/lastfm"
)
const keepFor = 30 * time.Hour * 24
@@ -24,11 +24,14 @@ func New(db *db.DB, lastfmClient *lastfm.Client) *ArtistInfoCache {
return &ArtistInfoCache{db: db, lastfmClient: lastfmClient}
}
-func (a *ArtistInfoCache) GetOrLookup(ctx context.Context, apiKey string, artistID int) (*db.ArtistInfo, error) {
+func (a *ArtistInfoCache) GetOrLookup(ctx context.Context, artistID int) (*db.ArtistInfo, error) {
var artist db.Artist
if err := a.db.Find(&artist, "id=?", artistID).Error; err != nil {
return nil, fmt.Errorf("find artist in db: %w", err)
}
+ if artist.Name == "" {
+ return nil, fmt.Errorf("no metadata to look up")
+ }
var artistInfo db.ArtistInfo
if err := a.db.Find(&artistInfo, "id=?", artistID).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
@@ -36,7 +39,7 @@ func (a *ArtistInfoCache) GetOrLookup(ctx context.Context, apiKey string, artist
}
if artistInfo.ID == 0 || artistInfo.Biography == "" /* prev not found maybe */ || time.Since(artistInfo.UpdatedAt) > keepFor {
- return a.Lookup(ctx, apiKey, &artist)
+ return a.Lookup(ctx, &artist)
}
return &artistInfo, nil
@@ -50,15 +53,18 @@ func (a *ArtistInfoCache) Get(ctx context.Context, artistID int) (*db.ArtistInfo
return &artistInfo, nil
}
-func (a *ArtistInfoCache) Lookup(ctx context.Context, apiKey string, artist *db.Artist) (*db.ArtistInfo, error) {
+func (a *ArtistInfoCache) Lookup(ctx context.Context, artist *db.Artist) (*db.ArtistInfo, error) {
var artistInfo db.ArtistInfo
artistInfo.ID = artist.ID
if err := a.db.FirstOrCreate(&artistInfo, "id=?", artistInfo.ID).Error; err != nil {
return nil, fmt.Errorf("first or create artist info: %w", err)
}
+ if err := a.db.Save(&artistInfo).Error; err != nil {
+ return nil, fmt.Errorf("bump updated_at time: %w", err)
+ }
- info, err := a.lastfmClient.ArtistGetInfo(apiKey, artist.Name)
+ info, err := a.lastfmClient.ArtistGetInfo(artist.Name)
if err != nil {
return nil, fmt.Errorf("get upstream info: %w", err)
}
@@ -77,7 +83,7 @@ func (a *ArtistInfoCache) Lookup(ctx context.Context, apiKey string, artist *db.
url, _ := a.lastfmClient.StealArtistImage(info.URL)
artistInfo.ImageURL = url
- topTracksResponse, err := a.lastfmClient.ArtistGetTopTracks(apiKey, artist.Name)
+ topTracksResponse, err := a.lastfmClient.ArtistGetTopTracks(artist.Name)
if err != nil {
return nil, fmt.Errorf("get top tracks: %w", err)
}
@@ -94,29 +100,24 @@ func (a *ArtistInfoCache) Lookup(ctx context.Context, apiKey string, artist *db.
return &artistInfo, nil
}
-func (a *ArtistInfoCache) Refresh(apiKey string, interval time.Duration) error {
- ticker := time.NewTicker(interval)
- for range ticker.C {
- q := a.db.
- Where("artist_infos.id IS NULL OR artist_infos.updated_at", time.Now().Add(-keepFor)).
- Joins("LEFT JOIN artist_infos ON artist_infos.id=artists.id")
+func (a *ArtistInfoCache) Refresh() error {
+ q := a.db.
+ Where("artist_infos.id IS NULL OR artist_infos.updated_at", time.Now().Add(-keepFor)).
+ Joins("LEFT JOIN artist_infos ON artist_infos.id=artists.id")
- var artist db.Artist
- if err := q.Find(&artist).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
- log.Printf("error finding non cached artist: %v", err)
- continue
- }
- if artist.ID == 0 {
- continue
- }
-
- if _, err := a.Lookup(context.Background(), apiKey, &artist); err != nil {
- log.Printf("error looking up non cached artist %s: %v", artist.Name, err)
- continue
- }
-
- log.Printf("cached artist info for %q", artist.Name)
+ var artist db.Artist
+ if err := q.Find(&artist).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
+ return fmt.Errorf("finding non cached artist: %w", err)
}
+ if artist.ID == 0 {
+ return nil
+ }
+
+ if _, err := a.Lookup(context.Background(), &artist); err != nil {
+ return fmt.Errorf("looking up non cached artist %s: %w", artist.Name, err)
+ }
+
+ log.Printf("cached artist info for %q", artist.Name)
return nil
}
diff --git a/server/ctrlsubsonic/artistinfocache/artistinfocache_test.go b/infocache/artistinfocache/artistinfocache_test.go
similarity index 56%
rename from server/ctrlsubsonic/artistinfocache/artistinfocache_test.go
rename to infocache/artistinfocache/artistinfocache_test.go
index 29e923e..3e4edeb 100644
--- a/server/ctrlsubsonic/artistinfocache/artistinfocache_test.go
+++ b/infocache/artistinfocache/artistinfocache_test.go
@@ -9,12 +9,14 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.senan.xyz/gonic/db"
+ "go.senan.xyz/gonic/lastfm"
+ "go.senan.xyz/gonic/lastfm/mockclient"
"go.senan.xyz/gonic/mockfs"
- "go.senan.xyz/gonic/scrobble/lastfm"
- "go.senan.xyz/gonic/scrobble/lastfm/mockclient"
)
func TestInfoCache(t *testing.T) {
+ t.Parallel()
+
m := mockfs.New(t)
m.AddItems()
m.ScanAndClean()
@@ -27,20 +29,25 @@ func TestInfoCache(t *testing.T) {
assert.Nil(artist.Info)
var count atomic.Int32
- lastfmClient := lastfm.NewClientCustom(mockclient.New(t, func(w http.ResponseWriter, r *http.Request) {
- switch method := r.URL.Query().Get("method"); method {
- case "artist.getInfo":
- count.Add(1)
- w.Write(mockclient.ArtistGetInfoResponse)
- case "artist.getTopTracks":
- w.Write(mockclient.ArtistGetTopTracksResponse)
- }
- }))
+ lastfmClient := lastfm.NewClientCustom(
+ mockclient.New(t, func(w http.ResponseWriter, r *http.Request) {
+ switch method := r.URL.Query().Get("method"); method {
+ case "artist.getInfo":
+ count.Add(1)
+ w.Write(mockclient.ArtistGetInfoResponse)
+ case "artist.getTopTracks":
+ w.Write(mockclient.ArtistGetTopTracksResponse)
+ }
+ }),
+ func() (apiKey string, secret string, err error) {
+ return "", "", nil
+ },
+ )
cache := New(m.DB(), lastfmClient)
- _, err := cache.GetOrLookup(context.Background(), "", artist.ID)
+ _, err := cache.GetOrLookup(context.Background(), artist.ID)
require.NoError(t, err)
- _, err = cache.GetOrLookup(context.Background(), "", artist.ID)
+ _, err = cache.GetOrLookup(context.Background(), artist.ID)
require.NoError(t, err)
require.Equal(t, int32(1), count.Load())
diff --git a/jukebox/jukebox.go b/jukebox/jukebox.go
index 3a04aa0..47eae36 100644
--- a/jukebox/jukebox.go
+++ b/jukebox/jukebox.go
@@ -310,9 +310,13 @@ func (j *Jukebox) Quit() error {
if j.conn == nil || j.conn.IsClosed() {
return nil
}
- if _, err := j.conn.Call("quit"); err != nil {
- return fmt.Errorf("quit: %w", err)
- }
+ go func() {
+ _, _ = j.conn.Call("quit")
+ }()
+
+ time.Sleep(250 * time.Millisecond)
+ _ = j.cmd.Process.Kill()
+
if err := j.conn.Close(); err != nil {
return fmt.Errorf("close: %w", err)
}
@@ -331,13 +335,15 @@ func (j *Jukebox) getDecode(dest any, property string) error {
return nil
}
-type mpvPlaylist []mpvPlaylistItem
-type mpvPlaylistItem struct {
- ID int
- Filename string
- Current bool
- Playing bool
-}
+type (
+ mpvPlaylist []mpvPlaylistItem
+ mpvPlaylistItem struct {
+ ID int
+ Filename string
+ Current bool
+ Playing bool
+ }
+)
func waitUntil(timeout time.Duration, f func() bool) bool {
quit := time.NewTicker(timeout)
diff --git a/jukebox/jukebox_test.go b/jukebox/jukebox_test.go
index c320d3e..15dfeb7 100644
--- a/jukebox/jukebox_test.go
+++ b/jukebox/jukebox_test.go
@@ -11,34 +11,13 @@ import (
"go.senan.xyz/gonic/jukebox"
)
-func newJukebox(t *testing.T) *jukebox.Jukebox {
- sockPath := filepath.Join(t.TempDir(), "mpv.sock")
-
- j := jukebox.New()
- err := j.Start(
- sockPath,
- []string{jukebox.MPVArg("--ao", "null")},
- )
- if errors.Is(err, jukebox.ErrMPVTooOld) {
- t.Skip("old mpv found, skipping")
- }
- if err != nil {
- t.Fatalf("start jukebox: %v", err)
- }
- t.Cleanup(func() {
- j.Quit()
- })
- return j
-}
-
func TestPlaySkipReset(t *testing.T) {
t.Skip("bit flakey currently")
t.Parallel()
j := newJukebox(t)
- require := require.New(t)
- require.NoError(j.SetPlaylist([]string{
+ require.NoError(t, j.SetPlaylist([]string{
testPath("tr_0.mp3"),
testPath("tr_1.mp3"),
testPath("tr_2.mp3"),
@@ -47,56 +26,56 @@ func TestPlaySkipReset(t *testing.T) {
}))
status, err := j.GetStatus()
- require.NoError(err)
- require.Equal(0, status.CurrentIndex)
- require.Equal(testPath("tr_0.mp3"), status.CurrentFilename)
- require.Equal(5, status.Length)
- require.Equal(true, status.Playing)
+ require.NoError(t, err)
+ require.Equal(t, 0, status.CurrentIndex)
+ require.Equal(t, testPath("tr_0.mp3"), status.CurrentFilename)
+ require.Equal(t, 5, status.Length)
+ require.Equal(t, true, status.Playing)
items, err := j.GetPlaylist()
- require.NoError(err)
+ require.NoError(t, err)
itemsSorted := append([]string(nil), items...)
sort.Strings(itemsSorted)
- require.Equal(itemsSorted, items)
+ require.Equal(t, itemsSorted, items)
- require.NoError(j.Play())
+ require.NoError(t, j.Play())
status, err = j.GetStatus()
- require.NoError(err)
- require.Equal(true, status.Playing)
+ require.NoError(t, err)
+ require.Equal(t, true, status.Playing)
- require.NoError(j.Pause())
+ require.NoError(t, j.Pause())
status, err = j.GetStatus()
- require.NoError(err)
- require.Equal(false, status.Playing)
+ require.NoError(t, err)
+ require.Equal(t, false, status.Playing)
- require.NoError(j.Play())
+ require.NoError(t, j.Play())
// skip to 2
- require.NoError(j.SkipToPlaylistIndex(2, 0))
+ require.NoError(t, j.SkipToPlaylistIndex(2, 0))
status, err = j.GetStatus()
- require.NoError(err)
- require.Equal(2, status.CurrentIndex)
- require.Equal(testPath("tr_2.mp3"), status.CurrentFilename)
- require.Equal(5, status.Length)
- require.Equal(true, status.Playing)
+ require.NoError(t, err)
+ require.Equal(t, 2, status.CurrentIndex)
+ require.Equal(t, testPath("tr_2.mp3"), status.CurrentFilename)
+ require.Equal(t, 5, status.Length)
+ require.Equal(t, true, status.Playing)
// skip to 3
- require.NoError(j.SkipToPlaylistIndex(3, 0))
+ require.NoError(t, j.SkipToPlaylistIndex(3, 0))
status, err = j.GetStatus()
- require.NoError(err)
- require.Equal(3, status.CurrentIndex)
- require.Equal(testPath("tr_3.mp3"), status.CurrentFilename)
- require.Equal(5, status.Length)
- require.Equal(true, status.Playing)
+ require.NoError(t, err)
+ require.Equal(t, 3, status.CurrentIndex)
+ require.Equal(t, testPath("tr_3.mp3"), status.CurrentFilename)
+ require.Equal(t, 5, status.Length)
+ require.Equal(t, true, status.Playing)
// just add one more by overwriting the playlist like some clients do
// we should keep the current track unchaned if we find it
- require.NoError(j.SetPlaylist([]string{
+ require.NoError(t, j.SetPlaylist([]string{
"testdata/tr_0.mp3",
"testdata/tr_1.mp3",
"testdata/tr_2.mp3",
@@ -106,24 +85,24 @@ func TestPlaySkipReset(t *testing.T) {
}))
status, err = j.GetStatus()
- require.NoError(err)
- require.Equal(3, status.CurrentIndex) // index unchanged
- require.Equal(testPath("tr_3.mp3"), status.CurrentFilename)
- require.Equal(6, status.Length) // we added one more track
- require.Equal(true, status.Playing)
+ require.NoError(t, err)
+ require.Equal(t, 3, status.CurrentIndex) // index unchanged
+ require.Equal(t, testPath("tr_3.mp3"), status.CurrentFilename)
+ require.Equal(t, 6, status.Length) // we added one more track
+ require.Equal(t, true, status.Playing)
// skip to 3 again
- require.NoError(j.SkipToPlaylistIndex(3, 0))
+ require.NoError(t, j.SkipToPlaylistIndex(3, 0))
status, err = j.GetStatus()
- require.NoError(err)
- require.Equal(3, status.CurrentIndex)
- require.Equal(testPath("tr_3.mp3"), status.CurrentFilename)
- require.Equal(6, status.Length)
- require.Equal(true, status.Playing)
+ require.NoError(t, err)
+ require.Equal(t, 3, status.CurrentIndex)
+ require.Equal(t, testPath("tr_3.mp3"), status.CurrentFilename)
+ require.Equal(t, 6, status.Length)
+ require.Equal(t, true, status.Playing)
// remove all but 3
- require.NoError(j.SetPlaylist([]string{
+ require.NoError(t, j.SetPlaylist([]string{
"testdata/tr_0.mp3",
"testdata/tr_1.mp3",
"testdata/tr_2.mp3",
@@ -131,25 +110,25 @@ func TestPlaySkipReset(t *testing.T) {
}))
status, err = j.GetStatus()
- require.NoError(err)
- require.Equal(3, status.CurrentIndex) // index unchanged
- require.Equal(testPath("tr_3.mp3"), status.CurrentFilename)
- require.Equal(4, status.Length)
- require.Equal(true, status.Playing)
+ require.NoError(t, err)
+ require.Equal(t, 3, status.CurrentIndex) // index unchanged
+ require.Equal(t, testPath("tr_3.mp3"), status.CurrentFilename)
+ require.Equal(t, 4, status.Length)
+ require.Equal(t, true, status.Playing)
// skip to 2 (5s long) in the middle of the track
- require.NoError(j.SkipToPlaylistIndex(2, 2))
+ require.NoError(t, j.SkipToPlaylistIndex(2, 2))
status, err = j.GetStatus()
- require.NoError(err)
- require.Equal(2, status.CurrentIndex) // index unchanged
- require.Equal(testPath("tr_2.mp3"), status.CurrentFilename)
- require.Equal(4, status.Length)
- require.Equal(true, status.Playing)
- require.Equal(2, status.Position) // at new position
+ require.NoError(t, err)
+ require.Equal(t, 2, status.CurrentIndex) // index unchanged
+ require.Equal(t, testPath("tr_2.mp3"), status.CurrentFilename)
+ require.Equal(t, 4, status.Length)
+ require.Equal(t, true, status.Playing)
+ require.Equal(t, 2, status.Position) // at new position
// overwrite completely
- require.NoError(j.SetPlaylist([]string{
+ require.NoError(t, j.SetPlaylist([]string{
"testdata/tr_5.mp3",
"testdata/tr_6.mp3",
"testdata/tr_7.mp3",
@@ -158,33 +137,54 @@ func TestPlaySkipReset(t *testing.T) {
}))
status, err = j.GetStatus()
- require.NoError(err)
- require.Equal(0, status.CurrentIndex) // index unchanged
- require.Equal(testPath("tr_5.mp3"), status.CurrentFilename)
- require.Equal(5, status.Length)
- require.Equal(true, status.Playing)
+ require.NoError(t, err)
+ require.Equal(t, 0, status.CurrentIndex) // index unchanged
+ require.Equal(t, testPath("tr_5.mp3"), status.CurrentFilename)
+ require.Equal(t, 5, status.Length)
+ require.Equal(t, true, status.Playing)
}
func TestVolume(t *testing.T) {
t.Parallel()
j := newJukebox(t)
- require := require.New(t)
vol, err := j.GetVolumePct()
- require.NoError(err)
- require.Equal(100.0, vol)
+ require.NoError(t, err)
+ require.Equal(t, 100.0, vol)
- require.NoError(j.SetVolumePct(69.0))
+ require.NoError(t, j.SetVolumePct(69.0))
vol, err = j.GetVolumePct()
- require.NoError(err)
- require.Equal(69.0, vol)
+ require.NoError(t, err)
+ require.Equal(t, 69.0, vol)
- require.NoError(j.SetVolumePct(0.0))
+ require.NoError(t, j.SetVolumePct(0.0))
vol, err = j.GetVolumePct()
- require.NoError(err)
- require.Equal(0.0, vol)
+ require.NoError(t, err)
+ require.Equal(t, 0.0, vol)
+}
+
+func newJukebox(tb testing.TB) *jukebox.Jukebox {
+ tb.Helper()
+
+ sockPath := filepath.Join(tb.TempDir(), "mpv.sock")
+
+ j := jukebox.New()
+ err := j.Start(
+ sockPath,
+ []string{jukebox.MPVArg("--ao", "null")},
+ )
+ if errors.Is(err, jukebox.ErrMPVTooOld) {
+ tb.Skip("old mpv found, skipping")
+ }
+ if err != nil {
+ tb.Fatalf("start jukebox: %v", err)
+ }
+ tb.Cleanup(func() {
+ j.Quit()
+ })
+ return j
}
func testPath(path string) string {
diff --git a/lastfm/client.go b/lastfm/client.go
new file mode 100644
index 0000000..4e406e1
--- /dev/null
+++ b/lastfm/client.go
@@ -0,0 +1,326 @@
+package lastfm
+
+import (
+ "crypto/md5"
+ "encoding/hex"
+ "encoding/xml"
+ "errors"
+ "fmt"
+ "net/http"
+ "net/url"
+ "sort"
+ "strconv"
+ "time"
+
+ "github.com/andybalholm/cascadia"
+ "go.senan.xyz/gonic/db"
+ "go.senan.xyz/gonic/scrobble"
+ "golang.org/x/net/html"
+)
+
+var (
+ ErrLastFM = errors.New("last.fm error")
+ ErrNoUserSession = errors.New("no lastfm user session present")
+)
+
+type KeySecretFunc func() (apiKey, secret string, err error)
+
+type Client struct {
+ httpClient *http.Client
+ keySecret KeySecretFunc
+}
+
+func NewClient(keySecret KeySecretFunc) *Client {
+ return NewClientCustom(http.DefaultClient, keySecret)
+}
+
+func NewClientCustom(httpClient *http.Client, keySecret KeySecretFunc) *Client {
+ return &Client{httpClient: httpClient, keySecret: keySecret}
+}
+
+const (
+ BaseURL = "https://ws.audioscrobbler.com/2.0/"
+)
+
+func (c *Client) ArtistGetInfo(artistName string) (Artist, error) {
+ apiKey, _, err := c.keySecret()
+ if err != nil {
+ return Artist{}, fmt.Errorf("get key and secret: %w", err)
+ }
+
+ params := url.Values{}
+ params.Add("method", "artist.getInfo")
+ params.Add("api_key", apiKey)
+ params.Add("artist", artistName)
+
+ resp, err := c.makeRequest(http.MethodGet, params)
+ if err != nil {
+ return Artist{}, fmt.Errorf("make request: %w", err)
+ }
+ return resp.Artist, nil
+}
+
+func (c *Client) AlbumGetInfo(artistName, albumName string) (Album, error) {
+ apiKey, _, err := c.keySecret()
+ if err != nil {
+ return Album{}, fmt.Errorf("get key and secret: %w", err)
+ }
+
+ params := url.Values{}
+ params.Add("method", "album.getInfo")
+ params.Add("api_key", apiKey)
+ params.Add("artist", artistName)
+ params.Add("album", albumName)
+
+ resp, err := c.makeRequest(http.MethodGet, params)
+ if err != nil {
+ return Album{}, fmt.Errorf("make request: %w", err)
+ }
+
+ return resp.Album, nil
+}
+
+func (c *Client) ArtistGetTopTracks(artistName string) (TopTracks, error) {
+ apiKey, _, err := c.keySecret()
+ if err != nil {
+ return TopTracks{}, fmt.Errorf("get key and secret: %w", err)
+ }
+
+ params := url.Values{}
+ params.Add("method", "artist.getTopTracks")
+ params.Add("api_key", apiKey)
+ params.Add("artist", artistName)
+
+ resp, err := c.makeRequest(http.MethodGet, params)
+ if err != nil {
+ return TopTracks{}, fmt.Errorf("make request: %w", err)
+ }
+ return resp.TopTracks, nil
+}
+
+func (c *Client) TrackGetSimilarTracks(artistName, trackName string) (SimilarTracks, error) {
+ apiKey, _, err := c.keySecret()
+ if err != nil {
+ return SimilarTracks{}, fmt.Errorf("get key and secret: %w", err)
+ }
+
+ params := url.Values{}
+ params.Add("method", "track.getSimilar")
+ params.Add("api_key", apiKey)
+ params.Add("track", trackName)
+ params.Add("artist", artistName)
+
+ resp, err := c.makeRequest(http.MethodGet, params)
+ if err != nil {
+ return SimilarTracks{}, fmt.Errorf("make request: %w", err)
+ }
+ return resp.SimilarTracks, nil
+}
+
+func (c *Client) ArtistGetSimilar(artistName string) (SimilarArtists, error) {
+ apiKey, _, err := c.keySecret()
+ if err != nil {
+ return SimilarArtists{}, fmt.Errorf("get key and secret: %w", err)
+ }
+
+ params := url.Values{}
+ params.Add("method", "artist.getSimilar")
+ params.Add("api_key", apiKey)
+ params.Add("artist", artistName)
+
+ resp, err := c.makeRequest(http.MethodGet, params)
+ if err != nil {
+ return SimilarArtists{}, fmt.Errorf("making similar artists GET: %w", err)
+ }
+ return resp.SimilarArtists, nil
+}
+
+func (c *Client) UserGetLovedTracks(userName string) (LovedTracks, error) {
+ apiKey, _, err := c.keySecret()
+ if err != nil {
+ return LovedTracks{}, fmt.Errorf("get key and secret: %w", err)
+ }
+
+ params := url.Values{}
+ params.Add("method", "user.getLovedTracks")
+ params.Add("api_key", apiKey)
+ params.Add("user", userName)
+ params.Add("limit", "1000") // TODO: paginate
+
+ resp, err := c.makeRequest(http.MethodGet, params)
+ if err != nil {
+ return LovedTracks{}, fmt.Errorf("making user get loved tracks GET: %w", err)
+ }
+ return resp.LovedTracks, nil
+}
+
+func (c *Client) GetSession(token string) (string, error) {
+ apiKey, secret, err := c.keySecret()
+ if err != nil {
+ return "", fmt.Errorf("get key and secret: %w", err)
+ }
+
+ params := url.Values{}
+ params.Add("method", "auth.getSession")
+ params.Add("api_key", apiKey)
+ params.Add("token", token)
+ params.Add("api_sig", GetParamSignature(params, secret))
+
+ resp, err := c.makeRequest(http.MethodGet, params)
+ if err != nil {
+ return "", fmt.Errorf("make request: %w", err)
+ }
+ return resp.Session.Key, nil
+}
+
+//nolint:gochecknoglobals
+var artistOpenGraphQuery = cascadia.MustCompile(`html > head > meta[property="og:image"]`)
+
+func (c *Client) StealArtistImage(artistURL string) (string, error) {
+ resp, err := c.httpClient.Get(artistURL) //nolint:gosec
+ if err != nil {
+ return "", fmt.Errorf("get artist url: %w", err)
+ }
+ defer resp.Body.Close()
+
+ node, err := html.Parse(resp.Body)
+ if err != nil {
+ return "", fmt.Errorf("parse html: %w", err)
+ }
+
+ n := cascadia.Query(node, artistOpenGraphQuery)
+ if n == nil {
+ return "", nil
+ }
+
+ var imageURL string
+ for _, attr := range n.Attr {
+ if attr.Key == "content" {
+ imageURL = attr.Val
+ break
+ }
+ }
+
+ return imageURL, nil
+}
+
+func (c *Client) IsUserAuthenticated(user db.User) bool {
+ return user.LastFMSession != ""
+}
+
+func (c *Client) Scrobble(user db.User, track scrobble.Track, stamp time.Time, submission bool) error {
+ apiKey, secret, err := c.keySecret()
+ if err != nil {
+ return fmt.Errorf("get key and secret: %w", err)
+ }
+ if !c.IsUserAuthenticated(user) {
+ return ErrNoUserSession
+ }
+
+ params := url.Values{}
+ if submission {
+ params.Add("method", "track.Scrobble")
+ params.Add("timestamp", strconv.Itoa(int(stamp.Unix()))) // last.fm wants the timestamp in seconds
+ } else {
+ params.Add("method", "track.updateNowPlaying")
+ }
+
+ params.Add("artist", track.Artist)
+ params.Add("track", track.Track)
+ params.Add("trackNumber", strconv.Itoa(int(track.TrackNumber)))
+ params.Add("album", track.Album)
+ params.Add("albumArtist", track.AlbumArtist)
+ params.Add("duration", strconv.Itoa(int(track.Duration.Seconds())))
+
+ if track.MusicBrainzID != "" {
+ params.Add("mbid", track.MusicBrainzID)
+ }
+
+ params.Add("sk", user.LastFMSession)
+ params.Add("api_key", apiKey)
+ params.Add("api_sig", GetParamSignature(params, secret))
+
+ _, err = c.makeRequest(http.MethodPost, params)
+ return err
+}
+
+func (c *Client) LoveTrack(user *db.User, track *db.Track) error {
+ apiKey, secret, err := c.keySecret()
+ if err != nil {
+ return fmt.Errorf("get key and secret: %w", err)
+ }
+ if !c.IsUserAuthenticated(*user) {
+ return ErrNoUserSession
+ }
+
+ params := url.Values{}
+ params.Add("method", "track.love")
+ params.Add("track", track.TagTitle)
+ params.Add("artist", track.TagTrackArtist)
+ params.Add("api_key", apiKey)
+ params.Add("sk", user.LastFMSession)
+ params.Add("api_sig", GetParamSignature(params, secret))
+
+ _, err = c.makeRequest(http.MethodPost, params)
+ return err
+}
+
+func (c *Client) GetCurrentUser(user *db.User) (User, error) {
+ apiKey, secret, err := c.keySecret()
+ if err != nil {
+ return User{}, fmt.Errorf("get key and secret: %w", err)
+ }
+ if !c.IsUserAuthenticated(*user) {
+ return User{}, ErrNoUserSession
+ }
+
+ params := url.Values{}
+ params.Add("method", "user.getInfo")
+ params.Add("api_key", apiKey)
+ params.Add("sk", user.LastFMSession)
+ params.Add("api_sig", GetParamSignature(params, secret))
+
+ resp, err := c.makeRequest(http.MethodGet, params)
+ if err != nil {
+ return User{}, fmt.Errorf("make request: %w", err)
+ }
+ return resp.User, nil
+}
+
+func (c *Client) makeRequest(method string, params url.Values) (LastFM, error) {
+ req, _ := http.NewRequest(method, BaseURL, nil)
+ req.URL.RawQuery = params.Encode()
+
+ resp, err := c.httpClient.Do(req)
+ if err != nil {
+ return LastFM{}, fmt.Errorf("get: %w", err)
+ }
+ defer resp.Body.Close()
+
+ var lastfm LastFM
+ if err = xml.NewDecoder(resp.Body).Decode(&lastfm); err != nil {
+ return LastFM{}, fmt.Errorf("decoding: %w", err)
+ }
+
+ if lastfm.Error.Code != 0 {
+ return LastFM{}, fmt.Errorf("%v: %w", lastfm.Error.Value, ErrLastFM)
+ }
+ return lastfm, nil
+}
+
+func GetParamSignature(params url.Values, secret string) string {
+ // the parameters must be in order before hashing
+ paramKeys := make([]string, 0, len(params))
+ for k := range params {
+ paramKeys = append(paramKeys, k)
+ }
+ sort.Strings(paramKeys)
+ toHash := ""
+ for _, k := range paramKeys {
+ toHash += k
+ toHash += params[k][0]
+ }
+ toHash += secret
+ hash := md5.Sum([]byte(toHash))
+ return hex.EncodeToString(hash[:])
+}
diff --git a/lastfm/client_test.go b/lastfm/client_test.go
new file mode 100644
index 0000000..6525676
--- /dev/null
+++ b/lastfm/client_test.go
@@ -0,0 +1,579 @@
+//nolint:goconst
+package lastfm_test
+
+import (
+ "crypto/md5"
+ "encoding/xml"
+ "fmt"
+ "net/http"
+ "net/url"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/require"
+ "go.senan.xyz/gonic/db"
+ "go.senan.xyz/gonic/lastfm"
+ "go.senan.xyz/gonic/lastfm/mockclient"
+ "go.senan.xyz/gonic/scrobble"
+)
+
+func TestArtistGetInfo(t *testing.T) {
+ t.Parallel()
+
+ client := lastfm.NewClientCustom(
+ mockclient.New(t, func(w http.ResponseWriter, r *http.Request) {
+ require.Equal(t, http.MethodGet, r.Method)
+ require.Equal(t, url.Values{"method": []string{"artist.getInfo"}, "api_key": []string{"apiKey1"}, "artist": []string{"Artist 1"}}, r.URL.Query())
+
+ require.Equal(t, "/2.0/", r.URL.Path)
+ require.Equal(t, lastfm.BaseURL, "https://"+r.Host+r.URL.Path)
+
+ w.WriteHeader(http.StatusOK)
+ w.Write(mockclient.ArtistGetInfoResponse)
+ }),
+ func() (string, string, error) {
+ return "apiKey1", "", nil
+ },
+ )
+
+ actual, err := client.ArtistGetInfo("Artist 1")
+ require.NoError(t, err)
+ require.Equal(t, lastfm.Artist{
+ XMLName: xml.Name{
+ Local: "artist",
+ },
+ Name: "Artist 1",
+ MBID: "366c1119-ec4f-4312-b729-a5637d148e3e",
+ Streamable: "0",
+ Stats: struct {
+ Listeners string `xml:"listeners"`
+ Playcount string `xml:"playcount"`
+ }{
+ Listeners: "1",
+ Playcount: "2",
+ },
+ URL: "https://www.last.fm/music/Artist+1",
+ Image: []lastfm.Image{
+ {
+ Size: "small",
+ Text: "https://last.fm/artist-1-small.png",
+ },
+ },
+ Bio: lastfm.ArtistBio{
+ Published: "13 May 2023, 00:24",
+ Summary: "Summary",
+ Content: "Content",
+ },
+ Similar: struct {
+ Artists []lastfm.Artist `xml:"artist"`
+ }{
+ Artists: []lastfm.Artist{
+ {
+ XMLName: xml.Name{
+ Local: "artist",
+ },
+ Name: "Similar Artist 1",
+ URL: "https://www.last.fm/music/Similar+Artist+1",
+ Image: []lastfm.Image{
+ {
+ Size: "small",
+ Text: "https://last.fm/similar-artist-1-small.png",
+ },
+ },
+ },
+ },
+ },
+ Tags: struct {
+ Tag []lastfm.ArtistTag `xml:"tag"`
+ }{
+ Tag: []lastfm.ArtistTag{
+ {
+ Name: "tag1",
+ URL: "https://www.last.fm/tag/tag1",
+ },
+ },
+ },
+ }, actual)
+}
+
+func TestArtistGetInfoClientRequestFails(t *testing.T) {
+ t.Parallel()
+
+ client := lastfm.NewClientCustom(
+ mockclient.New(t, func(w http.ResponseWriter, r *http.Request) {
+ require.Equal(t, http.MethodGet, r.Method)
+ require.Equal(t, url.Values{
+ "method": []string{"artist.getInfo"},
+ "api_key": []string{"apiKey1"},
+ "artist": []string{"Artist 1"},
+ }, r.URL.Query())
+
+ require.Equal(t, "/2.0/", r.URL.Path)
+ require.Equal(t, lastfm.BaseURL, "https://"+r.Host+r.URL.Path)
+
+ w.WriteHeader(http.StatusInternalServerError)
+ }),
+ func() (string, string, error) {
+ return "apiKey1", "", nil
+ },
+ )
+
+ actual, err := client.ArtistGetInfo("Artist 1")
+ require.Error(t, err)
+ require.Zero(t, actual)
+}
+
+func TestArtistGetTopTracks(t *testing.T) {
+ t.Parallel()
+
+ client := lastfm.NewClientCustom(
+ mockclient.New(t, func(w http.ResponseWriter, r *http.Request) {
+ require.Equal(t, http.MethodGet, r.Method)
+ require.Equal(t, url.Values{
+ "method": []string{"artist.getTopTracks"},
+ "api_key": []string{"apiKey1"},
+ "artist": []string{"artist1"},
+ }, r.URL.Query())
+
+ require.Equal(t, "/2.0/", r.URL.Path)
+ require.Equal(t, lastfm.BaseURL, "https://"+r.Host+r.URL.Path)
+
+ w.WriteHeader(http.StatusOK)
+ w.Write(mockclient.ArtistGetTopTracksResponse)
+ }),
+ func() (string, string, error) {
+ return "apiKey1", "", nil
+ },
+ )
+
+ actual, err := client.ArtistGetTopTracks("artist1")
+ require.NoError(t, err)
+ require.Equal(t, lastfm.TopTracks{
+ Artist: "Artist 1",
+ XMLName: xml.Name{
+ Local: "toptracks",
+ },
+ Tracks: []lastfm.Track{
+ {
+ Image: []lastfm.Image{
+ {
+ Text: "https://last.fm/track-1-small.png",
+ Size: "small",
+ },
+ {
+ Text: "https://last.fm/track-1-large.png",
+ Size: "large",
+ },
+ },
+ Listeners: 2,
+ MBID: "fdfc47cb-69d3-4318-ba71-d54fbc20169a",
+ Name: "Track 1",
+ PlayCount: 1,
+ Rank: 1,
+ URL: "https://www.last.fm/music/Artist+1/_/Track+1",
+ },
+ {
+ Image: []lastfm.Image{
+ {
+ Text: "https://last.fm/track-2-small.png",
+ Size: "small",
+ },
+ {
+ Text: "https://last.fm/track-2-large.png",
+ Size: "large",
+ },
+ },
+ Listeners: 3,
+ MBID: "cf32e694-1ea6-4ba0-9e8b-d5f1950da9c8",
+ Name: "Track 2",
+ PlayCount: 2,
+ Rank: 2,
+ URL: "https://www.last.fm/music/Artist+1/_/Track+2",
+ },
+ },
+ }, actual)
+}
+
+func TestArtistGetTopTracksClientRequestFails(t *testing.T) {
+ t.Parallel()
+
+ client := lastfm.NewClientCustom(
+ mockclient.New(t, func(w http.ResponseWriter, r *http.Request) {
+ require.Equal(t, http.MethodGet, r.Method)
+ require.Equal(t, url.Values{
+ "method": []string{"artist.getTopTracks"},
+ "api_key": []string{"apiKey1"},
+ "artist": []string{"artist1"},
+ }, r.URL.Query())
+
+ require.Equal(t, "/2.0/", r.URL.Path)
+ require.Equal(t, lastfm.BaseURL, "https://"+r.Host+r.URL.Path)
+
+ w.WriteHeader(http.StatusInternalServerError)
+ }),
+ func() (string, string, error) {
+ return "apiKey1", "", nil
+ },
+ )
+
+ actual, err := client.ArtistGetTopTracks("artist1")
+ require.Error(t, err)
+ require.Zero(t, actual)
+}
+
+func TestArtistGetSimilar(t *testing.T) {
+ t.Parallel()
+
+ client := lastfm.NewClientCustom(
+ mockclient.New(t, func(w http.ResponseWriter, r *http.Request) {
+ require.Equal(t, http.MethodGet, r.Method)
+ require.Equal(t, url.Values{
+ "method": []string{"artist.getSimilar"},
+ "api_key": []string{"apiKey1"},
+ "artist": []string{"artist1"},
+ }, r.URL.Query())
+
+ require.Equal(t, "/2.0/", r.URL.Path)
+ require.Equal(t, lastfm.BaseURL, "https://"+r.Host+r.URL.Path)
+
+ w.WriteHeader(http.StatusOK)
+ w.Write(mockclient.ArtistGetSimilarResponse)
+ }),
+ func() (string, string, error) {
+ return "apiKey1", "", nil
+ },
+ )
+
+ actual, err := client.ArtistGetSimilar("artist1")
+ require.NoError(t, err)
+ require.Equal(t, lastfm.SimilarArtists{
+ XMLName: xml.Name{
+ Local: "similarartists",
+ },
+ Artist: "Artist 1",
+ Artists: []lastfm.Artist{
+ {
+ XMLName: xml.Name{
+ Local: "artist",
+ },
+ Image: []lastfm.Image{
+ {
+ Text: "https://last.fm/artist-2-small.png",
+ Size: "small",
+ },
+ {
+ Text: "https://last.fm/artist-2-large.png",
+ Size: "large",
+ },
+ },
+ MBID: "d2addad9-3fc4-4ce8-9cd4-63f2a19bb922",
+ Name: "Artist 2",
+ Similar: struct {
+ Artists []lastfm.Artist `xml:"artist"`
+ }{},
+ Streamable: "0",
+ URL: "https://www.last.fm/music/Artist+2",
+ },
+ {
+ XMLName: xml.Name{
+ Local: "artist",
+ },
+ Image: []lastfm.Image{
+ {
+ Text: "https://last.fm/artist-3-small.png",
+ Size: "small",
+ },
+ {
+ Text: "https://last.fm/artist-3-large.png",
+ Size: "large",
+ },
+ },
+ MBID: "dc95d067-df3e-4b83-a5fe-5ec773b1883f",
+ Name: "Artist 3",
+ Similar: struct {
+ Artists []lastfm.Artist `xml:"artist"`
+ }{},
+ Streamable: "0",
+ URL: "https://www.last.fm/music/Artist+3",
+ },
+ },
+ }, actual)
+}
+
+func TestArtistGetSimilarClientRequestFails(t *testing.T) {
+ t.Parallel()
+
+ client := lastfm.NewClientCustom(
+ mockclient.New(t, func(w http.ResponseWriter, r *http.Request) {
+ require.Equal(t, http.MethodGet, r.Method)
+ require.Equal(t, url.Values{
+ "method": []string{"artist.getSimilar"},
+ "api_key": []string{"apiKey1"},
+ "artist": []string{"artist1"},
+ }, r.URL.Query())
+
+ require.Equal(t, "/2.0/", r.URL.Path)
+ require.Equal(t, lastfm.BaseURL, "https://"+r.Host+r.URL.Path)
+
+ w.WriteHeader(http.StatusInternalServerError)
+ }),
+ func() (string, string, error) {
+ return "apiKey1", "", nil
+ },
+ )
+
+ actual, err := client.ArtistGetSimilar("artist1")
+ require.Error(t, err)
+ require.Zero(t, actual)
+}
+
+func TestTrackGetSimilarTracks(t *testing.T) {
+ t.Parallel()
+
+ client := lastfm.NewClientCustom(
+ mockclient.New(t, func(w http.ResponseWriter, r *http.Request) {
+ require.Equal(t, http.MethodGet, r.Method)
+ require.Equal(t, url.Values{
+ "method": []string{"track.getSimilar"},
+ "api_key": []string{"apiKey1"},
+ "artist": []string{"artist1"},
+ "track": []string{"track1"},
+ }, r.URL.Query())
+
+ require.Equal(t, "/2.0/", r.URL.Path)
+ require.Equal(t, lastfm.BaseURL, "https://"+r.Host+r.URL.Path)
+
+ w.WriteHeader(http.StatusOK)
+ w.Write(mockclient.TrackGetSimilarResponse)
+ }),
+ func() (string, string, error) {
+ return "apiKey1", "", nil
+ },
+ )
+
+ actual, err := client.TrackGetSimilarTracks("artist1", "track1")
+
+ require.NoError(t, err)
+ require.Equal(t, lastfm.SimilarTracks{
+ Artist: "Artist 1",
+ Track: "Track 1",
+ XMLName: xml.Name{
+ Local: "similartracks",
+ },
+ Tracks: []lastfm.Track{
+ {
+ Image: []lastfm.Image{
+ {
+ Text: "https://last.fm/track-1-small.png",
+ Size: "small",
+ },
+ {
+ Text: "https://last.fm/track-1-large.png",
+ Size: "large",
+ },
+ },
+ MBID: "7096931c-bf82-4896-b1e7-42b60a0e16ea",
+ Name: "Track 1",
+ PlayCount: 1,
+ URL: "https://www.last.fm/music/Artist+1/_/Track+1",
+ },
+ {
+ Image: []lastfm.Image{
+ {
+ Text: "https://last.fm/track-2-small.png",
+ Size: "small",
+ },
+ {
+ Text: "https://last.fm/track-2-large.png",
+ Size: "large",
+ },
+ },
+ MBID: "2aff1321-149f-4000-8762-3468c917600c",
+ Name: "Track 2",
+ PlayCount: 2,
+ URL: "https://www.last.fm/music/Artist+2/_/Track+2",
+ },
+ },
+ }, actual)
+}
+
+func TestTrackGetSimilarTracksClientRequestFails(t *testing.T) {
+ t.Parallel()
+
+ client := lastfm.NewClientCustom(
+ mockclient.New(t, func(w http.ResponseWriter, r *http.Request) {
+ require.Equal(t, http.MethodGet, r.Method)
+ require.Equal(t, url.Values{
+ "method": []string{"track.getSimilar"},
+ "api_key": []string{"apiKey1"},
+ "artist": []string{"artist1"},
+ "track": []string{"track1"},
+ }, r.URL.Query())
+
+ require.Equal(t, "/2.0/", r.URL.Path)
+ require.Equal(t, lastfm.BaseURL, "https://"+r.Host+r.URL.Path)
+
+ w.WriteHeader(http.StatusInternalServerError)
+ }),
+ func() (string, string, error) {
+ return "apiKey1", "", nil
+ },
+ )
+
+ actual, err := client.TrackGetSimilarTracks("artist1", "track1")
+ require.Error(t, err)
+ require.Zero(t, actual)
+}
+
+func TestGetSession(t *testing.T) {
+ t.Parallel()
+
+ client := lastfm.NewClientCustom(
+ mockclient.New(t, func(w http.ResponseWriter, r *http.Request) {
+ require.Equal(t, http.MethodGet, r.Method)
+ require.Equal(t, url.Values{
+ "method": []string{"auth.getSession"},
+ "api_key": []string{"apiKey1"},
+ "api_sig": []string{"b872a708a0b8b1d9fc1230b1cb6493f8"},
+ "token": []string{"token1"},
+ }, r.URL.Query())
+
+ require.Equal(t, "/2.0/", r.URL.Path)
+ require.Equal(t, lastfm.BaseURL, "https://"+r.Host+r.URL.Path)
+
+ w.WriteHeader(http.StatusOK)
+ w.Write(mockclient.GetSessionResponse)
+ }),
+ func() (string, string, error) {
+ return "apiKey1", "secret1", nil
+ },
+ )
+
+ actual, err := client.GetSession("token1")
+ require.NoError(t, err)
+ require.Equal(t, "sessionKey1", actual)
+}
+
+func TestGetSessionClientRequestFails(t *testing.T) {
+ t.Parallel()
+
+ client := lastfm.NewClientCustom(
+ mockclient.New(t, func(w http.ResponseWriter, r *http.Request) {
+ require.Equal(t, http.MethodGet, r.Method)
+ require.Equal(t, url.Values{
+ "method": []string{"auth.getSession"},
+ "api_key": []string{"apiKey1"},
+ "api_sig": []string{"b872a708a0b8b1d9fc1230b1cb6493f8"},
+ "token": []string{"token1"},
+ }, r.URL.Query())
+
+ require.Equal(t, "/2.0/", r.URL.Path)
+ require.Equal(t, lastfm.BaseURL, "https://"+r.Host+r.URL.Path)
+
+ w.WriteHeader(http.StatusInternalServerError)
+ }),
+ func() (string, string, error) {
+ return "apiKey1", "secret1", nil
+ },
+ )
+
+ actual, err := client.GetSession("token1")
+
+ require.Error(t, err)
+ require.Zero(t, actual)
+}
+
+func TestScrobble(t *testing.T) {
+ t.Parallel()
+
+ client := lastfm.NewClientCustom(
+ mockclient.New(t, func(w http.ResponseWriter, r *http.Request) {
+ require.Equal(t, http.MethodPost, r.Method)
+ require.Equal(t, url.Values{
+ "album": []string{"album1"},
+ "albumArtist": []string{"artist1"},
+ "api_key": []string{"apiKey1"},
+ "api_sig": []string{"d235a0b911eb4923953f496c61a2a6af"},
+ "artist": []string{"trackArtist1"},
+ "duration": []string{"100"},
+ "method": []string{"track.Scrobble"},
+ "sk": []string{"lastFMSession1"},
+ "mbid": []string{"916b242d-d439-4ae4-a439-556eef99c06e"},
+ "timestamp": []string{"1691843641"},
+ "track": []string{"title1"},
+ "trackNumber": []string{"1"},
+ }, r.URL.Query())
+
+ require.Equal(t, "/2.0/", r.URL.Path)
+ require.Equal(t, lastfm.BaseURL, "https://"+r.Host+r.URL.Path)
+
+ w.WriteHeader(http.StatusOK)
+ w.Write(mockclient.ArtistGetTopTracksResponse)
+ }),
+ func() (apiKey string, secret string, err error) {
+ return "apiKey1", "secret1", nil
+ },
+ )
+
+ user := db.User{
+ LastFMSession: "lastFMSession1",
+ }
+ track := scrobble.Track{
+ Track: "title1",
+ Artist: "trackArtist1",
+ Album: "album1",
+ AlbumArtist: "artist1",
+ TrackNumber: 1,
+ Duration: 100 * time.Second,
+ MusicBrainzID: "916b242d-d439-4ae4-a439-556eef99c06e",
+ }
+
+ stamp := time.Date(2023, 8, 12, 12, 34, 1, 200, time.UTC)
+
+ err := client.Scrobble(user, track, stamp, true)
+ require.NoError(t, err)
+}
+
+func TestScrobbleErrorsWithoutLastFMSession(t *testing.T) {
+ t.Parallel()
+
+ client := lastfm.NewClient(func() (apiKey string, secret string, err error) {
+ return "", "", nil
+ })
+
+ err := client.Scrobble(db.User{}, scrobble.Track{}, time.Now(), false)
+ require.ErrorIs(t, err, lastfm.ErrNoUserSession)
+}
+
+func TestScrobbleFailsWithoutLastFMAPIKey(t *testing.T) {
+ t.Parallel()
+
+ user := db.User{
+ LastFMSession: "lastFMSession1",
+ }
+
+ scrobbler := lastfm.NewClient(func() (string, string, error) {
+ return "", "", fmt.Errorf("no keys")
+ })
+
+ err := scrobbler.Scrobble(user, scrobble.Track{}, time.Now(), false)
+
+ require.Error(t, err)
+}
+
+func TestGetParamSignature(t *testing.T) {
+ t.Parallel()
+
+ params := url.Values{}
+ params.Add("ccc", "CCC")
+ params.Add("bbb", "BBB")
+ params.Add("aaa", "AAA")
+ params.Add("ddd", "DDD")
+ actual := lastfm.GetParamSignature(params, "secret")
+ expected := fmt.Sprintf("%x", md5.Sum([]byte(
+ "aaaAAAbbbBBBcccCCCdddDDDsecret",
+ )))
+ if actual != expected {
+ t.Errorf("expected %x, got %s", expected, actual)
+ }
+}
diff --git a/scrobble/lastfm/mockclient/artist_get_info_response.xml b/lastfm/mockclient/artist_get_info_response.xml
similarity index 100%
rename from scrobble/lastfm/mockclient/artist_get_info_response.xml
rename to lastfm/mockclient/artist_get_info_response.xml
diff --git a/scrobble/lastfm/mockclient/artist_get_similar_response.xml b/lastfm/mockclient/artist_get_similar_response.xml
similarity index 100%
rename from scrobble/lastfm/mockclient/artist_get_similar_response.xml
rename to lastfm/mockclient/artist_get_similar_response.xml
diff --git a/scrobble/lastfm/mockclient/artist_get_top_tracks_response.xml b/lastfm/mockclient/artist_get_top_tracks_response.xml
similarity index 100%
rename from scrobble/lastfm/mockclient/artist_get_top_tracks_response.xml
rename to lastfm/mockclient/artist_get_top_tracks_response.xml
diff --git a/scrobble/lastfm/mockclient/get_session_response.xml b/lastfm/mockclient/get_session_response.xml
similarity index 100%
rename from scrobble/lastfm/mockclient/get_session_response.xml
rename to lastfm/mockclient/get_session_response.xml
diff --git a/scrobble/lastfm/mockclient/mockclient.go b/lastfm/mockclient/mockclient.go
similarity index 88%
rename from scrobble/lastfm/mockclient/mockclient.go
rename to lastfm/mockclient/mockclient.go
index 2e3f8cf..593e656 100644
--- a/scrobble/lastfm/mockclient/mockclient.go
+++ b/lastfm/mockclient/mockclient.go
@@ -10,9 +10,11 @@ import (
"testing"
)
-func New(t testing.TB, handler http.HandlerFunc) *http.Client {
+func New(tb testing.TB, handler http.HandlerFunc) *http.Client {
+ tb.Helper()
+
server := httptest.NewTLSServer(handler)
- t.Cleanup(server.Close)
+ tb.Cleanup(server.Close)
return &http.Client{
Transport: &http.Transport{
diff --git a/scrobble/lastfm/mockclient/track_get_similar_response.xml b/lastfm/mockclient/track_get_similar_response.xml
similarity index 100%
rename from scrobble/lastfm/mockclient/track_get_similar_response.xml
rename to lastfm/mockclient/track_get_similar_response.xml
diff --git a/lastfm/model.go b/lastfm/model.go
new file mode 100644
index 0000000..ab49bcd
--- /dev/null
+++ b/lastfm/model.go
@@ -0,0 +1,191 @@
+package lastfm
+
+import "encoding/xml"
+
+type (
+ LastFM struct {
+ XMLName xml.Name `xml:"lfm"`
+ Status string `xml:"status,attr"`
+ Session Session `xml:"session"`
+ Error Error `xml:"error"`
+ Artist Artist `xml:"artist"`
+ Album Album `xml:"album"`
+ TopTracks TopTracks `xml:"toptracks"`
+ SimilarTracks SimilarTracks `xml:"similartracks"`
+ SimilarArtists SimilarArtists `xml:"similarartists"`
+ LovedTracks LovedTracks `xml:"lovedtracks"`
+ User User `xml:"user"`
+ }
+
+ Session struct {
+ Name string `xml:"name"`
+ Key string `xml:"key"`
+ Subscriber uint `xml:"subscriber"`
+ }
+
+ Error struct {
+ Code uint `xml:"code,attr"`
+ Value string `xml:",chardata"`
+ }
+
+ SimilarArtist struct {
+ XMLName xml.Name `xml:"artist"`
+ Name string `xml:"name"`
+ MBID string `xml:"mbid"`
+ URL string `xml:"url"`
+ Image []Image `xml:"image"`
+ Streamable string `xml:"streamable"`
+ }
+
+ Image struct {
+ Text string `xml:",chardata"`
+ Size string `xml:"size,attr"`
+ }
+
+ Artist struct {
+ XMLName xml.Name `xml:"artist"`
+ Name string `xml:"name"`
+ MBID string `xml:"mbid"`
+ URL string `xml:"url"`
+ Image []Image `xml:"image"`
+ Streamable string `xml:"streamable"`
+ Stats struct {
+ Listeners string `xml:"listeners"`
+ Playcount string `xml:"playcount"`
+ } `xml:"stats"`
+ Similar struct {
+ Artists []Artist `xml:"artist"`
+ } `xml:"similar"`
+ Tags struct {
+ Tag []ArtistTag `xml:"tag"`
+ } `xml:"tags"`
+ Bio ArtistBio `xml:"bio"`
+ }
+
+ Album struct {
+ XMLName xml.Name `xml:"album"`
+ Name string `xml:"name"`
+ Artist string `xml:"artist"`
+ MBID string `xml:"mbid"`
+ URL string `xml:"url"`
+ Image []struct {
+ Text string `xml:",chardata"`
+ Size string `xml:"size,attr"`
+ } `xml:"image"`
+ Listeners string `xml:"listeners"`
+ Playcount string `xml:"playcount"`
+ Tracks struct {
+ Text string `xml:",chardata"`
+ Track []struct {
+ Text string `xml:",chardata"`
+ Rank string `xml:"rank,attr"`
+ Name string `xml:"name"`
+ URL string `xml:"url"`
+ Duration string `xml:"duration"`
+ Streamable struct {
+ Text string `xml:",chardata"`
+ Fulltrack string `xml:"fulltrack,attr"`
+ } `xml:"streamable"`
+ Artist struct {
+ Text string `xml:",chardata"`
+ Name string `xml:"name"`
+ Mbid string `xml:"mbid"`
+ URL string `xml:"url"`
+ } `xml:"artist"`
+ } `xml:"track"`
+ } `xml:"tracks"`
+ Tags struct {
+ Text string `xml:",chardata"`
+ Tag []struct {
+ Text string `xml:",chardata"`
+ Name string `xml:"name"`
+ URL string `xml:"url"`
+ } `xml:"tag"`
+ } `xml:"tags"`
+ Wiki struct {
+ Text string `xml:",chardata"`
+ Published string `xml:"published"`
+ Summary string `xml:"summary"`
+ Content string `xml:"content"`
+ } `xml:"wiki"`
+ }
+
+ ArtistTag struct {
+ Name string `xml:"name"`
+ URL string `xml:"url"`
+ }
+
+ ArtistBio struct {
+ Published string `xml:"published"`
+ Summary string `xml:"summary"`
+ Content string `xml:"content"`
+ }
+
+ TopTracks struct {
+ XMLName xml.Name `xml:"toptracks"`
+ Artist string `xml:"artist,attr"`
+ Tracks []Track `xml:"track"`
+ }
+
+ SimilarTracks struct {
+ XMLName xml.Name `xml:"similartracks"`
+ Artist string `xml:"artist,attr"`
+ Track string `xml:"track,attr"`
+ Tracks []Track `xml:"track"`
+ }
+
+ SimilarArtists struct {
+ XMLName xml.Name `xml:"similarartists"`
+ Artist string `xml:"artist,attr"`
+ Artists []Artist `xml:"artist"`
+ }
+
+ Track struct {
+ Rank int `xml:"rank,attr"`
+ Tracks []Track `xml:"track"`
+ Name string `xml:"name"`
+ MBID string `xml:"mbid"`
+ PlayCount int `xml:"playcount"`
+ Listeners int `xml:"listeners"`
+ URL string `xml:"url"`
+ Image []Image `xml:"image"`
+ }
+
+ LovedTracks struct {
+ XMLName xml.Name `xml:"lovedtracks"`
+ Tracks []struct {
+ Track
+ Date struct {
+ Text string `xml:",chardata"`
+ UTS string `xml:"uts,attr"`
+ } `xml:"date"`
+ Artist Artist `xml:"artist"`
+ } `xml:"track"`
+ }
+
+ User struct {
+ Text string `xml:",chardata"`
+ Name string `xml:"name"`
+ Realname string `xml:"realname"`
+ Image []struct {
+ Text string `xml:",chardata"`
+ Size string `xml:"size,attr"`
+ } `xml:"image"`
+ URL string `xml:"url"`
+ Country string `xml:"country"`
+ Age string `xml:"age"`
+ Gender string `xml:"gender"`
+ Subscriber string `xml:"subscriber"`
+ Playcount string `xml:"playcount"`
+ Playlists string `xml:"playlists"`
+ Bootstrap string `xml:"bootstrap"`
+ Registered struct {
+ Text string `xml:",chardata"`
+ Unixtime string `xml:"unixtime,attr"`
+ } `xml:"registered"`
+ Type string `xml:"type"`
+ ArtistCount string `xml:"artist_count"`
+ AlbumCount string `xml:"album_count"`
+ TrackCount string `xml:"track_count"`
+ }
+)
diff --git a/scrobble/listenbrainz/listenbrainz.go b/listenbrainz/listenbrainz.go
similarity index 64%
rename from scrobble/listenbrainz/listenbrainz.go
rename to listenbrainz/listenbrainz.go
index 0e5affb..df44213 100644
--- a/scrobble/listenbrainz/listenbrainz.go
+++ b/listenbrainz/listenbrainz.go
@@ -10,7 +10,6 @@ import (
"net/http/httputil"
"time"
- "github.com/google/uuid"
"go.senan.xyz/gonic/db"
"go.senan.xyz/gonic/scrobble"
)
@@ -23,46 +22,41 @@ const (
listenTypePlayingNow = "playing_now"
)
-var (
- ErrListenBrainz = errors.New("listenbrainz error")
-)
+var ErrListenBrainz = errors.New("listenbrainz error")
-type Scrobbler struct {
+type Client struct {
httpClient *http.Client
}
-func NewScrobbler() *Scrobbler {
- return &Scrobbler{
- httpClient: http.DefaultClient,
- }
+func NewClient() *Client {
+ return NewClientCustom(http.DefaultClient)
}
-func (s *Scrobbler) Scrobble(user *db.User, track *db.Track, stamp time.Time, submission bool) error {
- if user.ListenBrainzURL == "" || user.ListenBrainzToken == "" {
- return nil
- }
+func NewClientCustom(httpClient *http.Client) *Client {
+ return &Client{httpClient: httpClient}
+}
- // make sure we provide a valid uuid, since some users may have an incorrect mbid in their tags
- var trackMBID string
- if _, err := uuid.Parse(track.TagBrainzID); err == nil {
- trackMBID = track.TagBrainzID
- }
+func (c *Client) IsUserAuthenticated(user db.User) bool {
+ return user.ListenBrainzURL != "" && user.ListenBrainzToken != ""
+}
+func (c *Client) Scrobble(user db.User, track scrobble.Track, stamp time.Time, submission bool) error {
payload := &Payload{
TrackMetadata: &TrackMetadata{
AdditionalInfo: &AdditionalInfo{
- TrackNumber: track.TagTrackNumber,
- RecordingMBID: trackMBID,
- TrackLength: track.Length,
+ TrackNumber: int(track.TrackNumber),
+ RecordingMBID: track.MusicBrainzID,
+ TrackLength: int(track.Duration.Seconds()),
},
- ArtistName: track.TagTrackArtist,
- TrackName: track.TagTitle,
- ReleaseName: track.Album.TagTitle,
+ ArtistName: track.Artist,
+ TrackName: track.Track,
+ ReleaseName: track.Album,
},
}
scrobble := Scrobble{
Payload: []*Payload{payload},
}
+
if submission && len(scrobble.Payload) > 0 {
scrobble.ListenType = listenTypeSingle
scrobble.Payload[0].ListenedAt = int(stamp.Unix())
@@ -74,12 +68,15 @@ func (s *Scrobbler) Scrobble(user *db.User, track *db.Track, stamp time.Time, su
if err := json.NewEncoder(&payloadBuf).Encode(scrobble); err != nil {
return err
}
+
submitURL := fmt.Sprintf("%s%s", user.ListenBrainzURL, submitPath)
authHeader := fmt.Sprintf("Token %s", user.ListenBrainzToken)
+
req, _ := http.NewRequest(http.MethodPost, submitURL, &payloadBuf)
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Authorization", authHeader)
- resp, err := s.httpClient.Do(req)
+
+ resp, err := c.httpClient.Do(req)
if err != nil {
return fmt.Errorf("http post: %w", err)
}
@@ -95,5 +92,3 @@ func (s *Scrobbler) Scrobble(user *db.User, track *db.Track, stamp time.Time, su
}
return nil
}
-
-var _ scrobble.Scrobbler = (*Scrobbler)(nil)
diff --git a/listenbrainz/listenbrainz_test.go b/listenbrainz/listenbrainz_test.go
new file mode 100644
index 0000000..13326a7
--- /dev/null
+++ b/listenbrainz/listenbrainz_test.go
@@ -0,0 +1,115 @@
+package listenbrainz_test
+
+import (
+ "context"
+ "crypto/tls"
+ _ "embed"
+ "io"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/require"
+ "go.senan.xyz/gonic/db"
+ "go.senan.xyz/gonic/listenbrainz"
+ "go.senan.xyz/gonic/scrobble"
+)
+
+func TestScrobble(t *testing.T) {
+ t.Parallel()
+
+ client := listenbrainz.NewClientCustom(
+ newMockClient(t, func(w http.ResponseWriter, r *http.Request) {
+ require.Equal(t, http.MethodPost, r.Method)
+ require.Equal(t, "/1/submit-listens", r.URL.Path)
+ require.Equal(t, "application/json", r.Header.Get("Content-Type"))
+ require.Equal(t, "Token token1", r.Header.Get("Authorization"))
+ bodyBytes, err := io.ReadAll(r.Body)
+ require.NoError(t, err)
+ require.JSONEq(t, submitListensRequest, string(bodyBytes))
+
+ w.WriteHeader(http.StatusOK)
+ w.Write([]byte(`{"accepted": 1}`))
+ }),
+ )
+
+ err := client.Scrobble(
+ db.User{ListenBrainzURL: "https://listenbrainz.org", ListenBrainzToken: "token1"},
+ scrobble.Track{Track: "title", Artist: "artist", Album: "album", TrackNumber: 1},
+ time.Unix(1683804525, 0),
+ true,
+ )
+ require.NoError(t, err)
+}
+
+func TestScrobbleUnauthorized(t *testing.T) {
+ t.Parallel()
+
+ client := listenbrainz.NewClientCustom(
+ newMockClient(t, func(w http.ResponseWriter, r *http.Request) {
+ require.Equal(t, http.MethodPost, r.Method)
+ require.Equal(t, "/1/submit-listens", r.URL.Path)
+ require.Equal(t, "application/json", r.Header.Get("Content-Type"))
+ require.Equal(t, "Token token1", r.Header.Get("Authorization"))
+
+ w.WriteHeader(http.StatusUnauthorized)
+ w.Write([]byte(`{"code": 401, "error": "Invalid authorization token."}`))
+ }),
+ )
+
+ err := client.Scrobble(
+ db.User{ListenBrainzURL: "https://listenbrainz.org", ListenBrainzToken: "token1"},
+ scrobble.Track{Track: "title", Artist: "artist", Album: "album", TrackNumber: 1},
+ time.Now(),
+ true,
+ )
+
+ require.ErrorIs(t, err, listenbrainz.ErrListenBrainz)
+}
+
+func TestScrobbleServerError(t *testing.T) {
+ t.Parallel()
+
+ client := listenbrainz.NewClientCustom(
+ newMockClient(t, func(w http.ResponseWriter, r *http.Request) {
+ require.Equal(t, http.MethodPost, r.Method)
+ require.Equal(t, "/1/submit-listens", r.URL.Path)
+ require.Equal(t, "application/json", r.Header.Get("Content-Type"))
+ require.Equal(t, "Token token1", r.Header.Get("Authorization"))
+
+ w.WriteHeader(http.StatusInternalServerError)
+ }),
+ )
+
+ err := client.Scrobble(
+ db.User{ListenBrainzURL: "https://listenbrainz.org", ListenBrainzToken: "token1"},
+ scrobble.Track{Track: "title", Artist: "artist", Album: "album", TrackNumber: 1},
+ time.Now(),
+ true,
+ )
+
+ require.ErrorIs(t, err, listenbrainz.ErrListenBrainz)
+}
+
+func newMockClient(tb testing.TB, handler http.HandlerFunc) *http.Client {
+ tb.Helper()
+
+ server := httptest.NewTLSServer(handler)
+ tb.Cleanup(server.Close)
+
+ return &http.Client{
+ Transport: &http.Transport{
+ DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
+ return net.Dial(network, server.Listener.Addr().String())
+ },
+ TLSClientConfig: &tls.Config{
+ InsecureSkipVerify: true, //nolint:gosec
+ },
+ },
+ }
+}
+
+//go:embed testdata/submit_listens_request.json
+var submitListensRequest string
diff --git a/scrobble/listenbrainz/model.go b/listenbrainz/model.go
similarity index 100%
rename from scrobble/listenbrainz/model.go
rename to listenbrainz/model.go
diff --git a/scrobble/listenbrainz/testdata/submit_listens_request.json b/listenbrainz/testdata/submit_listens_request.json
similarity index 100%
rename from scrobble/listenbrainz/testdata/submit_listens_request.json
rename to listenbrainz/testdata/submit_listens_request.json
diff --git a/mime/mime.go b/mime/mime.go
deleted file mode 100644
index 04ffe56..0000000
--- a/mime/mime.go
+++ /dev/null
@@ -1,40 +0,0 @@
-//nolint:gochecknoglobals
-package mime
-
-import (
- "log"
- stdmime "mime"
- "strings"
-)
-
-var supportedAudioTypes = map[string]string{
- ".mp3": "audio/mpeg",
- ".flac": "audio/x-flac",
- ".aac": "audio/x-aac",
- ".m4a": "audio/m4a",
- ".m4b": "audio/m4b",
- ".ogg": "audio/ogg",
- ".opus": "audio/ogg",
- ".wma": "audio/x-ms-wma",
- ".wav": "audio/x-wav",
-}
-
-//nolint:gochecknoinits
-func init() {
- for ext, mime := range supportedAudioTypes {
- if err := stdmime.AddExtensionType(ext, mime); err != nil {
- log.Fatalf("adding audio type mime for ext %q: %v", ext, err)
- }
- }
-}
-
-var TypeByExtension = stdmime.TypeByExtension
-var ParseMediaType = stdmime.ParseMediaType
-var FormatMediaType = stdmime.FormatMediaType
-
-func TypeByAudioExtension(ext string) string {
- if _, ok := supportedAudioTypes[strings.ToLower(ext)]; !ok {
- return ""
- }
- return stdmime.TypeByExtension(ext)
-}
diff --git a/mockfs/mockfs.go b/mockfs/mockfs.go
index 8221604..23eabc5 100644
--- a/mockfs/mockfs.go
+++ b/mockfs/mockfs.go
@@ -1,20 +1,19 @@
+//nolint:thelper
package mockfs
import (
"context"
"errors"
"fmt"
- "net/url"
"os"
"path/filepath"
"strings"
"testing"
"time"
- "github.com/mattn/go-sqlite3"
"go.senan.xyz/gonic/db"
"go.senan.xyz/gonic/scanner"
- "go.senan.xyz/gonic/scanner/tags"
+ "go.senan.xyz/gonic/tags/tagcommon"
)
var ErrPathNotFound = errors.New("path not found")
@@ -27,29 +26,31 @@ type MockFS struct {
db *db.DB
}
-func New(t testing.TB) *MockFS { return newMockFS(t, []string{""}, "") }
-func NewWithDirs(t testing.TB, dirs []string) *MockFS { return newMockFS(t, dirs, "") }
-func NewWithExcludePattern(t testing.TB, excludePattern string) *MockFS {
- return newMockFS(t, []string{""}, excludePattern)
+func New(tb testing.TB) *MockFS { return newMockFS(tb, []string{""}, "") }
+func NewWithDirs(tb testing.TB, dirs []string) *MockFS { return newMockFS(tb, dirs, "") }
+func NewWithExcludePattern(tb testing.TB, excludePattern string) *MockFS {
+ return newMockFS(tb, []string{""}, excludePattern)
}
-func newMockFS(t testing.TB, dirs []string, excludePattern string) *MockFS {
+func newMockFS(tb testing.TB, dirs []string, excludePattern string) *MockFS {
+ tb.Helper()
+
dbc, err := db.NewMock()
if err != nil {
- t.Fatalf("create db: %v", err)
+ tb.Fatalf("create db: %v", err)
}
- t.Cleanup(func() {
+ tb.Cleanup(func() {
if err := dbc.Close(); err != nil {
- t.Fatalf("close db: %v", err)
+ tb.Fatalf("close db: %v", err)
}
})
if err := dbc.Migrate(db.MigrationContext{}); err != nil {
- t.Fatalf("migrate db db: %v", err)
+ tb.Fatalf("migrate db db: %v", err)
}
dbc.LogMode(false)
- tmpDir := t.TempDir()
+ tmpDir := tb.TempDir()
var absDirs []string
for _, dir := range dirs {
@@ -57,7 +58,7 @@ func newMockFS(t testing.TB, dirs []string, excludePattern string) *MockFS {
}
for _, absDir := range absDirs {
if err := os.MkdirAll(absDir, os.ModePerm); err != nil {
- t.Fatalf("mk abs dir: %v", err)
+ tb.Fatalf("mk abs dir: %v", err)
}
}
@@ -66,11 +67,11 @@ func newMockFS(t testing.TB, dirs []string, excludePattern string) *MockFS {
scanner.AlbumArtist: {Mode: scanner.Multi},
}
- tagReader := &tagReader{paths: map[string]*tagReaderResult{}}
+ tagReader := &tagReader{paths: map[string]*TagInfo{}}
scanner := scanner.New(absDirs, dbc, multiValueSettings, tagReader, excludePattern)
return &MockFS{
- t: t,
+ t: tb,
scanner: scanner,
dir: tmpDir,
tagReader: tagReader,
@@ -78,10 +79,13 @@ func newMockFS(t testing.TB, dirs []string, excludePattern string) *MockFS {
}
}
-func (m *MockFS) DB() *db.DB { return m.db }
-func (m *MockFS) TmpDir() string { return m.dir }
+func (m *MockFS) DB() *db.DB { return m.db }
+func (m *MockFS) TmpDir() string { return m.dir }
+func (m *MockFS) TagReader() tagcommon.Reader { return m.tagReader }
func (m *MockFS) ScanAndClean() *scanner.Context {
+ m.t.Helper()
+
ctx, err := m.scanner.ScanAndClean(scanner.ScanOptions{})
if err != nil {
m.t.Fatalf("error scan and cleaning: %v", err)
@@ -90,6 +94,8 @@ func (m *MockFS) ScanAndClean() *scanner.Context {
}
func (m *MockFS) ScanAndCleanErr() (*scanner.Context, error) {
+ m.t.Helper()
+
return m.scanner.ScanAndClean(scanner.ScanOptions{})
}
@@ -122,12 +128,11 @@ func (m *MockFS) addItems(prefix string, onlyGlob string, covers bool) {
}
m.AddTrack(path)
- m.SetTags(path, func(tags *Tags) error {
+ m.SetTags(path, func(tags *TagInfo) {
tags.RawArtist = fmt.Sprintf("artist-%d", ar)
tags.RawAlbumArtist = fmt.Sprintf("artist-%d", ar)
tags.RawAlbum = fmt.Sprintf("album-%d", al)
tags.RawTitle = fmt.Sprintf("title-%d", tr)
- return nil
})
}
if covers {
@@ -176,10 +181,9 @@ func (m *MockFS) SetRealAudio(path string, length int, audioPath string) {
if err := os.Symlink(filepath.Join(wd, audioPath), abspath); err != nil {
m.t.Fatalf("symlink: %v", err)
}
- m.SetTags(path, func(tags *Tags) error {
+ m.SetTags(path, func(tags *TagInfo) {
tags.RawLength = length
tags.RawBitrate = 0
- return nil
})
}
@@ -284,18 +288,15 @@ func (m *MockFS) AddCover(path string) {
defer f.Close()
}
-func (m *MockFS) SetTags(path string, cb func(*Tags) error) {
- abspath := filepath.Join(m.dir, path)
- if err := os.Chtimes(abspath, time.Time{}, time.Now()); err != nil {
+func (m *MockFS) SetTags(path string, cb func(*TagInfo)) {
+ absPath := filepath.Join(m.dir, path)
+ if err := os.Chtimes(absPath, time.Time{}, time.Now()); err != nil {
m.t.Fatalf("touch track: %v", err)
}
- r := m.tagReader
- if _, ok := r.paths[abspath]; !ok {
- r.paths[abspath] = &tagReaderResult{tags: &Tags{}}
- }
- if err := cb(r.paths[abspath].tags); err != nil {
- r.paths[abspath].err = err
+ if _, ok := m.tagReader.paths[absPath]; !ok {
+ m.tagReader.paths[absPath] = &TagInfo{}
}
+ cb(m.tagReader.paths[absPath])
}
func (m *MockFS) DumpDB(suffix ...string) {
@@ -308,104 +309,63 @@ func (m *MockFS) DumpDB(suffix ...string) {
p = append(p, suffix...)
destPath := filepath.Join(os.TempDir(), strings.Join(p, "-"))
- dest, err := db.New(destPath, url.Values{})
- if err != nil {
- m.t.Fatalf("create dest db: %v", err)
- }
- defer dest.Close()
-
- connSrc, err := m.db.DB.DB().Conn(context.Background())
- if err != nil {
- m.t.Fatalf("getting src raw conn: %v", err)
- }
- defer connSrc.Close()
- connDest, err := dest.DB.DB().Conn(context.Background())
- if err != nil {
- m.t.Fatalf("getting dest raw conn: %v", err)
- }
- defer connDest.Close()
-
- err = connDest.Raw(func(connDest interface{}) error {
- return connSrc.Raw(func(connSrc interface{}) error {
- connDestq := connDest.(*sqlite3.SQLiteConn)
- connSrcq := connSrc.(*sqlite3.SQLiteConn)
- bk, err := connDestq.Backup("main", connSrcq, "main")
- if err != nil {
- return fmt.Errorf("create backup db: %w", err)
- }
- for done, _ := bk.Step(-1); !done; {
- m.t.Logf("dumping db...")
- }
- if err := bk.Finish(); err != nil {
- return fmt.Errorf("finishing dump: %w", err)
- }
- return nil
- })
- })
- if err != nil {
- m.t.Fatalf("backing up: %v", err)
+ if err := db.Dump(context.Background(), m.db.DB, destPath); err != nil {
+ m.t.Fatalf("dumping db: %v", err)
}
m.t.Error(destPath)
}
-type tagReaderResult struct {
- tags *Tags
- err error
-}
-
type tagReader struct {
- paths map[string]*tagReaderResult
+ paths map[string]*TagInfo
}
-func (m *tagReader) Read(abspath string) (tags.Parser, error) {
- p, ok := m.paths[abspath]
+func (m *tagReader) CanRead(absPath string) bool {
+ stat, _ := os.Stat(absPath)
+ return stat.Mode().IsRegular()
+}
+
+func (m *tagReader) Read(absPath string) (tagcommon.Info, error) {
+ p, ok := m.paths[absPath]
if !ok {
return nil, ErrPathNotFound
}
- return p.tags, p.err
+ if p.Error != nil {
+ return nil, p.Error
+ }
+ return p, nil
}
-var _ tags.Reader = (*tagReader)(nil)
-
-type Tags struct {
+type TagInfo struct {
RawTitle string
RawArtist string
+ RawArtists []string
RawAlbum string
RawAlbumArtist string
RawAlbumArtists []string
RawGenre string
-
- RawBitrate int
- RawLength int
+ RawBitrate int
+ RawLength int
+ Error error
}
-func (m *Tags) Title() string { return m.RawTitle }
-func (m *Tags) BrainzID() string { return "" }
-func (m *Tags) Artist() string { return m.RawArtist }
-func (m *Tags) Album() string { return m.RawAlbum }
-func (m *Tags) AlbumArtist() string { return m.RawAlbumArtist }
-func (m *Tags) AlbumArtists() []string { return m.RawAlbumArtists }
-func (m *Tags) AlbumBrainzID() string { return "" }
-func (m *Tags) Genre() string { return m.RawGenre }
-func (m *Tags) Genres() []string { return []string{m.RawGenre} }
-func (m *Tags) TrackNumber() int { return 1 }
-func (m *Tags) DiscNumber() int { return 1 }
-func (m *Tags) Year() int { return 2021 }
+func (i *TagInfo) Title() string { return i.RawTitle }
+func (i *TagInfo) BrainzID() string { return "" }
+func (i *TagInfo) Artist() string { return i.RawArtist }
+func (i *TagInfo) Artists() []string { return i.RawArtists }
+func (i *TagInfo) Album() string { return i.RawAlbum }
+func (i *TagInfo) AlbumArtist() string { return i.RawAlbumArtist }
+func (i *TagInfo) AlbumArtists() []string { return i.RawAlbumArtists }
+func (i *TagInfo) AlbumBrainzID() string { return "" }
+func (i *TagInfo) Genre() string { return i.RawGenre }
+func (i *TagInfo) Genres() []string { return []string{i.RawGenre} }
+func (i *TagInfo) TrackNumber() int { return 1 }
+func (i *TagInfo) DiscNumber() int { return 1 }
+func (i *TagInfo) Year() int { return 2021 }
+func (i *TagInfo) Length() int { return firstInt(100, i.RawLength) }
+func (i *TagInfo) Bitrate() int { return firstInt(100, i.RawBitrate) }
-func (m *Tags) Length() int { return firstInt(100, m.RawLength) }
-func (m *Tags) Bitrate() int { return firstInt(100, m.RawBitrate) }
-
-var _ tags.Parser = (*Tags)(nil)
-
-func first(or string, strs ...string) string {
- for _, str := range strs {
- if str != "" {
- return str
- }
- }
- return or
-}
+var _ tagcommon.Reader = (*tagReader)(nil)
func firstInt(or int, ints ...int) int {
for _, int := range ints {
diff --git a/playlist/playlist.go b/playlist/playlist.go
index bb8dd91..618af33 100644
--- a/playlist/playlist.go
+++ b/playlist/playlist.go
@@ -14,9 +14,11 @@ import (
"time"
)
-var ErrInvalidPathFormat = errors.New("invalid path format")
-var ErrInvalidBasePath = errors.New("invalid base path")
-var ErrNoUserPrefix = errors.New("no user prefix")
+var (
+ ErrInvalidPathFormat = errors.New("invalid path format")
+ ErrInvalidBasePath = errors.New("invalid base path")
+ ErrNoUserPrefix = errors.New("no user prefix")
+)
const (
extM3U = ".m3u"
@@ -31,7 +33,6 @@ type Store struct {
func NewStore(basePath string) (*Store, error) {
if basePath == "" {
return nil, ErrInvalidBasePath
-
}
// sanity check layout, just in case someone tries to use an existing folder
@@ -108,6 +109,7 @@ const (
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 "", ""
@@ -169,10 +171,10 @@ func (s *Store) Write(relPath string, playlist *Playlist) error {
defer lock(&s.mu)()
absPath := filepath.Join(s.basePath, relPath)
- if err := os.MkdirAll(filepath.Dir(absPath), 0777); err != nil {
+ if err := os.MkdirAll(filepath.Dir(absPath), 0o777); err != nil {
return fmt.Errorf("make m3u base dir: %w", err)
}
- file, err := os.OpenFile(absPath, os.O_RDWR|os.O_CREATE, 0666)
+ file, err := os.OpenFile(absPath, os.O_RDWR|os.O_CREATE, 0o666)
if err != nil {
return fmt.Errorf("create m3u: %w", err)
}
diff --git a/playlist/playlist_test.go b/playlist/playlist_test.go
index 52c1387..10b6234 100644
--- a/playlist/playlist_test.go
+++ b/playlist/playlist_test.go
@@ -8,20 +8,20 @@ import (
)
func TestPlaylist(t *testing.T) {
- require := require.New(t)
+ t.Parallel()
tmp := t.TempDir()
store, err := playlist.NewStore(tmp)
- require.NoError(err)
+ require.NoError(t, err)
playlistIDs, err := store.List()
- require.NoError(err)
- require.Empty(playlistIDs)
+ require.NoError(t, err)
+ require.Empty(t, playlistIDs)
for _, playlistID := range playlistIDs {
playlist, err := store.Read(playlistID)
- require.NoError(err)
- require.NotZero(playlist.UpdatedAt)
+ require.NoError(t, err)
+ require.NotZero(t, playlist.UpdatedAt)
}
before := playlist.Playlist{
@@ -40,18 +40,18 @@ It has multiple lines 👍
}
newPath := playlist.NewPath(before.UserID, before.Name)
- require.NoError(store.Write(newPath, &before))
+ require.NoError(t, store.Write(newPath, &before))
after, err := store.Read(newPath)
- require.NoError(err)
+ require.NoError(t, err)
- require.Equal(after.UserID, before.UserID)
- require.Equal(after.Name, before.Name)
- require.Equal(after.Comment, before.Comment)
- require.Equal(after.Items, before.Items)
- require.Equal(after.IsPublic, before.IsPublic)
+ require.Equal(t, after.UserID, before.UserID)
+ require.Equal(t, after.Name, before.Name)
+ require.Equal(t, after.Comment, before.Comment)
+ require.Equal(t, after.Items, before.Items)
+ require.Equal(t, after.IsPublic, before.IsPublic)
playlistIDs, err = store.List()
- require.NoError(err)
- require.True(len(playlistIDs) == 1)
+ require.NoError(t, err)
+ require.True(t, len(playlistIDs) == 1)
}
diff --git a/podcasts/podcasts.go b/podcast/podcast.go
similarity index 74%
rename from podcasts/podcasts.go
rename to podcast/podcast.go
index b2e8368..00851e2 100644
--- a/podcasts/podcasts.go
+++ b/podcast/podcast.go
@@ -1,16 +1,16 @@
-package podcasts
+package podcast
import (
"errors"
"fmt"
"io"
"log"
+ "mime"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
- "regexp"
"strconv"
"strings"
"time"
@@ -19,65 +19,28 @@ import (
"github.com/mmcdole/gofeed"
"go.senan.xyz/gonic/db"
- "go.senan.xyz/gonic/mime"
- "go.senan.xyz/gonic/scanner/tags"
+ "go.senan.xyz/gonic/fileutil"
+ "go.senan.xyz/gonic/tags/tagcommon"
)
var ErrNoAudioInFeedItem = errors.New("no audio in feed item")
-const downloadAllWaitInterval = 3 * time.Second
-const 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`
+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`
+)
type Podcasts struct {
- db *db.DB
- baseDir string
- tagger tags.Reader
+ db *db.DB
+ baseDir string
+ tagReader tagcommon.Reader
}
-func New(db *db.DB, base string, tagger tags.Reader) *Podcasts {
- // Walk podcast path making filenames safe. Phase 1: Files
- err := filepath.WalkDir(base, func(path string, d os.DirEntry, err error) error {
- if (path == base) || d.IsDir() {
- return nil
- }
- if err != nil {
- return err
- }
- localBase := d.Name()
- dir := filepath.Dir(path)
- safeBase := safeFilename(localBase)
- if localBase == safeBase {
- return nil
- }
- return os.Rename(strings.Join([]string{dir, localBase}, "/"), strings.Join([]string{dir, safeBase}, "/"))
- })
- if err != nil {
- log.Fatalf("error making podcast episode filenames safe: %v\n", err)
- }
- // Phase 2: Directories
- err = filepath.WalkDir(base, func(path string, d os.DirEntry, err error) error {
- var pathError *os.PathError
- if (path == base) || !d.IsDir() || errors.As(err, &pathError) { // Spurious path errors after move
- return nil
- }
- if err != nil {
- return err
- }
- localBase := d.Name()
- dir := filepath.Dir(path)
- safeBase := safeFilename(localBase)
- if localBase == safeBase {
- return nil
- }
- return os.Rename(strings.Join([]string{dir, localBase}, "/"), strings.Join([]string{dir, safeBase}, "/"))
- })
- if err != nil {
- log.Fatalf("error making podcast directory names safe: %v\n", err)
- }
+func New(db *db.DB, base string, tagReader tagcommon.Reader) *Podcasts {
return &Podcasts{
- db: db,
- baseDir: base,
- tagger: tagger,
+ db: db,
+ baseDir: base,
+ tagReader: tagReader,
}
}
@@ -132,15 +95,18 @@ func (p *Podcasts) GetNewestPodcastEpisodes(count int) ([]*db.PodcastEpisode, er
}
func (p *Podcasts) AddNewPodcast(rssURL string, feed *gofeed.Feed) (*db.Podcast, error) {
+ rootDir, err := fileutil.Unique(filepath.Join(p.baseDir, fileutil.Safe(feed.Title)), "")
+ if err != nil {
+ return nil, fmt.Errorf("find unique podcast dir: %w", err)
+ }
podcast := db.Podcast{
Description: feed.Description,
ImageURL: feed.Image.URL,
Title: feed.Title,
URL: rssURL,
+ RootDir: rootDir,
}
- podPath := absPath(p.baseDir, &podcast)
- err := os.Mkdir(podPath, 0755)
- if err != nil && !os.IsExist(err) {
+ if err := os.Mkdir(podcast.RootDir, 0o755); err != nil && !os.IsExist(err) {
return nil, err
}
if err := p.db.Save(&podcast).Error; err != nil {
@@ -150,7 +116,7 @@ func (p *Podcasts) AddNewPodcast(rssURL string, feed *gofeed.Feed) (*db.Podcast,
return nil, err
}
go func() {
- if err := p.downloadPodcastCover(podPath, &podcast); err != nil {
+ if err := p.downloadPodcastCover(&podcast); err != nil {
log.Printf("error downloading podcast cover: %v", err)
}
}()
@@ -273,17 +239,17 @@ func (p *Podcasts) AddEpisode(podcastID int, item *gofeed.Item) (*db.PodcastEpis
return nil, ErrNoAudioInFeedItem
}
-func isAudio(rawItemURL string) (bool, error) {
+func (p *Podcasts) isAudio(rawItemURL string) (bool, error) {
itemURL, err := url.Parse(rawItemURL)
if err != nil {
return false, err
}
-
- return mime.TypeByAudioExtension(path.Ext(itemURL.Path)) != "", nil
+ return p.tagReader.CanRead(itemURL.Path), nil
}
func itemToEpisode(podcastID, size, duration int, audio string,
- item *gofeed.Item) *db.PodcastEpisode {
+ item *gofeed.Item,
+) *db.PodcastEpisode {
return &db.PodcastEpisode{
PodcastID: podcastID,
Description: item.Description,
@@ -298,7 +264,7 @@ func itemToEpisode(podcastID, size, duration int, audio string,
func (p *Podcasts) findEnclosureAudio(podcastID, duration int, item *gofeed.Item) (*db.PodcastEpisode, bool) {
for _, enc := range item.Enclosures {
- if t, err := isAudio(enc.URL); !t || err != nil {
+ if t, err := p.isAudio(enc.URL); !t || err != nil {
continue
}
size, _ := strconv.Atoi(enc.Length)
@@ -313,7 +279,7 @@ func (p *Podcasts) findMediaAudio(podcastID, duration int, item *gofeed.Item) (*
return nil, false
}
for _, ext := range extensions {
- if t, err := isAudio(ext.Attrs["url"]); !t || err != nil {
+ if t, err := p.isAudio(ext.Attrs["url"]); !t || err != nil {
continue
}
return itemToEpisode(podcastID, 0, duration, ext.Attrs["url"], item), true
@@ -379,6 +345,7 @@ func (p *Podcasts) DownloadEpisode(episodeID int) error {
podcastEpisode := db.PodcastEpisode{}
podcast := db.Podcast{}
err := p.db.
+ Preload("Podcast").
Where("id=?", episodeID).
First(&podcastEpisode).
Error
@@ -417,13 +384,16 @@ func (p *Podcasts) DownloadEpisode(episodeID int) error {
}
filename = path.Base(audioURL.Path)
}
- filename = p.findUniqueEpisodeName(&podcast, &podcastEpisode, safeFilename(filename))
- audioFile, err := os.Create(path.Join(absPath(p.baseDir, &podcast), filename))
+ path, err := fileutil.Unique(podcast.RootDir, fileutil.Safe(filename))
+ if err != nil {
+ return fmt.Errorf("find unique path: %w", err)
+ }
+ _, 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
- podcastEpisode.Path = path.Join(safeFilename(podcast.Title), filename)
p.db.Save(&podcastEpisode)
go func() {
if err := p.doPodcastDownload(&podcastEpisode, audioFile, resp.Body); err != nil {
@@ -433,68 +403,48 @@ func (p *Podcasts) DownloadEpisode(episodeID int) error {
return nil
}
-func (p *Podcasts) findUniqueEpisodeName(podcast *db.Podcast, podcastEpisode *db.PodcastEpisode, filename string) string {
- podcastPath := path.Join(absPath(p.baseDir, podcast), filename)
- if _, err := os.Stat(podcastPath); os.IsNotExist(err) {
- return filename
- }
- titlePath := fmt.Sprintf("%s%s", safeFilename(podcastEpisode.Title), filepath.Ext(filename))
- podcastPath = path.Join(absPath(p.baseDir, podcast), titlePath)
- if _, err := os.Stat(podcastPath); os.IsNotExist(err) {
- return titlePath
- }
- // try to find a filename like FILENAME (1).mp3 incrementing
- return findEpisode(absPath(p.baseDir, podcast), filename, 1)
-}
-
-func findEpisode(base, filename string, count int) string {
- noExt := strings.TrimSuffix(filename, filepath.Ext(filename))
- testFile := fmt.Sprintf("%s (%d)%s", noExt, count, filepath.Ext(filename))
- podcastPath := path.Join(base, testFile)
- if _, err := os.Stat(podcastPath); os.IsNotExist(err) {
- return testFile
- }
- return findEpisode(base, filename, count+1)
-}
-
func getContentDispositionFilename(header string) (string, bool) {
_, params, _ := mime.ParseMediaType(header)
filename, ok := params["filename"]
return filename, ok
}
-func (p *Podcasts) downloadPodcastCover(podPath string, podcast *db.Podcast) error {
+func (p *Podcasts) downloadPodcastCover(podcast *db.Podcast) error {
imageURL, err := url.Parse(podcast.ImageURL)
if err != nil {
return fmt.Errorf("parse image url: %w", err)
}
- ext := path.Ext(imageURL.Path)
- client := &http.Client{}
req, err := http.NewRequest("GET", podcast.ImageURL, nil)
if err != nil {
return fmt.Errorf("create http request: %w", err)
}
req.Header.Add("User-Agent", fetchUserAgent)
- // nolint: bodyclose
+
+ client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("fetch image url: %w", err)
}
+ defer resp.Body.Close()
+
+ ext := path.Ext(imageURL.Path)
if ext == "" {
contentHeader := resp.Header.Get("content-disposition")
filename, _ := getContentDispositionFilename(contentHeader)
- ext = path.Ext(filename)
+ ext = filepath.Ext(filename)
}
- coverPath := path.Join(podPath, "cover"+ext)
- coverFile, err := os.Create(coverPath)
+
+ cover := "cover" + ext
+ coverFile, err := os.Create(filepath.Join(podcast.RootDir, cover))
if err != nil {
return fmt.Errorf("creating podcast cover: %w", err)
}
defer coverFile.Close()
+
if _, err := io.Copy(coverFile, resp.Body); err != nil {
return fmt.Errorf("writing podcast cover: %w", err)
}
- podcast.ImagePath = path.Join(safeFilename(podcast.Title), fmt.Sprintf("cover%s", ext))
+ podcast.Image = fmt.Sprintf("cover%s", ext)
if err := p.db.Save(podcast).Error; err != nil {
return fmt.Errorf("save podcast: %w", err)
}
@@ -506,20 +456,25 @@ func (p *Podcasts) doPodcastDownload(podcastEpisode *db.PodcastEpisode, file *os
return fmt.Errorf("writing podcast episode: %w", err)
}
defer file.Close()
- stat, _ := file.Stat()
- podcastPath := path.Join(p.baseDir, podcastEpisode.Path)
- podcastTags, err := p.tagger.Read(podcastPath)
+
+ 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())
- return p.db.Save(podcastEpisode).Error
+
+ 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 {
@@ -531,7 +486,11 @@ func (p *Podcasts) DeletePodcast(podcastID int) error {
if err != nil {
return err
}
- if err := os.RemoveAll(absPath(p.baseDir, &podcast)); err != nil {
+ if podcast.RootDir == "" {
+ return fmt.Errorf("podcast has no root dir")
+ }
+
+ if err := os.RemoveAll(podcast.RootDir); err != nil {
return fmt.Errorf("delete podcast directory: %w", err)
}
err = p.db.
@@ -546,13 +505,13 @@ func (p *Podcasts) DeletePodcast(podcastID int) error {
func (p *Podcasts) DeletePodcastEpisode(podcastEpisodeID int) error {
episode := db.PodcastEpisode{}
- err := p.db.First(&episode, podcastEpisodeID).Error
+ err := p.db.Preload("Podcast").First(&episode, podcastEpisodeID).Error
if err != nil {
return err
}
episode.Status = db.PodcastEpisodeStatusDeleted
p.db.Save(&episode)
- if err := os.Remove(filepath.Join(p.baseDir, episode.Path)); err != nil {
+ if err := os.Remove(episode.AbsPath()); err != nil {
return err
}
return err
@@ -566,6 +525,7 @@ func (p *Podcasts) PurgeOldPodcasts(maxAge time.Duration) error {
Where("created_at < ?", expDate).
Where("updated_at < ?", expDate).
Where("modified_at < ?", expDate).
+ Preload("Podcast").
Find(&episodes).
Error
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
@@ -576,20 +536,12 @@ func (p *Podcasts) PurgeOldPodcasts(maxAge time.Duration) error {
if err := p.db.Save(episode).Error; err != nil {
return fmt.Errorf("save new podcast status: %w", err)
}
- if err := os.Remove(filepath.Join(p.baseDir, episode.Path)); err != nil {
+ if episode.Podcast == nil {
+ return fmt.Errorf("episode %d has no podcast", episode.ID)
+ }
+ if err := os.Remove(episode.AbsPath()); err != nil {
return fmt.Errorf("remove podcast path: %w", err)
}
}
return nil
}
-
-var nonAlphaNum = regexp.MustCompile("[^a-zA-Z0-9_.]+")
-
-func safeFilename(filename string) string {
- filename = nonAlphaNum.ReplaceAllString(filename, "")
- return filename
-}
-
-func absPath(base string, p *db.Podcast) string {
- return filepath.Join(base, safeFilename(p.Title))
-}
diff --git a/podcast/podcast_test.go b/podcast/podcast_test.go
new file mode 100644
index 0000000..377565d
--- /dev/null
+++ b/podcast/podcast_test.go
@@ -0,0 +1,81 @@
+package podcast
+
+import (
+ "bytes"
+ _ "embed"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "github.com/mmcdole/gofeed"
+ "github.com/stretchr/testify/require"
+ "go.senan.xyz/gonic/db"
+ "go.senan.xyz/gonic/mockfs"
+)
+
+//go:embed testdata/rss.new
+var testRSS []byte
+
+func TestPodcastsAndEpisodesWithSameName(t *testing.T) {
+ t.Parallel()
+
+ t.Skip("requires network access")
+
+ m := mockfs.New(t)
+
+ base := t.TempDir()
+ podcasts := New(m.DB(), base, m.TagReader())
+
+ fp := gofeed.NewParser()
+ newFeed, err := fp.Parse(bytes.NewReader(testRSS))
+ if err != nil {
+ t.Fatalf("parse test data: %v", err)
+ }
+
+ podcast, err := podcasts.AddNewPodcast("file://testdata/rss.new", newFeed)
+ require.NoError(t, err)
+
+ require.Equal(t, podcast.RootDir, filepath.Join(base, "InternetBox"))
+
+ podcast, err = podcasts.AddNewPodcast("file://testdata/rss.new", newFeed)
+ require.NoError(t, err)
+
+ // check we made a unique podcast name
+ require.Equal(t, podcast.RootDir, filepath.Join(base, "InternetBox (1)"))
+
+ podcastEpisodes, err := podcasts.GetNewestPodcastEpisodes(10)
+ require.NoError(t, err)
+ require.Greater(t, len(podcastEpisodes), 0)
+
+ var pe []*db.PodcastEpisode
+ require.NoError(t, m.DB().Order("id").Find(&pe, "podcast_id=? AND title=?", podcast.ID, "Episode 126").Error)
+ require.Len(t, pe, 2)
+
+ require.NoError(t, podcasts.DownloadEpisode(pe[0].ID))
+ require.NoError(t, podcasts.DownloadEpisode(pe[1].ID))
+
+ require.NoError(t, m.DB().Order("id").Preload("Podcast").Find(&pe, "podcast_id=? AND title=?", podcast.ID, "Episode 126").Error)
+ require.Len(t, pe, 2)
+
+ // check we made a unique podcast episode names
+ require.Equal(t, "InternetBoxEpisode126.mp3", pe[0].Filename)
+ require.Equal(t, "InternetBoxEpisode126 (1).mp3", pe[1].Filename)
+}
+
+func TestGetMoreRecentEpisodes(t *testing.T) {
+ t.Parallel()
+
+ fp := gofeed.NewParser()
+ newFeed, err := fp.Parse(bytes.NewReader(testRSS))
+ if err != nil {
+ t.Fatalf("parse test data: %v", err)
+ }
+ after, err := time.Parse(time.RFC1123, "Mon, 27 Jun 2016 06:33:43 +0000")
+ if err != nil {
+ t.Fatalf("parse time: %v", err)
+ }
+ entries := getEntriesAfterDate(newFeed.Items, after)
+ if len(entries) != 2 {
+ t.Errorf("expected 2 entries, got %d", len(entries))
+ }
+}
diff --git a/podcasts/testdata/rss.new b/podcast/testdata/rss.new
similarity index 82%
rename from podcasts/testdata/rss.new
rename to podcast/testdata/rss.new
index 64f85c0..086207a 100644
--- a/podcasts/testdata/rss.new
+++ b/podcast/testdata/rss.new
@@ -2,7 +2,7 @@
- Internet Box
+ Internet Box!
Mon, 01 Apr 2019 04:35:43 +0000
Sun, 10 Jan 2021 00:07:33 +0000
Libsyn WebEngine 2.0
@@ -70,7 +70,23 @@
Mon, 27 Jun 2016 06:33:43 +0000
-
+
+ The Internet Box is clicking this week!
]]>
+ The Internet Box is clicking this week!]]>
+
+ 01:20:42
+ yes
+ box,2,factory,internet,pizza,future,robots,season,farts,cake,via,reddit,313,vorarephilia
+
+
+
+
+ -
+ Episode 126
+ Mon, 27 Jun 2016 06:33:43 +0000
+
+
+
The Internet Box is clicking this week!]]>
The Internet Box is clicking this week!]]>
diff --git a/podcasts/podcasts_test.go b/podcasts/podcasts_test.go
deleted file mode 100644
index 279d96a..0000000
--- a/podcasts/podcasts_test.go
+++ /dev/null
@@ -1,29 +0,0 @@
-package podcasts
-
-import (
- "os"
- "testing"
- "time"
-
- "github.com/mmcdole/gofeed"
-)
-
-func TestGetMoreRecentEpisodes(t *testing.T) {
- fp := gofeed.NewParser()
- newFile, err := os.Open("testdata/rss.new")
- if err != nil {
- t.Fatalf("open test data: %v", err)
- }
- newFeed, err := fp.Parse(newFile)
- if err != nil {
- t.Fatalf("parse test data: %v", err)
- }
- after, err := time.Parse(time.RFC1123, "Mon, 27 Jun 2016 06:33:43 +0000")
- if err != nil {
- t.Fatalf("parse time: %v", err)
- }
- entries := getEntriesAfterDate(newFeed.Items, after)
- if len(entries) != 2 {
- t.Errorf("expected 2 entries, got %d", len(entries))
- }
-}
diff --git a/scanner/scanner.go b/scanner/scanner.go
index 9ac1914..e405a5a 100644
--- a/scanner/scanner.go
+++ b/scanner/scanner.go
@@ -1,3 +1,4 @@
+//nolint:nestif
package scanner
import (
@@ -19,8 +20,7 @@ import (
"github.com/rainycape/unidecode"
"go.senan.xyz/gonic/db"
- "go.senan.xyz/gonic/mime"
- "go.senan.xyz/gonic/scanner/tags"
+ "go.senan.xyz/gonic/tags/tagcommon"
)
var (
@@ -32,15 +32,12 @@ type Scanner struct {
db *db.DB
musicDirs []string
multiValueSettings map[Tag]MultiValueSetting
- tagger tags.Reader
+ tagReader tagcommon.Reader
excludePattern *regexp.Regexp
scanning *int32
- watcher *fsnotify.Watcher
- watchMap map[string]string // maps watched dirs back to root music dir
- watchDone chan bool
}
-func New(musicDirs []string, db *db.DB, multiValueSettings map[Tag]MultiValueSetting, tagger tags.Reader, excludePattern string) *Scanner {
+func New(musicDirs []string, db *db.DB, multiValueSettings map[Tag]MultiValueSetting, tagReader tagcommon.Reader, excludePattern string) *Scanner {
var excludePatternRegExp *regexp.Regexp
if excludePattern != "" {
excludePatternRegExp = regexp.MustCompile(excludePattern)
@@ -50,23 +47,15 @@ func New(musicDirs []string, db *db.DB, multiValueSettings map[Tag]MultiValueSet
db: db,
musicDirs: musicDirs,
multiValueSettings: multiValueSettings,
- tagger: tagger,
+ tagReader: tagReader,
excludePattern: excludePatternRegExp,
scanning: new(int32),
- watchMap: make(map[string]string),
- watchDone: make(chan bool),
}
}
-func (s *Scanner) IsScanning() bool {
- return atomic.LoadInt32(s.scanning) == 1
-}
-func (s *Scanner) StartScanning() bool {
- return atomic.CompareAndSwapInt32(s.scanning, 0, 1)
-}
-func (s *Scanner) StopScanning() {
- defer atomic.StoreInt32(s.scanning, 0)
-}
+func (s *Scanner) IsScanning() bool { return atomic.LoadInt32(s.scanning) == 1 }
+func (s *Scanner) StartScanning() bool { return atomic.CompareAndSwapInt32(s.scanning, 0, 1) }
+func (s *Scanner) StopScanning() { defer atomic.StoreInt32(s.scanning, 0) }
type ScanOptions struct {
IsFull bool
@@ -93,7 +82,7 @@ func (s *Scanner) ScanAndClean(opts ScanOptions) (*Context, error) {
for _, dir := range s.musicDirs {
err := filepath.WalkDir(dir, func(absPath string, d fs.DirEntry, err error) error {
- return s.scanCallback(c, dir, absPath, d, err)
+ return s.scanCallback(c, absPath, d, err)
})
if err != nil {
return nil, fmt.Errorf("walk: %w", err)
@@ -120,94 +109,82 @@ func (s *Scanner) ScanAndClean(opts ScanOptions) (*Context, error) {
return c, errors.Join(c.errs...)
}
-func (s *Scanner) ExecuteWatch() error {
- var err error
- s.watcher, err = fsnotify.NewWatcher()
+func (s *Scanner) ExecuteWatch(done <-chan struct{}) error {
+ watcher, err := fsnotify.NewWatcher()
if err != nil {
- log.Printf("error creating watcher: %v\n", err)
- return err
+ return fmt.Errorf("creating watcher: %w", err)
}
- defer s.watcher.Close()
+ defer watcher.Close()
- t := time.NewTimer(10 * time.Second)
- if !t.Stop() {
- <-t.C
- }
+ const batchInterval = 10 * time.Second
+ batchT := time.NewTimer(batchInterval)
+ batchT.Stop()
for _, dir := range s.musicDirs {
err := filepath.WalkDir(dir, func(absPath string, d fs.DirEntry, err error) error {
- return s.watchCallback(dir, absPath, d, err)
+ return watchCallback(watcher, absPath, d, err)
})
if err != nil {
log.Printf("error watching directory tree: %v\n", err)
+ continue
}
}
- scanList := map[string]struct{}{}
+ batchSeen := map[string]struct{}{}
for {
select {
- case <-t.C:
+ case <-batchT.C:
if !s.StartScanning() {
- scanList = map[string]struct{}{}
break
}
- for dirName := range scanList {
+ for absPath := range batchSeen {
c := &Context{
seenTracks: map[int]struct{}{},
seenAlbums: map[int]struct{}{},
- isFull: false,
}
- musicDirName := s.watchMap[dirName]
- if musicDirName == "" {
- musicDirName = s.watchMap[filepath.Dir(dirName)]
- }
- err = filepath.WalkDir(dirName, func(absPath string, d fs.DirEntry, err error) error {
- return s.watchCallback(musicDirName, absPath, d, err)
+ err = filepath.WalkDir(absPath, func(absPath string, d fs.DirEntry, err error) error {
+ return watchCallback(watcher, absPath, d, err)
})
if err != nil {
log.Printf("error watching directory tree: %v\n", err)
+ continue
}
- err = filepath.WalkDir(dirName, func(absPath string, d fs.DirEntry, err error) error {
- return s.scanCallback(c, musicDirName, absPath, d, err)
+ err = filepath.WalkDir(absPath, func(absPath string, d fs.DirEntry, err error) error {
+ return s.scanCallback(c, absPath, d, err)
})
if err != nil {
log.Printf("error walking: %v", err)
+ continue
}
-
}
- scanList = map[string]struct{}{}
s.StopScanning()
- case event := <-s.watcher.Events:
- var dirName string
+ clear(batchSeen)
+
+ case event := <-watcher.Events:
if event.Op&(fsnotify.Create|fsnotify.Write) == 0 {
break
}
- if len(scanList) == 0 {
- t.Reset(10 * time.Second)
- }
fileInfo, err := os.Stat(event.Name)
if err != nil {
break
}
if fileInfo.IsDir() {
- dirName = event.Name
+ batchSeen[event.Name] = struct{}{}
} else {
- dirName = filepath.Dir(event.Name)
+ batchSeen[filepath.Dir(event.Name)] = struct{}{}
}
- scanList[dirName] = struct{}{}
- case err = <-s.watcher.Errors:
+ batchT.Reset(batchInterval)
+
+ case err = <-watcher.Errors:
log.Printf("error from watcher: %v\n", err)
- case <-s.watchDone:
+
+ case <-done:
return nil
}
}
}
-func (s *Scanner) CancelWatch() {
- s.watchDone <- true
-}
-
-func (s *Scanner) watchCallback(dir string, absPath string, d fs.DirEntry, err error) error {
+func watchCallback(watcher *fsnotify.Watcher, absPath string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
@@ -218,27 +195,23 @@ func (s *Scanner) watchCallback(dir string, absPath string, d fs.DirEntry, err e
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 s.watchCallback(dir, subAbs, d, err)
+ return watchCallback(watcher, subAbs, d, err)
})
default:
return nil
}
- if s.watchMap[absPath] == "" {
- s.watchMap[absPath] = dir
- err = s.watcher.Add(absPath)
+ if err := watcher.Add(absPath); err != nil {
+ return fmt.Errorf("add path to watcher: %w", err)
}
- return err
+ return nil
}
-func (s *Scanner) scanCallback(c *Context, dir string, absPath string, d fs.DirEntry, err error) error {
+func (s *Scanner) scanCallback(c *Context, absPath string, d fs.DirEntry, err error) error {
if err != nil {
c.errs = append(c.errs, err)
return nil
}
- if dir == absPath {
- return nil
- }
switch d.Type() {
case os.ModeDir:
@@ -246,33 +219,34 @@ func (s *Scanner) scanCallback(c *Context, dir string, absPath string, d fs.DirE
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 s.scanCallback(c, dir, subAbs, d, err)
+ return s.scanCallback(c, subAbs, d, err)
})
default:
return nil
}
if s.excludePattern != nil && s.excludePattern.MatchString(absPath) {
- log.Printf("excluding folder `%s`", absPath)
+ log.Printf("excluding folder %q", absPath)
return nil
}
- log.Printf("processing folder `%s`", absPath)
+ log.Printf("processing folder %q", absPath)
- tx := s.db.Begin()
- if err := s.scanDir(tx, c, dir, absPath); err != nil {
- c.errs = append(c.errs, fmt.Errorf("%q: %w", absPath, err))
- tx.Rollback()
+ return s.db.Transaction(func(tx *db.DB) error {
+ if err := s.scanDir(tx, c, absPath); err != nil {
+ c.errs = append(c.errs, fmt.Errorf("%q: %w", absPath, err))
+ return nil
+ }
return nil
- }
- if err := tx.Commit().Error; err != nil {
- return fmt.Errorf("commit tx: %w", err)
- }
-
- return nil
+ })
}
-func (s *Scanner) scanDir(tx *db.DB, c *Context, musicDir string, absPath string) error {
+func (s *Scanner) scanDir(tx *db.DB, c *Context, absPath string) error {
+ musicDir, relPath := musicDirRelative(s.musicDirs, absPath)
+ if musicDir == absPath {
+ return nil
+ }
+
items, err := os.ReadDir(absPath)
if err != nil {
return err
@@ -281,9 +255,12 @@ func (s *Scanner) scanDir(tx *db.DB, c *Context, musicDir string, absPath string
var tracks []string
var cover string
for _, item := range items {
- fullpath := filepath.Join(absPath, item.Name())
- if s.excludePattern != nil && s.excludePattern.MatchString(fullpath) {
- log.Printf("excluding path `%s`", fullpath)
+ absPath := filepath.Join(absPath, item.Name())
+ if s.excludePattern != nil && s.excludePattern.MatchString(absPath) {
+ log.Printf("excluding path %q", absPath)
+ continue
+ }
+ if item.IsDir() {
continue
}
@@ -291,13 +268,12 @@ func (s *Scanner) scanDir(tx *db.DB, c *Context, musicDir string, absPath string
cover = item.Name()
continue
}
- if mime := mime.TypeByAudioExtension(filepath.Ext(item.Name())); mime != "" {
+ if s.tagReader.CanRead(absPath) {
tracks = append(tracks, item.Name())
continue
}
}
- relPath, _ := filepath.Rel(musicDir, absPath)
pdir, pbasename := filepath.Split(filepath.Dir(relPath))
var parent db.Album
if err := tx.Where("root_dir=? AND left_path=? AND right_path=?", musicDir, pdir, pbasename).Assign(db.Album{RootDir: musicDir, LeftPath: pdir, RightPath: pbasename}).FirstOrCreate(&parent).Error; err != nil {
@@ -317,7 +293,7 @@ func (s *Scanner) scanDir(tx *db.DB, c *Context, musicDir string, absPath string
sort.Strings(tracks)
for i, basename := range tracks {
absPath := filepath.Join(musicDir, relPath, basename)
- if err := s.populateTrackAndAlbumArtists(tx, c, i, &album, basename, absPath); err != nil {
+ if err := s.populateTrackAndArtists(tx, c, i, &album, basename, absPath); err != nil {
return fmt.Errorf("populate track %q: %w", basename, err)
}
}
@@ -325,7 +301,7 @@ func (s *Scanner) scanDir(tx *db.DB, c *Context, musicDir string, absPath string
return nil
}
-func (s *Scanner) populateTrackAndAlbumArtists(tx *db.DB, c *Context, i int, album *db.Album, basename string, absPath string) error {
+func (s *Scanner) populateTrackAndArtists(tx *db.DB, c *Context, i int, album *db.Album, basename string, absPath string) error {
stat, err := os.Stat(absPath)
if err != nil {
return fmt.Errorf("stating %q: %w", basename, err)
@@ -341,20 +317,24 @@ func (s *Scanner) populateTrackAndAlbumArtists(tx *db.DB, c *Context, i int, alb
return nil
}
- trags, err := s.tagger.Read(absPath)
+ trags, err := s.tagReader.Read(absPath)
if err != nil {
- return fmt.Errorf("%v: %w", err, ErrReadingTags)
+ return fmt.Errorf("%w: %w", err, ErrReadingTags)
}
- genreNames := parseMulti(trags, s.multiValueSettings[Genre], tags.MustGenres, tags.MustGenre)
+ genreNames := parseMulti(trags, s.multiValueSettings[Genre], tagcommon.MustGenres, tagcommon.MustGenre)
genreIDs, err := populateGenres(tx, genreNames)
if err != nil {
return fmt.Errorf("populate genres: %w", err)
}
- // metadata for the album table comes only from the the first track's tags
+ // metadata for the album table comes only from the first track's tags
if i == 0 {
- albumArtistNames := parseMulti(trags, s.multiValueSettings[AlbumArtist], tags.MustAlbumArtists, tags.MustAlbumArtist)
+ if err := tx.Where("album_id=?", album.ID).Delete(db.ArtistAppearances{}).Error; err != nil {
+ return fmt.Errorf("delete artist appearances: %w", err)
+ }
+
+ albumArtistNames := parseMulti(trags, s.multiValueSettings[AlbumArtist], tagcommon.MustAlbumArtists, tagcommon.MustAlbumArtist)
var albumArtistIDs []int
for _, albumArtistName := range albumArtistNames {
albumArtist, err := populateArtist(tx, albumArtistName)
@@ -367,6 +347,10 @@ func (s *Scanner) populateTrackAndAlbumArtists(tx *db.DB, c *Context, i int, alb
return fmt.Errorf("populate album artists: %w", err)
}
+ if err := populateArtistAppearances(tx, album, albumArtistIDs); err != nil {
+ return fmt.Errorf("populate track artists: %w", err)
+ }
+
if err := populateAlbum(tx, album, trags, stat.ModTime()); err != nil {
return fmt.Errorf("populate album: %w", err)
}
@@ -383,16 +367,34 @@ func (s *Scanner) populateTrackAndAlbumArtists(tx *db.DB, c *Context, i int, alb
return fmt.Errorf("populate track genres: %w", err)
}
+ trackArtistNames := parseMulti(trags, s.multiValueSettings[Artist], tagcommon.MustArtists, tagcommon.MustArtist)
+ var trackArtistIDs []int
+ for _, trackArtistName := range trackArtistNames {
+ trackArtist, err := populateArtist(tx, trackArtistName)
+ if err != nil {
+ return fmt.Errorf("populate track artist: %w", err)
+ }
+ trackArtistIDs = append(trackArtistIDs, trackArtist.ID)
+ }
+ if err := populateTrackArtists(tx, &track, trackArtistIDs); err != nil {
+ return fmt.Errorf("populate track artists: %w", err)
+ }
+
+ if err := populateArtistAppearances(tx, album, trackArtistIDs); err != nil {
+ return fmt.Errorf("populate track artists: %w", err)
+ }
+
c.seenTracks[track.ID] = struct{}{}
c.seenTracksNew++
return nil
}
-func populateAlbum(tx *db.DB, album *db.Album, trags tags.Parser, modTime time.Time) error {
- albumName := tags.MustAlbum(trags)
+func populateAlbum(tx *db.DB, album *db.Album, trags tagcommon.Info, modTime time.Time) error {
+ albumName := tagcommon.MustAlbum(trags)
album.TagTitle = albumName
album.TagTitleUDec = decoded(albumName)
+ album.TagAlbumArtist = tagcommon.MustAlbumArtist(trags)
album.TagBrainzID = trags.AlbumBrainzID()
album.TagYear = trags.Year()
@@ -402,7 +404,6 @@ func populateAlbum(tx *db.DB, album *db.Album, trags tags.Parser, modTime time.T
if err := tx.Save(&album).Error; err != nil {
return fmt.Errorf("saving album: %w", err)
}
-
return nil
}
@@ -430,7 +431,7 @@ func populateAlbumBasics(tx *db.DB, musicDir string, parent, album *db.Album, di
return nil
}
-func populateTrack(tx *db.DB, album *db.Album, track *db.Track, trags tags.Parser, absPath string, size int) error {
+func populateTrack(tx *db.DB, album *db.Album, track *db.Track, trags tagcommon.Info, absPath string, size int) error {
basename := filepath.Base(absPath)
track.Filename = basename
track.FilenameUDec = decoded(basename)
@@ -510,7 +511,7 @@ func populateAlbumGenres(tx *db.DB, album *db.Album, genreIDs []int) error {
func populateAlbumArtists(tx *db.DB, album *db.Album, albumArtistIDs []int) error {
if err := tx.Where("album_id=?", album.ID).Delete(db.AlbumArtist{}).Error; err != nil {
- return fmt.Errorf("delete old album album artists: %w", err)
+ return fmt.Errorf("delete old album artists: %w", err)
}
if err := tx.InsertBulkLeftMany("album_artists", []string{"album_id", "artist_id"}, album.ID, albumArtistIDs); err != nil {
@@ -519,6 +520,24 @@ func populateAlbumArtists(tx *db.DB, album *db.Album, albumArtistIDs []int) erro
return nil
}
+func populateTrackArtists(tx *db.DB, track *db.Track, trackArtistIDs []int) error {
+ if err := tx.Where("track_id=?", track.ID).Delete(db.TrackArtist{}).Error; err != nil {
+ return fmt.Errorf("delete old track artists: %w", err)
+ }
+
+ if err := tx.InsertBulkLeftMany("track_artists", []string{"track_id", "artist_id"}, track.ID, trackArtistIDs); err != nil {
+ return fmt.Errorf("insert bulk track artists: %w", err)
+ }
+ return nil
+}
+
+func populateArtistAppearances(tx *db.DB, album *db.Album, artistIDs []int) error {
+ if err := tx.InsertBulkLeftMany("artist_appearances", []string{"album_id", "artist_id"}, album.ID, artistIDs); err != nil {
+ return fmt.Errorf("insert bulk track artists: %w", err)
+ }
+ return nil
+}
+
func (s *Scanner) cleanTracks(c *Context) error {
start := time.Now()
defer func() { log.Printf("finished clean tracks in %s, %d removed", durSince(start), c.TracksMissing()) }()
@@ -536,7 +555,7 @@ func (s *Scanner) cleanTracks(c *Context) error {
c.tracksMissing = append(c.tracksMissing, int64(a))
}
}
- return s.db.TransactionChunked(c.tracksMissing, func(tx *gorm.DB, chunk []int64) error {
+ return s.db.TransactionChunked(c.tracksMissing, func(tx *db.DB, chunk []int64) error {
return tx.Where(chunk).Delete(&db.Track{}).Error
})
}
@@ -558,7 +577,7 @@ func (s *Scanner) cleanAlbums(c *Context) error {
c.albumsMissing = append(c.albumsMissing, int64(a))
}
}
- return s.db.TransactionChunked(c.albumsMissing, func(tx *gorm.DB, chunk []int64) error {
+ return s.db.TransactionChunked(c.albumsMissing, func(tx *db.DB, chunk []int64) error {
return tx.Where(chunk).Delete(&db.Album{}).Error
})
}
@@ -567,15 +586,17 @@ func (s *Scanner) cleanArtists(c *Context) error {
start := time.Now()
defer func() { log.Printf("finished clean artists in %s, %d removed", durSince(start), c.ArtistsMissing()) }()
- sub := s.db.
- Select("artists.id").
- Model(&db.Artist{}).
- Joins("LEFT JOIN album_artists ON album_artists.artist_id=artists.id").
- Where("album_artists.artist_id IS NULL").
- SubQuery()
- q := s.db.
- Where("artists.id IN ?", sub).
- Delete(&db.Artist{})
+ // gorm doesn't seem to support subqueries without parens for UNION
+ q := s.db.Exec(`
+ DELETE FROM artists
+ WHERE id NOT IN (
+ SELECT artist_id FROM track_artists
+ UNION
+ SELECT artist_id FROM album_artists
+ UNION
+ SELECT artist_id FROM artist_appearances
+ )
+ `)
if err := q.Error; err != nil {
return err
}
@@ -583,7 +604,7 @@ func (s *Scanner) cleanArtists(c *Context) error {
return nil
}
-func (s *Scanner) cleanGenres(c *Context) error {
+func (s *Scanner) cleanGenres(c *Context) error { //nolint:unparam
start := time.Now()
defer func() { log.Printf("finished clean genres in %s, %d removed", durSince(start), c.GenresMissing()) }()
@@ -675,6 +696,7 @@ type Tag uint8
const (
Genre Tag = iota
+ Artist
AlbumArtist
)
@@ -683,7 +705,7 @@ type MultiValueSetting struct {
Delim string
}
-func parseMulti(parser tags.Parser, setting MultiValueSetting, getMulti func(tags.Parser) []string, get func(tags.Parser) string) []string {
+func parseMulti(parser tagcommon.Info, setting MultiValueSetting, getMulti func(tagcommon.Info) []string, get func(tagcommon.Info) string) []string {
var parts []string
switch setting.Mode {
case Multi:
@@ -698,3 +720,13 @@ func parseMulti(parser tags.Parser, setting MultiValueSetting, getMulti func(tag
}
return parts
}
+
+func musicDirRelative(musicDirs []string, absPath string) (musicDir, relPath string) {
+ for _, musicDir := range musicDirs {
+ if strings.HasPrefix(absPath, musicDir) {
+ relPath, _ = filepath.Rel(musicDir, absPath)
+ return musicDir, relPath
+ }
+ }
+ return
+}
diff --git a/scanner/scanner_fuzz_test.go b/scanner/scanner_fuzz_test.go
index 9911326..daf8e02 100644
--- a/scanner/scanner_fuzz_test.go
+++ b/scanner/scanner_fuzz_test.go
@@ -33,9 +33,8 @@ func FuzzScanner(f *testing.F) {
for i := 0; i < toAdd; i++ {
path := fmt.Sprintf("artist-%d/album-%d/track-%d.flac", i/6, i/3, i)
m.AddTrack(path)
- m.SetTags(path, func(tags *mockfs.Tags) error {
+ m.SetTags(path, func(tags *mockfs.TagInfo) {
fuzzStruct(i, data, seed, tags)
- return nil
})
}
diff --git a/scanner/scanner_test.go b/scanner/scanner_test.go
index eb0aae2..dfec6e5 100644
--- a/scanner/scanner_test.go
+++ b/scanner/scanner_test.go
@@ -1,4 +1,4 @@
-//nolint:goconst
+//nolint:goconst,errorlint
package scanner_test
import (
@@ -26,72 +26,68 @@ func TestMain(m *testing.M) {
func TestTableCounts(t *testing.T) {
t.Parallel()
- assert := assert.New(t)
m := mockfs.New(t)
m.AddItems()
m.ScanAndClean()
var tracks int
- assert.NoError(m.DB().Model(&db.Track{}).Count(&tracks).Error) // not all tracks
- assert.Equal(tracks, m.NumTracks())
+ assert.NoError(t, m.DB().Model(&db.Track{}).Count(&tracks).Error) // not all tracks
+ assert.Equal(t, tracks, m.NumTracks())
var albums int
- assert.NoError(m.DB().Model(&db.Album{}).Count(&albums).Error) // not all albums
- assert.Equal(albums, 13) // not all albums
+ assert.NoError(t, m.DB().Model(&db.Album{}).Count(&albums).Error) // not all albums
+ assert.Equal(t, albums, 13) // not all albums
var artists int
- assert.NoError(m.DB().Model(&db.Artist{}).Count(&artists).Error) // not all artists
- assert.Equal(artists, 3) // not all artists
+ assert.NoError(t, m.DB().Model(&db.Artist{}).Count(&artists).Error) // not all artists
+ assert.Equal(t, artists, 3) // not all artists
}
func TestWithExcludePattern(t *testing.T) {
t.Parallel()
- assert := assert.New(t)
m := mockfs.NewWithExcludePattern(t, "\\/artist-1\\/|track-0.flac$")
m.AddItems()
m.ScanAndClean()
var tracks int
- assert.NoError(m.DB().Model(&db.Track{}).Count(&tracks).Error) // not all tracks
- assert.Equal(tracks, 12)
+ assert.NoError(t, m.DB().Model(&db.Track{}).Count(&tracks).Error) // not all tracks
+ assert.Equal(t, tracks, 12)
var albums int
- assert.NoError(m.DB().Model(&db.Album{}).Count(&albums).Error) // not all albums
- assert.Equal(albums, 10) // not all albums
+ assert.NoError(t, m.DB().Model(&db.Album{}).Count(&albums).Error) // not all albums
+ assert.Equal(t, albums, 10) // not all albums
var artists int
- assert.NoError(m.DB().Model(&db.Artist{}).Count(&artists).Error) // not all artists
- assert.Equal(artists, 2) // not all artists
+ assert.NoError(t, m.DB().Model(&db.Artist{}).Count(&artists).Error) // not all artists
+ assert.Equal(t, artists, 2) // not all artists
}
func TestParentID(t *testing.T) {
t.Parallel()
- require := require.New(t)
m := mockfs.New(t)
m.AddItems()
m.ScanAndClean()
var nullParentAlbums []*db.Album
- require.NoError(m.DB().Where("parent_id IS NULL").Find(&nullParentAlbums).Error) // one parent_id=NULL which is root folder
- require.Equal(1, len(nullParentAlbums)) // one parent_id=NULL which is root folder
- require.Equal("", nullParentAlbums[0].LeftPath)
- require.Equal(".", nullParentAlbums[0].RightPath)
+ assert.NoError(t, m.DB().Where("parent_id IS NULL").Find(&nullParentAlbums).Error) // one parent_id=NULL which is root folder
+ assert.Equal(t, 1, len(nullParentAlbums)) // one parent_id=NULL which is root folder
+ assert.Equal(t, "", nullParentAlbums[0].LeftPath)
+ assert.Equal(t, ".", nullParentAlbums[0].RightPath)
- require.Equal(gorm.ErrRecordNotFound, m.DB().Where("id=parent_id").Find(&db.Album{}).Error) // no self-referencing albums
+ assert.Equal(t, gorm.ErrRecordNotFound, m.DB().Where("id=parent_id").Find(&db.Album{}).Error) // no self-referencing albums
var album db.Album
var parent db.Album
- require.NoError(m.DB().Find(&album, "left_path=? AND right_path=?", "artist-0/", "album-0").Error) // album has parent ID
- require.NoError(m.DB().Find(&parent, "right_path=?", "artist-0").Error) // album has parent ID
- require.Equal(parent.ID, album.ParentID) // album has parent ID
+ assert.NoError(t, m.DB().Find(&album, "left_path=? AND right_path=?", "artist-0/", "album-0").Error) // album has parent ID
+ assert.NoError(t, m.DB().Find(&parent, "right_path=?", "artist-0").Error) // album has parent ID
+ assert.Equal(t, parent.ID, album.ParentID) // album has parent ID
}
func TestUpdatedCover(t *testing.T) {
t.Parallel()
- assert := assert.New(t)
m := mockfs.New(t)
m.AddItems()
@@ -100,13 +96,12 @@ func TestUpdatedCover(t *testing.T) {
m.ScanAndClean()
var album db.Album
- assert.NoError(m.DB().Where("left_path=? AND right_path=?", "artist-0/", "album-0").Find(&album).Error) // album has cover
- assert.Equal(album.Cover, "cover.jpg") // album has cover
+ assert.NoError(t, m.DB().Where("left_path=? AND right_path=?", "artist-0/", "album-0").Find(&album).Error) // album has cover
+ assert.Equal(t, album.Cover, "cover.jpg") // album has cover
}
func TestCoverBeforeTracks(t *testing.T) {
t.Parallel()
- require := require.New(t)
m := mockfs.New(t)
m.AddCover("artist-2/album-2/cover.jpg")
@@ -115,132 +110,131 @@ func TestCoverBeforeTracks(t *testing.T) {
m.ScanAndClean()
var album db.Album
- require.NoError(m.DB().Where("left_path=? AND right_path=?", "artist-2/", "album-2").Find(&album).Error) // album has cover
- require.Equal("cover.jpg", album.Cover) // album has cover
+ assert.NoError(t, m.DB().Where("left_path=? AND right_path=?", "artist-2/", "album-2").Find(&album).Error) // album has cover
+ assert.Equal(t, "cover.jpg", album.Cover) // album has cover
var albumArtist db.Artist
- require.NoError(m.DB().Joins("JOIN album_artists ON album_artists.artist_id=artists.id").Where("album_artists.album_id=?", album.ID).Find(&albumArtist).Error) // album has cover
- require.Equal("artist-2", albumArtist.Name) // album artist
+ assert.NoError(t, m.DB().Joins("JOIN album_artists ON album_artists.artist_id=artists.id").Where("album_artists.album_id=?", album.ID).Find(&albumArtist).Error) // album has cover
+ assert.Equal(t, "artist-2", albumArtist.Name) // album artist
var tracks []*db.Track
- require.NoError(m.DB().Where("album_id=?", album.ID).Find(&tracks).Error) // album has tracks
- require.Equal(3, len(tracks)) // album has tracks
+ assert.NoError(t, m.DB().Where("album_id=?", album.ID).Find(&tracks).Error) // album has tracks
+ assert.Equal(t, 3, len(tracks)) // album has tracks
}
func TestUpdatedTags(t *testing.T) {
t.Parallel()
- require := require.New(t)
m := mockfs.New(t)
m.AddTrack("artist-10/album-10/track-10.flac")
- m.SetTags("artist-10/album-10/track-10.flac", func(tags *mockfs.Tags) error {
+ m.SetTags("artist-10/album-10/track-10.flac", func(tags *mockfs.TagInfo) {
tags.RawArtist = "artist"
tags.RawAlbumArtist = "album-artist"
tags.RawAlbum = "album"
tags.RawTitle = "title"
- return nil
})
m.ScanAndClean()
var track db.Track
- require.NoError(m.DB().Preload("Album").Where("filename=?", "track-10.flac").Find(&track).Error) // track has tags
- require.Equal("artist", track.TagTrackArtist) // track has tags
- require.Equal("album", track.Album.TagTitle) // track has tags
- require.Equal("title", track.TagTitle) // track has tags
+ assert.NoError(t, m.DB().Preload("Album").Where("filename=?", "track-10.flac").Find(&track).Error) // track has tags
+ assert.Equal(t, "artist", track.TagTrackArtist) // track has tags
+ assert.Equal(t, "album", track.Album.TagTitle) // track has tags
+ assert.Equal(t, "title", track.TagTitle) // track has tags
var trackArtistA db.Artist
- require.NoError(m.DB().Joins("JOIN album_artists ON album_artists.artist_id=artists.id").Where("album_artists.album_id=?", track.AlbumID).Limit(1).Find(&trackArtistA).Error) // updated has tags
- require.Equal("album-artist", trackArtistA.Name) // track has tags
+ assert.NoError(t, m.DB().Joins("JOIN album_artists ON album_artists.artist_id=artists.id").Where("album_artists.album_id=?", track.AlbumID).Limit(1).Find(&trackArtistA).Error) // updated has tags
+ assert.Equal(t, "album-artist", trackArtistA.Name) // track has tags
- m.SetTags("artist-10/album-10/track-10.flac", func(tags *mockfs.Tags) error {
+ m.SetTags("artist-10/album-10/track-10.flac", func(tags *mockfs.TagInfo) {
tags.RawArtist = "artist-upd"
tags.RawAlbumArtist = "album-artist-upd"
tags.RawAlbum = "album-upd"
tags.RawTitle = "title-upd"
- return nil
})
m.ScanAndClean()
var updated db.Track
- require.NoError(m.DB().Preload("Album").Where("filename=?", "track-10.flac").Find(&updated).Error) // updated has tags
- require.Equal(track.ID, updated.ID) // updated has tags
- require.Equal("artist-upd", updated.TagTrackArtist) // updated has tags
- require.Equal("album-upd", updated.Album.TagTitle) // updated has tags
- require.Equal("title-upd", updated.TagTitle) // updated has tags
+ assert.NoError(t, m.DB().Preload("Album").Where("filename=?", "track-10.flac").Find(&updated).Error) // updated has tags
+ assert.Equal(t, track.ID, updated.ID) // updated has tags
+ assert.Equal(t, "artist-upd", updated.TagTrackArtist) // updated has tags
+ assert.Equal(t, "album-upd", updated.Album.TagTitle) // updated has tags
+ assert.Equal(t, "title-upd", updated.TagTitle) // updated has tags
var trackArtistB db.Artist
- require.NoError(m.DB().Joins("JOIN album_artists ON album_artists.artist_id=artists.id").Where("album_artists.album_id=?", track.AlbumID).Limit(1).Find(&trackArtistB).Error) // updated has tags
- require.Equal("album-artist-upd", trackArtistB.Name) // updated has tags
+ assert.NoError(t, m.DB().Joins("JOIN album_artists ON album_artists.artist_id=artists.id").Where("album_artists.album_id=?", track.AlbumID).Limit(1).Find(&trackArtistB).Error) // updated has tags
+ assert.Equal(t, "album-artist-upd", trackArtistB.Name) // updated has tags
}
// https://github.com/sentriz/gonic/issues/225
func TestUpdatedAlbumGenre(t *testing.T) {
t.Parallel()
- require := require.New(t)
m := mockfs.New(t)
m.AddItems()
- m.SetTags("artist-0/album-0/track-0.flac", func(tags *mockfs.Tags) error {
+ m.SetTags("artist-0/album-0/track-0.flac", func(tags *mockfs.TagInfo) {
tags.RawGenre = "gen-a;gen-b"
- return nil
})
m.ScanAndClean()
var album db.Album
- require.NoError(m.DB().Preload("Genres").Where("left_path=? AND right_path=?", "artist-0/", "album-0").Find(&album).Error)
- require.Equal([]string{"gen-a", "gen-b"}, album.GenreStrings())
+ assert.NoError(t, m.DB().Preload("Genres").Where("left_path=? AND right_path=?", "artist-0/", "album-0").Find(&album).Error)
+ assert.Equal(t, []string{"gen-a", "gen-b"}, genreStrings(album))
- m.SetTags("artist-0/album-0/track-0.flac", func(tags *mockfs.Tags) error {
+ m.SetTags("artist-0/album-0/track-0.flac", func(tags *mockfs.TagInfo) {
tags.RawGenre = "gen-a-upd;gen-b-upd"
- return nil
})
m.ScanAndClean()
var updated db.Album
- require.NoError(m.DB().Preload("Genres").Where("left_path=? AND right_path=?", "artist-0/", "album-0").Find(&updated).Error)
- require.Equal([]string{"gen-a-upd", "gen-b-upd"}, updated.GenreStrings())
+ assert.NoError(t, m.DB().Preload("Genres").Where("left_path=? AND right_path=?", "artist-0/", "album-0").Find(&updated).Error)
+ assert.Equal(t, []string{"gen-a-upd", "gen-b-upd"}, genreStrings(updated))
+}
+
+func genreStrings(album db.Album) []string {
+ var strs []string
+ for _, genre := range album.Genres {
+ strs = append(strs, genre.Name)
+ }
+ return strs
}
func TestDeleteAlbum(t *testing.T) {
t.Parallel()
- assert := assert.New(t)
m := mockfs.New(t)
m.AddItems()
m.ScanAndClean()
- assert.NoError(m.DB().Where("left_path=? AND right_path=?", "artist-2/", "album-2").Find(&db.Album{}).Error) // album exists
+ assert.NoError(t, m.DB().Where("left_path=? AND right_path=?", "artist-2/", "album-2").Find(&db.Album{}).Error) // album exists
m.RemoveAll("artist-2/album-2")
m.ScanAndClean()
- assert.Equal(m.DB().Where("left_path=? AND right_path=?", "artist-2/", "album-2").Find(&db.Album{}).Error, gorm.ErrRecordNotFound) // album doesn't exist
+ assert.Equal(t, m.DB().Where("left_path=? AND right_path=?", "artist-2/", "album-2").Find(&db.Album{}).Error, gorm.ErrRecordNotFound) // album doesn't exist
}
func TestDeleteArtist(t *testing.T) {
t.Parallel()
- assert := assert.New(t)
m := mockfs.New(t)
m.AddItems()
m.ScanAndClean()
- assert.NoError(m.DB().Where("left_path=? AND right_path=?", "artist-2/", "album-2").Find(&db.Album{}).Error) // album exists
+ assert.NoError(t, m.DB().Where("left_path=? AND right_path=?", "artist-2/", "album-2").Find(&db.Album{}).Error) // album exists
m.RemoveAll("artist-2")
m.ScanAndClean()
- assert.Equal(m.DB().Where("left_path=? AND right_path=?", "artist-2/", "album-2").Find(&db.Album{}).Error, gorm.ErrRecordNotFound) // album doesn't exist
- assert.Equal(m.DB().Where("name=?", "artist-2").Find(&db.Artist{}).Error, gorm.ErrRecordNotFound) // artist doesn't exist
+ assert.Equal(t, m.DB().Where("left_path=? AND right_path=?", "artist-2/", "album-2").Find(&db.Album{}).Error, gorm.ErrRecordNotFound) // album doesn't exist
+ assert.Equal(t, m.DB().Where("name=?", "artist-2").Find(&db.Artist{}).Error, gorm.ErrRecordNotFound) // artist doesn't exist
}
func TestGenres(t *testing.T) {
t.Parallel()
- assert := assert.New(t)
m := mockfs.New(t)
albumGenre := func(artist, album, genre string) error {
@@ -252,10 +246,10 @@ func TestGenres(t *testing.T) {
Error
}
isAlbumGenre := func(artist, album, genreName string) {
- assert.NoError(albumGenre(artist, album, genreName))
+ assert.NoError(t, albumGenre(artist, album, genreName))
}
isAlbumGenreMissing := func(artist, album, genreName string) {
- assert.Equal(albumGenre(artist, album, genreName), gorm.ErrRecordNotFound)
+ assert.Equal(t, albumGenre(artist, album, genreName), gorm.ErrRecordNotFound)
}
trackGenre := func(artist, album, filename, genreName string) error {
@@ -268,27 +262,27 @@ func TestGenres(t *testing.T) {
Error
}
isTrackGenre := func(artist, album, filename, genreName string) {
- assert.NoError(trackGenre(artist, album, filename, genreName))
+ assert.NoError(t, trackGenre(artist, album, filename, genreName))
}
isTrackGenreMissing := func(artist, album, filename, genreName string) {
- assert.Equal(trackGenre(artist, album, filename, genreName), gorm.ErrRecordNotFound)
+ assert.Equal(t, trackGenre(artist, album, filename, genreName), gorm.ErrRecordNotFound)
}
genre := func(genre string) error {
return m.DB().Where("name=?", genre).Find(&db.Genre{}).Error
}
isGenre := func(genreName string) {
- assert.NoError(genre(genreName))
+ assert.NoError(t, genre(genreName))
}
isGenreMissing := func(genreName string) {
- assert.Equal(genre(genreName), gorm.ErrRecordNotFound)
+ assert.Equal(t, genre(genreName), gorm.ErrRecordNotFound)
}
m.AddItems()
- m.SetTags("artist-0/album-0/track-0.flac", func(tags *mockfs.Tags) error { tags.RawGenre = "genre-a;genre-b"; return nil })
- m.SetTags("artist-0/album-0/track-1.flac", func(tags *mockfs.Tags) error { tags.RawGenre = "genre-c;genre-d"; return nil })
- m.SetTags("artist-1/album-2/track-0.flac", func(tags *mockfs.Tags) error { tags.RawGenre = "genre-e;genre-f"; return nil })
- m.SetTags("artist-1/album-2/track-1.flac", func(tags *mockfs.Tags) error { tags.RawGenre = "genre-g;genre-h"; return nil })
+ m.SetTags("artist-0/album-0/track-0.flac", func(tags *mockfs.TagInfo) { tags.RawGenre = "genre-a;genre-b" })
+ m.SetTags("artist-0/album-0/track-1.flac", func(tags *mockfs.TagInfo) { tags.RawGenre = "genre-c;genre-d" })
+ m.SetTags("artist-1/album-2/track-0.flac", func(tags *mockfs.TagInfo) { tags.RawGenre = "genre-e;genre-f" })
+ m.SetTags("artist-1/album-2/track-1.flac", func(tags *mockfs.TagInfo) { tags.RawGenre = "genre-g;genre-h" })
m.ScanAndClean()
isGenre("genre-a") // genre exists
@@ -308,7 +302,7 @@ func TestGenres(t *testing.T) {
isAlbumGenre("artist-0/", "album-0", "genre-a") // album genre exists
isAlbumGenre("artist-0/", "album-0", "genre-b") // album genre exists
- m.SetTags("artist-0/album-0/track-0.flac", func(tags *mockfs.Tags) error { tags.RawGenre = "genre-aa;genre-bb"; return nil })
+ m.SetTags("artist-0/album-0/track-0.flac", func(tags *mockfs.TagInfo) { tags.RawGenre = "genre-aa;genre-bb" })
m.ScanAndClean()
isTrackGenre("artist-0/", "album-0", "track-0.flac", "genre-aa") // updated track genre exists
@@ -325,7 +319,6 @@ func TestGenres(t *testing.T) {
func TestMultiFolders(t *testing.T) {
t.Parallel()
- require := require.New(t)
m := mockfs.NewWithDirs(t, []string{"m-1", "m-2", "m-3"})
m.AddItemsPrefix("m-1")
@@ -334,13 +327,13 @@ func TestMultiFolders(t *testing.T) {
m.ScanAndClean()
var rootDirs []*db.Album
- require.NoError(m.DB().Where("parent_id IS NULL").Find(&rootDirs).Error)
- require.Equal(3, len(rootDirs))
+ assert.NoError(t, m.DB().Where("parent_id IS NULL").Find(&rootDirs).Error)
+ assert.Equal(t, 3, len(rootDirs))
for i, r := range rootDirs {
- require.Equal(filepath.Join(m.TmpDir(), fmt.Sprintf("m-%d", i+1)), r.RootDir)
- require.Equal(0, r.ParentID)
- require.Equal("", r.LeftPath)
- require.Equal(".", r.RightPath)
+ assert.Equal(t, filepath.Join(m.TmpDir(), fmt.Sprintf("m-%d", i+1)), r.RootDir)
+ assert.Equal(t, 0, r.ParentID)
+ assert.Equal(t, "", r.LeftPath)
+ assert.Equal(t, ".", r.RightPath)
}
m.AddCover("m-3/artist-0/album-0/cover.jpg")
@@ -348,7 +341,7 @@ func TestMultiFolders(t *testing.T) {
m.LogItems()
checkCover := func(root string, q string) {
- require.NoError(m.DB().Where(q, filepath.Join(m.TmpDir(), root)).Find(&db.Album{}).Error)
+ assert.NoError(t, m.DB().Where(q, filepath.Join(m.TmpDir(), root)).Find(&db.Album{}).Error)
}
checkCover("m-1", "root_dir=? AND cover IS NULL") // mf 1 no cover
@@ -358,7 +351,6 @@ func TestMultiFolders(t *testing.T) {
func TestNewAlbumForExistingArtist(t *testing.T) {
t.Parallel()
- require := require.New(t)
m := mockfs.New(t)
m.AddItems()
@@ -368,80 +360,76 @@ func TestNewAlbumForExistingArtist(t *testing.T) {
m.LogArtists()
var artist db.Artist
- require.NoError(m.DB().Where("name=?", "artist-2").Find(&artist).Error) // find orig artist
- require.Greater(artist.ID, 0)
+ assert.NoError(t, m.DB().Where("name=?", "artist-2").Find(&artist).Error) // find orig artist
+ assert.Greater(t, artist.ID, 0)
for tr := 0; tr < 3; tr++ {
m.AddTrack(fmt.Sprintf("artist-2/new-album/track-%d.mp3", tr))
- m.SetTags(fmt.Sprintf("artist-2/new-album/track-%d.mp3", tr), func(tags *mockfs.Tags) error {
+ m.SetTags(fmt.Sprintf("artist-2/new-album/track-%d.mp3", tr), func(tags *mockfs.TagInfo) {
tags.RawArtist = "artist-2"
tags.RawAlbumArtist = "artist-2"
tags.RawAlbum = "new-album"
tags.RawTitle = fmt.Sprintf("title-%d", tr)
- return nil
})
}
var updated db.Artist
- require.NoError(m.DB().Where("name=?", "artist-2").Find(&updated).Error) // find updated artist
- require.Equal(updated.ID, artist.ID) // find updated artist
+ assert.NoError(t, m.DB().Where("name=?", "artist-2").Find(&updated).Error) // find updated artist
+ assert.Equal(t, updated.ID, artist.ID) // find updated artist
var all []*db.Artist
- require.NoError(m.DB().Find(&all).Error) // still only 3?
- require.Equal(3, len(all)) // still only 3?
+ assert.NoError(t, m.DB().Find(&all).Error) // still only 3?
+ assert.Equal(t, 3, len(all)) // still only 3?
}
func TestMultiFolderWithSharedArtist(t *testing.T) {
t.Parallel()
- require := require.New(t)
m := mockfs.NewWithDirs(t, []string{"m-0", "m-1"})
const artistName = "artist-a"
m.AddTrack(fmt.Sprintf("m-0/%s/album-a/track-1.flac", artistName))
- m.SetTags(fmt.Sprintf("m-0/%s/album-a/track-1.flac", artistName), func(tags *mockfs.Tags) error {
+ m.SetTags(fmt.Sprintf("m-0/%s/album-a/track-1.flac", artistName), func(tags *mockfs.TagInfo) {
tags.RawArtist = artistName
tags.RawAlbumArtist = artistName
tags.RawAlbum = "album-a"
tags.RawTitle = "track-1"
- return nil
})
m.ScanAndClean()
m.AddTrack(fmt.Sprintf("m-1/%s/album-a/track-1.flac", artistName))
- m.SetTags(fmt.Sprintf("m-1/%s/album-a/track-1.flac", artistName), func(tags *mockfs.Tags) error {
+ m.SetTags(fmt.Sprintf("m-1/%s/album-a/track-1.flac", artistName), func(tags *mockfs.TagInfo) {
tags.RawArtist = artistName
tags.RawAlbumArtist = artistName
tags.RawAlbum = "album-a"
tags.RawTitle = "track-1"
- return nil
})
m.ScanAndClean()
var artist db.Artist
- require.NoError(m.DB().Where("name=?", artistName).First(&artist).Error)
- require.Equal(artistName, artist.Name)
+ assert.NoError(t, m.DB().Where("name=?", artistName).First(&artist).Error)
+ assert.Equal(t, artistName, artist.Name)
var artistAlbums []*db.Album
- require.NoError(m.DB().
+ assert.NoError(t, m.DB().
Select("*, count(sub.id) child_count, sum(sub.length) duration").
Joins("JOIN album_artists ON album_artists.album_id=albums.id").
Joins("LEFT JOIN tracks sub ON albums.id=sub.album_id").
Where("album_artists.artist_id=?", artist.ID).
Group("albums.id").
Find(&artistAlbums).Error)
- require.Equal(2, len(artistAlbums))
+
+ assert.Equal(t, 2, len(artistAlbums))
for _, album := range artistAlbums {
- require.Greater(album.TagYear, 0)
- require.Greater(album.ChildCount, 0)
- require.Greater(album.Duration, 0)
+ assert.Greater(t, album.TagYear, 0)
+ assert.Greater(t, album.ChildCount, 0)
+ assert.Greater(t, album.Duration, 0)
}
}
func TestSymlinkedAlbum(t *testing.T) {
t.Parallel()
- require := require.New(t)
m := mockfs.NewWithDirs(t, []string{"scan"})
m.AddItemsPrefixWithCovers("temp")
@@ -455,31 +443,29 @@ func TestSymlinkedAlbum(t *testing.T) {
m.LogAlbums()
var track db.Track
- require.NoError(m.DB().Preload("Album.Parent").Find(&track).Error) // track exists
- require.NotNil(track.Album) // track has album
- require.NotZero(track.Album.Cover) // album has cover
- require.Equal("artist-sym", track.Album.Parent.RightPath) // artist is sym
+ require.NoError(t, m.DB().Preload("Album.Parent").Find(&track).Error) // track exists
+ require.NotNil(t, track.Album) // track has album
+ require.NotZero(t, track.Album.Cover) // album has cover
+ require.Equal(t, "artist-sym", track.Album.Parent.RightPath) // artist is sym
info, err := os.Stat(track.AbsPath())
- require.NoError(err) // track resolves
- require.False(info.IsDir()) // track resolves
- require.NotZero(info.ModTime()) // track resolves
+ require.NoError(t, err) // track resolves
+ require.False(t, info.IsDir()) // track resolves
+ require.NotZero(t, info.ModTime()) // track resolves
}
func TestSymlinkedSubdiscs(t *testing.T) {
t.Parallel()
- require := require.New(t)
m := mockfs.NewWithDirs(t, []string{"scan"})
addItem := func(prefix, artist, album, disc, track string) {
p := fmt.Sprintf("%s/%s/%s/%s/%s", prefix, artist, album, disc, track)
m.AddTrack(p)
- m.SetTags(p, func(tags *mockfs.Tags) error {
+ m.SetTags(p, func(tags *mockfs.TagInfo) {
tags.RawArtist = artist
tags.RawAlbumArtist = artist
tags.RawAlbum = album
tags.RawTitle = track
- return nil
})
}
@@ -499,51 +485,66 @@ func TestSymlinkedSubdiscs(t *testing.T) {
m.LogAlbums()
var track db.Track
- require.NoError(m.DB().Preload("Album.Parent").Find(&track).Error) // track exists
- require.NotNil(track.Album) // track has album
- require.Equal("album-sym", track.Album.Parent.RightPath) // artist is sym
+ assert.NoError(t, m.DB().Preload("Album.Parent").Find(&track).Error) // track exists
+ assert.NotNil(t, track.Album) // track has album
+ assert.Equal(t, "album-sym", track.Album.Parent.RightPath) // artist is sym
info, err := os.Stat(track.AbsPath())
- require.NoError(err) // track resolves
- require.False(info.IsDir()) // track resolves
- require.NotZero(info.ModTime()) // track resolves
+ assert.NoError(t, err) // track resolves
+ assert.False(t, info.IsDir()) // track resolves
+ assert.NotZero(t, info.ModTime()) // track resolves
+}
+
+func TestSymlinkEscapesMusicDirs(t *testing.T) {
+ t.Parallel()
+ m := mockfs.NewWithDirs(t, []string{"scandir"})
+
+ require.NoError(t, os.MkdirAll(filepath.Join(m.TmpDir(), "otherdir", "artist", "album-test"), os.ModePerm))
+ require.NoError(t, os.Symlink(
+ filepath.Join(m.TmpDir(), "otherdir", "artist"),
+ filepath.Join(m.TmpDir(), "scandir", "artist"),
+ ))
+
+ m.ScanAndClean()
+
+ var albums []*db.Album
+ require.NoError(t, m.DB().Find(&albums).Error)
+ require.Len(t, albums, 3)
}
func TestTagErrors(t *testing.T) {
t.Parallel()
- require := require.New(t)
m := mockfs.New(t)
m.AddItemsWithCovers()
- m.SetTags("artist-1/album-0/track-0.flac", func(tags *mockfs.Tags) error {
- return scanner.ErrReadingTags
+ m.SetTags("artist-1/album-0/track-0.flac", func(tags *mockfs.TagInfo) {
+ tags.Error = scanner.ErrReadingTags
})
- m.SetTags("artist-1/album-1/track-0.flac", func(tags *mockfs.Tags) error {
- return scanner.ErrReadingTags
+ m.SetTags("artist-1/album-1/track-0.flac", func(tags *mockfs.TagInfo) {
+ tags.Error = scanner.ErrReadingTags
})
ctx, err := m.ScanAndCleanErr()
errs, ok := err.(interface{ Unwrap() []error })
- require.True(ok)
+ assert.True(t, ok)
- require.ErrorAs(err, &errs)
- require.Equal(2, len(errs.Unwrap())) // we have 2 dir errors
- require.Equal(m.NumTracks()-(3*2), ctx.SeenTracks()) // we saw all tracks bar 2 album contents
- require.Equal(m.NumTracks()-(3*2), ctx.SeenTracksNew()) // we have all tracks bar 2 album contents
+ assert.ErrorAs(t, err, &errs)
+ 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), ctx.SeenTracksNew()) // we have all tracks bar 2 album contents
ctx, err = m.ScanAndCleanErr()
errs, ok = err.(interface{ Unwrap() []error })
- require.True(ok)
+ assert.True(t, ok)
- require.Equal(2, len(errs.Unwrap())) // we have 2 dir errors
- require.Equal(m.NumTracks()-(3*2), ctx.SeenTracks()) // we saw all tracks bar 2 album contents
- require.Equal(0, ctx.SeenTracksNew()) // we have no new tracks
+ 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, 0, ctx.SeenTracksNew()) // we have no new tracks
}
// https://github.com/sentriz/gonic/issues/185#issuecomment-1050092128
func TestCompilationAlbumWithoutAlbumArtist(t *testing.T) {
t.Parallel()
- require := require.New(t)
m := mockfs.New(t)
const pathArtist = "various-artists"
@@ -554,62 +555,59 @@ func TestCompilationAlbumWithoutAlbumArtist(t *testing.T) {
for i := 0; i < toAdd; i++ {
p := fmt.Sprintf("%s/%s/track-%d.flac", pathArtist, pathAlbum, i)
m.AddTrack(p)
- m.SetTags(p, func(tags *mockfs.Tags) error {
+ m.SetTags(p, func(tags *mockfs.TagInfo) {
// don't set an album artist
tags.RawTitle = fmt.Sprintf("track %d", i)
tags.RawArtist = fmt.Sprintf("artist %d", i)
tags.RawAlbum = pathArtist
- return nil
})
}
m.ScanAndClean()
var trackCount int
- require.NoError(m.DB().Model(&db.Track{}).Count(&trackCount).Error)
- require.Equal(5, trackCount)
+ assert.NoError(t, m.DB().Model(&db.Track{}).Count(&trackCount).Error)
+ assert.Equal(t, 5, trackCount)
var artists []*db.Artist
- require.NoError(m.DB().Find(&artists).Error)
- require.Equal(1, len(artists)) // we only have one album artist
- require.Equal("artist 0", artists[0].Name) // it came from the first track's fallback to artist tag
+ assert.NoError(t, m.DB().Joins("JOIN album_artists ON album_artists.artist_id=artists.id").Group("artists.id").Find(&artists).Error)
+ assert.Equal(t, 1, len(artists)) // we only have one album artist
+ assert.Equal(t, "artist 0", artists[0].Name) // it came from the first track's fallback to artist tag
var artistAlbums []*db.Album
- require.NoError(m.DB().Joins("JOIN album_artists ON album_artists.album_id=albums.id").Where("album_artists.artist_id=?", artists[0].ID).Find(&artistAlbums).Error)
- require.Equal(1, len(artistAlbums)) // the artist has one album
- require.Equal(pathAlbum, artistAlbums[0].RightPath)
- require.Equal(pathArtist+"/", artistAlbums[0].LeftPath)
+ assert.NoError(t, m.DB().Joins("JOIN album_artists ON album_artists.album_id=albums.id").Where("album_artists.artist_id=?", artists[0].ID).Find(&artistAlbums).Error)
+ assert.Equal(t, 1, len(artistAlbums)) // the artist has one album
+ assert.Equal(t, pathAlbum, artistAlbums[0].RightPath)
+ assert.Equal(t, pathArtist+"/", artistAlbums[0].LeftPath)
}
func TestIncrementalScanNoChangeNoUpdatedAt(t *testing.T) {
t.Parallel()
- require := require.New(t)
m := mockfs.New(t)
m.AddItems()
m.ScanAndClean()
var albumA db.Album
- require.NoError(m.DB().Joins("JOIN album_artists ON album_artists.album_id=albums.id").Order("updated_at DESC").Find(&albumA).Error)
+ assert.NoError(t, m.DB().Joins("JOIN album_artists ON album_artists.album_id=albums.id").Order("updated_at DESC").Find(&albumA).Error)
m.ScanAndClean()
var albumB db.Album
- require.NoError(m.DB().Joins("JOIN album_artists ON album_artists.album_id=albums.id").Order("updated_at DESC").Find(&albumB).Error)
+ assert.NoError(t, m.DB().Joins("JOIN album_artists ON album_artists.album_id=albums.id").Order("updated_at DESC").Find(&albumB).Error)
- require.Equal(albumB.UpdatedAt, albumA.UpdatedAt)
+ assert.Equal(t, albumB.UpdatedAt, albumA.UpdatedAt)
}
// https://github.com/sentriz/gonic/issues/230
func TestAlbumAndArtistSameNameWeirdness(t *testing.T) {
t.Parallel()
- assert := assert.New(t)
m := mockfs.New(t)
const name = "same"
add := func(path string, a ...interface{}) {
m.AddTrack(fmt.Sprintf(path, a...))
- m.SetTags(fmt.Sprintf(path, a...), func(tags *mockfs.Tags) error { return nil })
+ m.SetTags(fmt.Sprintf(path, a...), func(tags *mockfs.TagInfo) {})
}
add("an-artist/%s/track-1.flac", name)
@@ -620,20 +618,19 @@ func TestAlbumAndArtistSameNameWeirdness(t *testing.T) {
m.ScanAndClean()
var albums []*db.Album
- assert.NoError(m.DB().Find(&albums).Error)
- assert.Equal(len(albums), 5) // root, 2 artists, 2 albums
+ assert.NoError(t, m.DB().Find(&albums).Error)
+ assert.Equal(t, len(albums), 5) // root, 2 artists, 2 albums
}
func TestNoOrphanedGenres(t *testing.T) {
t.Parallel()
- require := assert.New(t)
m := mockfs.New(t)
m.AddItems()
- m.SetTags("artist-0/album-0/track-0.flac", func(tags *mockfs.Tags) error { tags.RawGenre = "genre-a;genre-b"; return nil })
- m.SetTags("artist-0/album-0/track-1.flac", func(tags *mockfs.Tags) error { tags.RawGenre = "genre-c;genre-d"; return nil })
- m.SetTags("artist-1/album-2/track-0.flac", func(tags *mockfs.Tags) error { tags.RawGenre = "genre-e;genre-f"; return nil })
- m.SetTags("artist-1/album-2/track-1.flac", func(tags *mockfs.Tags) error { tags.RawGenre = "genre-g;genre-h"; return nil })
+ m.SetTags("artist-0/album-0/track-0.flac", func(tags *mockfs.TagInfo) { tags.RawGenre = "genre-a;genre-b" })
+ m.SetTags("artist-0/album-0/track-1.flac", func(tags *mockfs.TagInfo) { tags.RawGenre = "genre-c;genre-d" })
+ m.SetTags("artist-1/album-2/track-0.flac", func(tags *mockfs.TagInfo) { tags.RawGenre = "genre-e;genre-f" })
+ m.SetTags("artist-1/album-2/track-1.flac", func(tags *mockfs.TagInfo) { tags.RawGenre = "genre-g;genre-h" })
m.ScanAndClean()
m.RemoveAll("artist-0")
@@ -642,46 +639,42 @@ func TestNoOrphanedGenres(t *testing.T) {
m.ScanAndClean()
var genreCount int
- require.NoError(m.DB().Model(&db.Genre{}).Count(&genreCount).Error)
- require.Equal(0, genreCount)
+ assert.NoError(t, m.DB().Model(&db.Genre{}).Count(&genreCount).Error)
+ assert.Equal(t, 0, genreCount)
}
func TestMultiArtistSupport(t *testing.T) {
t.Parallel()
- require := assert.New(t)
m := mockfs.New(t)
m.AddItemsGlob("artist-0/album-[012]/track-0.*")
- m.SetTags("artist-0/album-0/track-0.flac", func(tags *mockfs.Tags) error {
+ m.SetTags("artist-0/album-0/track-0.flac", func(tags *mockfs.TagInfo) {
tags.RawAlbum = "Mutator"
tags.RawAlbumArtists = []string{"Alan Vega", "Liz Lamere"}
- return nil
})
- m.SetTags("artist-0/album-1/track-0.flac", func(tags *mockfs.Tags) error {
+ m.SetTags("artist-0/album-1/track-0.flac", func(tags *mockfs.TagInfo) {
tags.RawAlbum = "Dead Man"
tags.RawAlbumArtists = []string{"Alan Vega", "Mercury Rev"}
- return nil
})
- m.SetTags("artist-0/album-2/track-0.flac", func(tags *mockfs.Tags) error {
+ m.SetTags("artist-0/album-2/track-0.flac", func(tags *mockfs.TagInfo) {
tags.RawAlbum = "Yerself Is Steam"
tags.RawAlbumArtist = "Mercury Rev"
- return nil
})
m.ScanAndClean()
var artists []*db.Artist
- require.NoError(m.DB().Find(&artists).Error)
- require.Len(artists, 3) // alan, liz, mercury
+ assert.NoError(t, m.DB().Joins("JOIN album_artists ON album_artists.artist_id=artists.id").Group("artists.id").Find(&artists).Error)
+ assert.Len(t, artists, 3) // alan, liz, mercury
var albumArtists []*db.AlbumArtist
- require.NoError(m.DB().Find(&albumArtists).Error)
- require.Len(albumArtists, 5)
+ assert.NoError(t, m.DB().Find(&albumArtists).Error)
+ assert.Len(t, albumArtists, 5)
type row struct{ Artist, Albums string }
state := func() []row {
var table []row
- require.NoError(m.DB().
+ assert.NoError(t, m.DB().
Select("artists.name artist, group_concat(albums.tag_title, ';') albums").
Model(db.Artist{}).
Joins("JOIN album_artists ON album_artists.artist_id=artists.id").
@@ -690,94 +683,107 @@ func TestMultiArtistSupport(t *testing.T) {
Group("artists.id").
Scan(&table).
Error)
+
return table
}
- require.Equal(
+ assert.Equal(t,
[]row{
{"Alan Vega", "Mutator;Dead Man"},
{"Liz Lamere", "Mutator"},
{"Mercury Rev", "Dead Man;Yerself Is Steam"},
},
- state(),
- )
+ state())
m.RemoveAll("artist-0/album-2")
- m.SetTags("artist-0/album-1/track-0.flac", func(tags *mockfs.Tags) error {
+ m.SetTags("artist-0/album-1/track-0.flac", func(tags *mockfs.TagInfo) {
tags.RawAlbum = "Dead Man"
tags.RawAlbumArtists = []string{"Alan Vega"}
- return nil
})
m.ScanAndClean()
- require.NoError(m.DB().Find(&artists).Error)
- require.Len(artists, 2) // alan, liz
+ assert.NoError(t, m.DB().Joins("JOIN album_artists ON album_artists.artist_id=artists.id").Group("artists.id").Find(&artists).Error)
+ assert.Len(t, artists, 2) // alan, liz
- require.NoError(m.DB().Find(&albumArtists).Error)
- require.Len(albumArtists, 3)
+ assert.NoError(t, m.DB().Find(&albumArtists).Error)
+ assert.Len(t, albumArtists, 3)
- require.Equal(
+ assert.Equal(t,
[]row{
{"Alan Vega", "Mutator;Dead Man"},
{"Liz Lamere", "Mutator"},
},
- state(),
- )
-
+ state())
}
func TestMultiArtistPreload(t *testing.T) {
t.Parallel()
- require := assert.New(t)
m := mockfs.New(t)
m.AddItemsGlob("artist-0/album-[012]/track-0.*")
- m.SetTags("artist-0/album-0/track-0.flac", func(tags *mockfs.Tags) error {
+ m.SetTags("artist-0/album-0/track-0.flac", func(tags *mockfs.TagInfo) {
tags.RawAlbum = "Mutator"
tags.RawAlbumArtists = []string{"Alan Vega", "Liz Lamere"}
- return nil
})
- m.SetTags("artist-0/album-1/track-0.flac", func(tags *mockfs.Tags) error {
+ m.SetTags("artist-0/album-1/track-0.flac", func(tags *mockfs.TagInfo) {
tags.RawAlbum = "Dead Man"
tags.RawAlbumArtists = []string{"Alan Vega", "Mercury Rev"}
- return nil
})
- m.SetTags("artist-0/album-2/track-0.flac", func(tags *mockfs.Tags) error {
+ m.SetTags("artist-0/album-2/track-0.flac", func(tags *mockfs.TagInfo) {
tags.RawAlbum = "Yerself Is Steam"
tags.RawAlbumArtist = "Mercury Rev"
- return nil
})
m.ScanAndClean()
var albums []*db.Album
- require.NoError(m.DB().Preload("Artists").Find(&albums).Error)
- require.GreaterOrEqual(len(albums), 3)
+ assert.NoError(t, m.DB().Preload("Artists").Find(&albums).Error)
+ assert.GreaterOrEqual(t, len(albums), 3)
for _, album := range albums {
switch album.TagTitle {
case "Mutator":
- require.Len(album.Artists, 2)
+ assert.Len(t, album.Artists, 2)
case "Dead Man":
- require.Len(album.Artists, 2)
+ assert.Len(t, album.Artists, 2)
case "Yerself Is Steam":
- require.Len(album.Artists, 1)
+ assert.Len(t, album.Artists, 1)
}
}
var artists []*db.Artist
- require.NoError(m.DB().Preload("Albums").Find(&artists).Error)
- require.Equal(3, len(artists))
+ assert.NoError(t, m.DB().Preload("Albums").Joins("JOIN album_artists ON album_artists.artist_id=artists.id").Group("artists.id").Find(&artists).Error)
+ assert.Equal(t, 3, len(artists))
for _, artist := range artists {
switch artist.Name {
case "Alan Vega":
- require.Len(artist.Albums, 2)
+ assert.Len(t, artist.Albums, 2)
case "Mercury Rev":
- require.Len(artist.Albums, 2)
+ assert.Len(t, artist.Albums, 2)
case "Liz Lamere":
- require.Len(artist.Albums, 1)
+ assert.Len(t, artist.Albums, 1)
}
}
}
+
+// https://github.com/sentriz/gonic/issues/402
+func TestRootNoClobberOnError(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.Error = fmt.Errorf("no") }) // give a track an error
+ m.AddCover("artist-0/album-0/Artwork/cover.png") // and add an extra cover dir
+
+ _, err := m.ScanAndCleanErr()
+ require.Error(t, err)
+
+ var roots []*db.Album
+ require.NoError(t, m.DB().Find(&roots, "parent_id IS NULL").Error)
+ require.Len(t, roots, 1)
+ require.Equal(t, ".", roots[0].RightPath)
+ require.Equal(t, 0, roots[0].ParentID)
+}
diff --git a/scanner/tags/tags.go b/scanner/tags/tags.go
deleted file mode 100644
index bfd0b3a..0000000
--- a/scanner/tags/tags.go
+++ /dev/null
@@ -1,152 +0,0 @@
-package tags
-
-import (
- "strconv"
- "strings"
-
- "github.com/sentriz/audiotags"
-)
-
-type TagReader struct{}
-
-func (*TagReader) Read(abspath string) (Parser, error) {
- raw, props, err := audiotags.Read(abspath)
- return &Tagger{raw, props}, err
-}
-
-type Tagger struct {
- raw map[string][]string
- props *audiotags.AudioProperties
-}
-
-// https://picard-docs.musicbrainz.org/downloads/MusicBrainz_Picard_Tag_Map.html
-
-func (t *Tagger) Title() string { return first(find(t.raw, "title")) }
-func (t *Tagger) BrainzID() string { return first(find(t.raw, "musicbrainz_trackid")) } // musicbrainz recording ID
-func (t *Tagger) Artist() string { return first(find(t.raw, "artist")) }
-func (t *Tagger) Album() string { return first(find(t.raw, "album")) }
-func (t *Tagger) AlbumArtist() string { return first(find(t.raw, "albumartist", "album artist")) }
-func (t *Tagger) AlbumArtists() []string { return find(t.raw, "albumartists", "album_artists") }
-func (t *Tagger) AlbumBrainzID() string { return first(find(t.raw, "musicbrainz_albumid")) } // musicbrainz release ID
-func (t *Tagger) Genre() string { return first(find(t.raw, "genre")) }
-func (t *Tagger) Genres() []string { return find(t.raw, "genres") }
-
-func (t *Tagger) TrackNumber() int {
- return intSep("/" /* eg. 5/12 */, first(find(t.raw, "tracknumber")))
-}
-func (t *Tagger) DiscNumber() int {
- return intSep("/" /* eg. 1/2 */, first(find(t.raw, "discnumber")))
-}
-func (t *Tagger) Year() int {
- return intSep("-" /* 2023-12-01 */, first(find(t.raw, "originaldate", "date", "year")))
-}
-
-func (t *Tagger) Length() int { return t.props.Length }
-func (t *Tagger) Bitrate() int { return t.props.Bitrate }
-
-type Reader interface {
- Read(abspath string) (Parser, error)
-}
-
-type Parser interface {
- Title() string
- BrainzID() string
- Artist() string
- Album() string
- AlbumArtist() string
- AlbumArtists() []string
- AlbumBrainzID() string
- Genre() string
- Genres() []string
- TrackNumber() int
- DiscNumber() int
- Length() int
- Bitrate() int
- Year() int
-}
-
-func fallback(or string, strs ...string) string {
- for _, str := range strs {
- if str != "" {
- return str
- }
- }
- return or
-}
-
-func first[T comparable](is []T) T {
- var z T
- for _, i := range is {
- if i != z {
- return i
- }
- }
- return z
-}
-
-func find(m map[string][]string, keys ...string) []string {
- for _, k := range keys {
- if r := filterStr(m[k]); len(r) > 0 {
- return r
- }
- }
- return nil
-}
-
-func filterStr(ss []string) []string {
- var r []string
- for _, s := range ss {
- if strings.TrimSpace(s) != "" {
- r = append(r, s)
- }
- }
- return r
-}
-
-func intSep(sep, in string) int {
- start, _, _ := strings.Cut(in, sep)
- out, _ := strconv.Atoi(start)
- return out
-}
-
-func MustAlbum(p Parser) string {
- if r := p.Album(); r != "" {
- return r
- }
- return "Unknown Album"
-}
-
-func MustArtist(p Parser) string {
- if r := p.Artist(); r != "" {
- return r
- }
- return "Unknown Artist"
-}
-
-func MustAlbumArtist(p Parser) string {
- if r := p.AlbumArtist(); r != "" {
- return r
- }
- return MustArtist(p)
-}
-
-func MustAlbumArtists(p Parser) []string {
- if r := p.AlbumArtists(); len(r) > 0 {
- return r
- }
- return []string{MustAlbumArtist(p)}
-}
-
-func MustGenre(p Parser) string {
- if r := p.Genre(); r != "" {
- return r
- }
- return "Unknown Genre"
-}
-
-func MustGenres(p Parser) []string {
- if r := p.Genres(); len(r) > 0 {
- return r
- }
- return []string{MustGenre(p)}
-}
diff --git a/scanner/testdata/fuzz/FuzzScanner/22023bdee30f39396809ddfa903114a127d16fbf11dbd52256541a17c9f60b07 b/scanner/testdata/fuzz/FuzzScanner/22023bdee30f39396809ddfa903114a127d16fbf11dbd52256541a17c9f60b07
deleted file mode 100644
index 7865f86..0000000
--- a/scanner/testdata/fuzz/FuzzScanner/22023bdee30f39396809ddfa903114a127d16fbf11dbd52256541a17c9f60b07
+++ /dev/null
@@ -1,3 +0,0 @@
-go test fuzz v1
-[]byte("\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00")
-int64(0)
diff --git a/scanner/testdata/fuzz/FuzzScanner/50640a7a67794863f262b749f288aff8610f2cac65b7cf65b8708eb0ea104519 b/scanner/testdata/fuzz/FuzzScanner/50640a7a67794863f262b749f288aff8610f2cac65b7cf65b8708eb0ea104519
deleted file mode 100644
index e35970a..0000000
--- a/scanner/testdata/fuzz/FuzzScanner/50640a7a67794863f262b749f288aff8610f2cac65b7cf65b8708eb0ea104519
+++ /dev/null
@@ -1,3 +0,0 @@
-go test fuzz v1
-[]byte("001")
-int64(3472329395739373616)
diff --git a/scanner/testdata/fuzz/FuzzScanner/b1f8e3fd8087149215418297f28d6e1e447100179409d69a827c6651370d96cc b/scanner/testdata/fuzz/FuzzScanner/b1f8e3fd8087149215418297f28d6e1e447100179409d69a827c6651370d96cc
deleted file mode 100644
index e35970a..0000000
--- a/scanner/testdata/fuzz/FuzzScanner/b1f8e3fd8087149215418297f28d6e1e447100179409d69a827c6651370d96cc
+++ /dev/null
@@ -1,3 +0,0 @@
-go test fuzz v1
-[]byte("001")
-int64(3472329395739373616)
diff --git a/scanner/testdata/fuzz/FuzzScanner/caf81e9797b19c76c1fc4dbf537d4d81f389524539f402d13aa01f93a65ac7e9 b/scanner/testdata/fuzz/FuzzScanner/caf81e9797b19c76c1fc4dbf537d4d81f389524539f402d13aa01f93a65ac7e9
deleted file mode 100644
index ffa7e5c..0000000
--- a/scanner/testdata/fuzz/FuzzScanner/caf81e9797b19c76c1fc4dbf537d4d81f389524539f402d13aa01f93a65ac7e9
+++ /dev/null
@@ -1,3 +0,0 @@
-go test fuzz v1
-[]byte("")
-int64(0)
diff --git a/scrobble/lastfm/client.go b/scrobble/lastfm/client.go
deleted file mode 100644
index 5e87e43..0000000
--- a/scrobble/lastfm/client.go
+++ /dev/null
@@ -1,164 +0,0 @@
-package lastfm
-
-import (
- "crypto/md5"
- "encoding/hex"
- "encoding/xml"
- "errors"
- "fmt"
- "net/http"
- "net/url"
- "sort"
-
- "github.com/andybalholm/cascadia"
- "golang.org/x/net/html"
-)
-
-const (
- baseURL = "https://ws.audioscrobbler.com/2.0/"
-)
-
-var (
- ErrLastFM = errors.New("last.fm error")
-
- //nolint:gochecknoglobals
- artistOpenGraphQuery = cascadia.MustCompile(`html > head > meta[property="og:image"]`)
-)
-
-type Client struct {
- httpClient *http.Client
-}
-
-func NewClientCustom(httpClient *http.Client) *Client {
- return &Client{httpClient: httpClient}
-}
-
-func NewClient() *Client {
- return NewClientCustom(http.DefaultClient)
-}
-
-func getParamSignature(params url.Values, secret string) string {
- // the parameters must be in order before hashing
- paramKeys := make([]string, 0, len(params))
- for k := range params {
- paramKeys = append(paramKeys, k)
- }
- sort.Strings(paramKeys)
- toHash := ""
- for _, k := range paramKeys {
- toHash += k
- toHash += params[k][0]
- }
- toHash += secret
- hash := md5.Sum([]byte(toHash))
- return hex.EncodeToString(hash[:])
-}
-
-func (c *Client) makeRequest(method string, params url.Values) (LastFM, error) {
- req, _ := http.NewRequest(method, baseURL, nil)
- req.URL.RawQuery = params.Encode()
- resp, err := c.httpClient.Do(req)
- if err != nil {
- return LastFM{}, fmt.Errorf("get: %w", err)
- }
- defer resp.Body.Close()
- decoder := xml.NewDecoder(resp.Body)
- lastfm := LastFM{}
- if err = decoder.Decode(&lastfm); err != nil {
- return LastFM{}, fmt.Errorf("decoding: %w", err)
- }
- if lastfm.Error.Code != 0 {
- return LastFM{}, fmt.Errorf("%v: %w", lastfm.Error.Value, ErrLastFM)
- }
- return lastfm, nil
-}
-
-func (c *Client) ArtistGetInfo(apiKey string, artistName string) (Artist, error) {
- params := url.Values{}
- params.Add("method", "artist.getInfo")
- params.Add("api_key", apiKey)
- params.Add("artist", artistName)
- resp, err := c.makeRequest("GET", params)
- if err != nil {
- return Artist{}, fmt.Errorf("making artist GET: %w", err)
- }
- return resp.Artist, nil
-}
-
-func (c *Client) ArtistGetTopTracks(apiKey, artistName string) (TopTracks, error) {
- params := url.Values{}
- params.Add("method", "artist.getTopTracks")
- params.Add("api_key", apiKey)
- params.Add("artist", artistName)
- resp, err := c.makeRequest("GET", params)
- if err != nil {
- return TopTracks{}, fmt.Errorf("making track GET: %w", err)
- }
- return resp.TopTracks, nil
-}
-
-func (c *Client) TrackGetSimilarTracks(apiKey string, artistName, trackName string) (SimilarTracks, error) {
- params := url.Values{}
- params.Add("method", "track.getSimilar")
- params.Add("api_key", apiKey)
- params.Add("track", trackName)
- params.Add("artist", artistName)
- resp, err := c.makeRequest("GET", params)
- if err != nil {
- return SimilarTracks{}, fmt.Errorf("making track GET: %w", err)
- }
- return resp.SimilarTracks, nil
-}
-
-func (c *Client) ArtistGetSimilar(apiKey string, artistName string) (SimilarArtists, error) {
- params := url.Values{}
- params.Add("method", "artist.getSimilar")
- params.Add("api_key", apiKey)
- params.Add("artist", artistName)
- resp, err := c.makeRequest("GET", params)
- if err != nil {
- return SimilarArtists{}, fmt.Errorf("making similar artists GET: %w", err)
- }
- return resp.SimilarArtists, nil
-}
-
-func (c *Client) GetSession(apiKey, secret, token string) (string, error) {
- params := url.Values{}
- params.Add("method", "auth.getSession")
- params.Add("api_key", apiKey)
- params.Add("token", token)
- params.Add("api_sig", getParamSignature(params, secret))
- resp, err := c.makeRequest("GET", params)
- if err != nil {
- return "", fmt.Errorf("making session GET: %w", err)
- }
- return resp.Session.Key, nil
-}
-
-func (c *Client) StealArtistImage(artistURL string) (string, error) {
- resp, err := http.Get(artistURL) //nolint:gosec
- if err != nil {
- return "", fmt.Errorf("get artist url: %w", err)
- }
- defer resp.Body.Close()
-
- node, err := html.Parse(resp.Body)
- if err != nil {
- return "", fmt.Errorf("parse html: %w", err)
- }
-
- n := cascadia.Query(node, artistOpenGraphQuery)
- if n == nil {
- return "", nil
- }
-
- var imageURL string
- for _, attr := range n.Attr {
- if attr.Key == "content" {
- imageURL = attr.Val
- break
- }
- }
-
- return imageURL, nil
-}
diff --git a/scrobble/lastfm/client_test.go b/scrobble/lastfm/client_test.go
deleted file mode 100644
index 58df4c7..0000000
--- a/scrobble/lastfm/client_test.go
+++ /dev/null
@@ -1,466 +0,0 @@
-package lastfm
-
-import (
- "crypto/md5"
- "encoding/xml"
- "fmt"
- "net/http"
- "net/url"
- "testing"
-
- "github.com/stretchr/testify/require"
- "go.senan.xyz/gonic/scrobble/lastfm/mockclient"
-)
-
-func TestArtistGetInfo(t *testing.T) {
- // arrange
- require := require.New(t)
- client := Client{mockclient.New(t, func(w http.ResponseWriter, r *http.Request) {
- require.Equal(http.MethodGet, r.Method)
- require.Equal(url.Values{
- "method": []string{"artist.getInfo"},
- "api_key": []string{"apiKey1"},
- "artist": []string{"Artist 1"},
- }, r.URL.Query())
- require.Equal("/2.0/", r.URL.Path)
- require.Equal(baseURL, "https://"+r.Host+r.URL.Path)
-
- w.WriteHeader(http.StatusOK)
- w.Write(mockclient.ArtistGetInfoResponse)
- })}
-
- // act
- actual, err := client.ArtistGetInfo("apiKey1", "Artist 1")
-
- // assert
- require.NoError(err)
- require.Equal(Artist{
- XMLName: xml.Name{
- Local: "artist",
- },
- Name: "Artist 1",
- MBID: "366c1119-ec4f-4312-b729-a5637d148e3e",
- Streamable: "0",
- Stats: struct {
- Listeners string `xml:"listeners"`
- Playcount string `xml:"playcount"`
- }{
- Listeners: "1",
- Playcount: "2",
- },
- URL: "https://www.last.fm/music/Artist+1",
- Image: []Image{
- {
- Size: "small",
- Text: "https://last.fm/artist-1-small.png",
- },
- },
- Bio: ArtistBio{
- Published: "13 May 2023, 00:24",
- Summary: "Summary",
- Content: "Content",
- },
- Similar: struct {
- Artists []Artist `xml:"artist"`
- }{
- Artists: []Artist{
- {
- XMLName: xml.Name{
- Local: "artist",
- },
- Name: "Similar Artist 1",
- URL: "https://www.last.fm/music/Similar+Artist+1",
- Image: []Image{
- {
- Size: "small",
- Text: "https://last.fm/similar-artist-1-small.png",
- },
- },
- },
- },
- },
- Tags: struct {
- Tag []ArtistTag `xml:"tag"`
- }{
- Tag: []ArtistTag{
- {
- Name: "tag1",
- URL: "https://www.last.fm/tag/tag1",
- },
- },
- },
- }, actual)
-}
-
-func TestArtistGetInfoClientRequestFails(t *testing.T) {
- // arrange
- require := require.New(t)
- client := Client{mockclient.New(t, func(w http.ResponseWriter, r *http.Request) {
- require.Equal(http.MethodGet, r.Method)
- require.Equal(url.Values{
- "method": []string{"artist.getInfo"},
- "api_key": []string{"apiKey1"},
- "artist": []string{"Artist 1"},
- }, r.URL.Query())
- require.Equal("/2.0/", r.URL.Path)
- require.Equal(baseURL, "https://"+r.Host+r.URL.Path)
-
- w.WriteHeader(http.StatusInternalServerError)
- })}
-
- // act
- actual, err := client.ArtistGetInfo("apiKey1", "Artist 1")
-
- // assert
- require.Error(err)
- require.Zero(actual)
-}
-
-func TestArtistGetTopTracks(t *testing.T) {
- // arrange
- require := require.New(t)
- client := Client{mockclient.New(t, func(w http.ResponseWriter, r *http.Request) {
- require.Equal(http.MethodGet, r.Method)
- require.Equal(url.Values{
- "method": []string{"artist.getTopTracks"},
- "api_key": []string{"apiKey1"},
- "artist": []string{"artist1"},
- }, r.URL.Query())
- require.Equal("/2.0/", r.URL.Path)
- require.Equal(baseURL, "https://"+r.Host+r.URL.Path)
-
- w.WriteHeader(http.StatusOK)
- w.Write(mockclient.ArtistGetTopTracksResponse)
- })}
-
- // act
- actual, err := client.ArtistGetTopTracks("apiKey1", "artist1")
-
- // assert
- require.NoError(err)
- require.Equal(TopTracks{
- Artist: "Artist 1",
- XMLName: xml.Name{
- Local: "toptracks",
- },
- Tracks: []Track{
- {
- Image: []Image{
- {
- Text: "https://last.fm/track-1-small.png",
- Size: "small",
- },
- {
- Text: "https://last.fm/track-1-large.png",
- Size: "large",
- },
- },
- Listeners: 2,
- MBID: "fdfc47cb-69d3-4318-ba71-d54fbc20169a",
- Name: "Track 1",
- PlayCount: 1,
- Rank: 1,
- URL: "https://www.last.fm/music/Artist+1/_/Track+1",
- },
- {
- Image: []Image{
- {
- Text: "https://last.fm/track-2-small.png",
- Size: "small",
- },
- {
- Text: "https://last.fm/track-2-large.png",
- Size: "large",
- },
- },
- Listeners: 3,
- MBID: "cf32e694-1ea6-4ba0-9e8b-d5f1950da9c8",
- Name: "Track 2",
- PlayCount: 2,
- Rank: 2,
- URL: "https://www.last.fm/music/Artist+1/_/Track+2",
- },
- },
- }, actual)
-}
-
-func TestArtistGetTopTracks_clientRequestFails(t *testing.T) {
- // arrange
- require := require.New(t)
- client := Client{mockclient.New(t, func(w http.ResponseWriter, r *http.Request) {
- require.Equal(http.MethodGet, r.Method)
- require.Equal(url.Values{
- "method": []string{"artist.getTopTracks"},
- "api_key": []string{"apiKey1"},
- "artist": []string{"artist1"},
- }, r.URL.Query())
- require.Equal("/2.0/", r.URL.Path)
- require.Equal(baseURL, "https://"+r.Host+r.URL.Path)
-
- w.WriteHeader(http.StatusInternalServerError)
- })}
-
- // act
- actual, err := client.ArtistGetTopTracks("apiKey1", "artist1")
-
- // assert
- require.Error(err)
- require.Zero(actual)
-}
-
-func TestArtistGetSimilar(t *testing.T) {
- // arrange
- require := require.New(t)
- client := Client{mockclient.New(t, func(w http.ResponseWriter, r *http.Request) {
- require.Equal(http.MethodGet, r.Method)
- require.Equal(url.Values{
- "method": []string{"artist.getSimilar"},
- "api_key": []string{"apiKey1"},
- "artist": []string{"artist1"},
- }, r.URL.Query())
- require.Equal("/2.0/", r.URL.Path)
- require.Equal(baseURL, "https://"+r.Host+r.URL.Path)
-
- w.WriteHeader(http.StatusOK)
- w.Write(mockclient.ArtistGetSimilarResponse)
- })}
-
- // act
- actual, err := client.ArtistGetSimilar("apiKey1", "artist1")
-
- // assert
- require.NoError(err)
- require.Equal(SimilarArtists{
- XMLName: xml.Name{
- Local: "similarartists",
- },
- Artist: "Artist 1",
- Artists: []Artist{
- {
- XMLName: xml.Name{
- Local: "artist",
- },
- Image: []Image{
- {
- Text: "https://last.fm/artist-2-small.png",
- Size: "small",
- },
- {
- Text: "https://last.fm/artist-2-large.png",
- Size: "large",
- },
- },
- MBID: "d2addad9-3fc4-4ce8-9cd4-63f2a19bb922",
- Name: "Artist 2",
- Similar: struct {
- Artists []Artist `xml:"artist"`
- }{},
- Streamable: "0",
- URL: "https://www.last.fm/music/Artist+2",
- },
- {
- XMLName: xml.Name{
- Local: "artist",
- },
- Image: []Image{
- {
- Text: "https://last.fm/artist-3-small.png",
- Size: "small",
- },
- {
- Text: "https://last.fm/artist-3-large.png",
- Size: "large",
- },
- },
- MBID: "dc95d067-df3e-4b83-a5fe-5ec773b1883f",
- Name: "Artist 3",
- Similar: struct {
- Artists []Artist `xml:"artist"`
- }{},
- Streamable: "0",
- URL: "https://www.last.fm/music/Artist+3",
- },
- },
- }, actual)
-}
-
-func TestArtistGetSimilar_clientRequestFails(t *testing.T) {
- // arrange
- require := require.New(t)
- client := Client{mockclient.New(t, func(w http.ResponseWriter, r *http.Request) {
- require.Equal(http.MethodGet, r.Method)
- require.Equal(url.Values{
- "method": []string{"artist.getSimilar"},
- "api_key": []string{"apiKey1"},
- "artist": []string{"artist1"},
- }, r.URL.Query())
- require.Equal("/2.0/", r.URL.Path)
- require.Equal(baseURL, "https://"+r.Host+r.URL.Path)
-
- w.WriteHeader(http.StatusInternalServerError)
- })}
-
- // act
- actual, err := client.ArtistGetSimilar("apiKey1", "artist1")
-
- // assert
- require.Error(err)
- require.Zero(actual)
-}
-
-func TestTrackGetSimilarTracks(t *testing.T) {
- // arrange
- require := require.New(t)
- client := Client{mockclient.New(t, func(w http.ResponseWriter, r *http.Request) {
- require.Equal(http.MethodGet, r.Method)
- require.Equal(url.Values{
- "method": []string{"track.getSimilar"},
- "api_key": []string{"apiKey1"},
- "artist": []string{"artist1"},
- "track": []string{"track1"},
- }, r.URL.Query())
- require.Equal("/2.0/", r.URL.Path)
- require.Equal(baseURL, "https://"+r.Host+r.URL.Path)
-
- w.WriteHeader(http.StatusOK)
- w.Write(mockclient.TrackGetSimilarResponse)
- })}
-
- // act
- actual, err := client.TrackGetSimilarTracks("apiKey1", "artist1", "track1")
-
- // assert
- require.NoError(err)
- require.Equal(SimilarTracks{
- Artist: "Artist 1",
- Track: "Track 1",
- XMLName: xml.Name{
- Local: "similartracks",
- },
- Tracks: []Track{
- {
- Image: []Image{
- {
- Text: "https://last.fm/track-1-small.png",
- Size: "small",
- },
- {
- Text: "https://last.fm/track-1-large.png",
- Size: "large",
- },
- },
- MBID: "7096931c-bf82-4896-b1e7-42b60a0e16ea",
- Name: "Track 1",
- PlayCount: 1,
- URL: "https://www.last.fm/music/Artist+1/_/Track+1",
- },
- {
- Image: []Image{
- {
- Text: "https://last.fm/track-2-small.png",
- Size: "small",
- },
- {
- Text: "https://last.fm/track-2-large.png",
- Size: "large",
- },
- },
- MBID: "2aff1321-149f-4000-8762-3468c917600c",
- Name: "Track 2",
- PlayCount: 2,
- URL: "https://www.last.fm/music/Artist+2/_/Track+2",
- },
- },
- }, actual)
-}
-
-func TestTrackGetSimilarTracks_clientRequestFails(t *testing.T) {
- // arrange
- require := require.New(t)
- client := Client{mockclient.New(t, func(w http.ResponseWriter, r *http.Request) {
- require.Equal(http.MethodGet, r.Method)
- require.Equal(url.Values{
- "method": []string{"track.getSimilar"},
- "api_key": []string{"apiKey1"},
- "artist": []string{"artist1"},
- "track": []string{"track1"},
- }, r.URL.Query())
- require.Equal("/2.0/", r.URL.Path)
- require.Equal(baseURL, "https://"+r.Host+r.URL.Path)
-
- w.WriteHeader(http.StatusInternalServerError)
- })}
-
- // act
- actual, err := client.TrackGetSimilarTracks("apiKey1", "artist1", "track1")
-
- // assert
- require.Error(err)
- require.Zero(actual)
-}
-
-func TestGetSession(t *testing.T) {
- // arrange
- require := require.New(t)
- client := Client{mockclient.New(t, func(w http.ResponseWriter, r *http.Request) {
- require.Equal(http.MethodGet, r.Method)
- require.Equal(url.Values{
- "method": []string{"auth.getSession"},
- "api_key": []string{"apiKey1"},
- "api_sig": []string{"b872a708a0b8b1d9fc1230b1cb6493f8"},
- "token": []string{"token1"},
- }, r.URL.Query())
- require.Equal("/2.0/", r.URL.Path)
- require.Equal(baseURL, "https://"+r.Host+r.URL.Path)
-
- w.WriteHeader(http.StatusOK)
- w.Write(mockclient.GetSessionResponse)
- })}
-
- // act
- actual, err := client.GetSession("apiKey1", "secret1", "token1")
-
- // assert
- require.NoError(err)
- require.Equal("sessionKey1", actual)
-}
-
-func TestGetSessioeClientRequestFails(t *testing.T) {
- // arrange
- require := require.New(t)
- client := Client{mockclient.New(t, func(w http.ResponseWriter, r *http.Request) {
- require.Equal(http.MethodGet, r.Method)
- require.Equal(url.Values{
- "method": []string{"auth.getSession"},
- "api_key": []string{"apiKey1"},
- "api_sig": []string{"b872a708a0b8b1d9fc1230b1cb6493f8"},
- "token": []string{"token1"},
- }, r.URL.Query())
- require.Equal("/2.0/", r.URL.Path)
- require.Equal(baseURL, "https://"+r.Host+r.URL.Path)
-
- w.WriteHeader(http.StatusInternalServerError)
- })}
-
- // act
- actual, err := client.GetSession("apiKey1", "secret1", "token1")
-
- // assert
- require.Error(err)
- require.Zero(actual)
-}
-
-func TestGetParamSignature(t *testing.T) {
- params := url.Values{}
- params.Add("ccc", "CCC")
- params.Add("bbb", "BBB")
- params.Add("aaa", "AAA")
- params.Add("ddd", "DDD")
- actual := getParamSignature(params, "secret")
- expected := fmt.Sprintf("%x", md5.Sum([]byte(
- "aaaAAAbbbBBBcccCCCdddDDDsecret",
- )))
- if actual != expected {
- t.Errorf("expected %x, got %s", expected, actual)
- }
-}
diff --git a/scrobble/lastfm/model.go b/scrobble/lastfm/model.go
deleted file mode 100644
index 1ddf379..0000000
--- a/scrobble/lastfm/model.go
+++ /dev/null
@@ -1,102 +0,0 @@
-package lastfm
-
-import "encoding/xml"
-
-type (
- LastFM struct {
- XMLName xml.Name `xml:"lfm"`
- Status string `xml:"status,attr"`
- Session Session `xml:"session"`
- Error Error `xml:"error"`
- Artist Artist `xml:"artist"`
- TopTracks TopTracks `xml:"toptracks"`
- SimilarTracks SimilarTracks `xml:"similartracks"`
- SimilarArtists SimilarArtists `xml:"similarartists"`
- }
-
- Session struct {
- Name string `xml:"name"`
- Key string `xml:"key"`
- Subscriber uint `xml:"subscriber"`
- }
-
- Error struct {
- Code uint `xml:"code,attr"`
- Value string `xml:",chardata"`
- }
-
- SimilarArtist struct {
- XMLName xml.Name `xml:"artist"`
- Name string `xml:"name"`
- MBID string `xml:"mbid"`
- URL string `xml:"url"`
- Image []Image `xml:"image"`
- Streamable string `xml:"streamable"`
- }
-
- Image struct {
- Text string `xml:",chardata"`
- Size string `xml:"size,attr"`
- }
-
- Artist struct {
- XMLName xml.Name `xml:"artist"`
- Name string `xml:"name"`
- MBID string `xml:"mbid"`
- URL string `xml:"url"`
- Image []Image `xml:"image"`
- Streamable string `xml:"streamable"`
- Stats struct {
- Listeners string `xml:"listeners"`
- Playcount string `xml:"playcount"`
- } `xml:"stats"`
- Similar struct {
- Artists []Artist `xml:"artist"`
- } `xml:"similar"`
- Tags struct {
- Tag []ArtistTag `xml:"tag"`
- } `xml:"tags"`
- Bio ArtistBio `xml:"bio"`
- }
-
- ArtistTag struct {
- Name string `xml:"name"`
- URL string `xml:"url"`
- }
-
- ArtistBio struct {
- Published string `xml:"published"`
- Summary string `xml:"summary"`
- Content string `xml:"content"`
- }
-
- TopTracks struct {
- XMLName xml.Name `xml:"toptracks"`
- Artist string `xml:"artist,attr"`
- Tracks []Track `xml:"track"`
- }
-
- SimilarTracks struct {
- XMLName xml.Name `xml:"similartracks"`
- Artist string `xml:"artist,attr"`
- Track string `xml:"track,attr"`
- Tracks []Track `xml:"track"`
- }
-
- SimilarArtists struct {
- XMLName xml.Name `xml:"similarartists"`
- Artist string `xml:"artist,attr"`
- Artists []Artist `xml:"artist"`
- }
-
- Track struct {
- Rank int `xml:"rank,attr"`
- Tracks []Track `xml:"track"`
- Name string `xml:"name"`
- MBID string `xml:"mbid"`
- PlayCount int `xml:"playcount"`
- Listeners int `xml:"listeners"`
- URL string `xml:"url"`
- Image []Image `xml:"image"`
- }
-)
diff --git a/scrobble/lastfm/scrobbler.go b/scrobble/lastfm/scrobbler.go
deleted file mode 100644
index e629158..0000000
--- a/scrobble/lastfm/scrobbler.go
+++ /dev/null
@@ -1,73 +0,0 @@
-package lastfm
-
-import (
- "fmt"
- "net/url"
- "strconv"
- "strings"
- "time"
-
- "github.com/google/uuid"
- "go.senan.xyz/gonic/db"
- "go.senan.xyz/gonic/scrobble"
-)
-
-type Scrobbler struct {
- db *db.DB
- client *Client
-}
-
-var _ scrobble.Scrobbler = (*Scrobbler)(nil)
-
-func NewScrobbler(db *db.DB, client *Client) *Scrobbler {
- return &Scrobbler{
- db: db,
- client: client,
- }
-}
-
-func (s *Scrobbler) Scrobble(user *db.User, track *db.Track, stamp time.Time, submission bool) error {
- if user.LastFMSession == "" {
- return nil
- }
- if track.Album == nil || len(track.Album.Artists) == 0 {
- return fmt.Errorf("track has no album artists")
- }
-
- apiKey, err := s.db.GetSetting(db.LastFMAPIKey)
- if err != nil {
- return fmt.Errorf("get api key: %w", err)
- }
- secret, err := s.db.GetSetting(db.LastFMSecret)
- if err != nil {
- return fmt.Errorf("get secret: %w", err)
- }
-
- params := url.Values{}
- if submission {
- params.Add("method", "track.Scrobble")
- // last.fm wants the timestamp in seconds
- params.Add("timestamp", strconv.Itoa(int(stamp.Unix())))
- } else {
- params.Add("method", "track.updateNowPlaying")
- }
-
- params.Add("api_key", apiKey)
- params.Add("sk", user.LastFMSession)
- params.Add("artist", track.TagTrackArtist)
- params.Add("track", track.TagTitle)
- params.Add("trackNumber", strconv.Itoa(track.TagTrackNumber))
- params.Add("album", track.Album.TagTitle)
- params.Add("albumArtist", strings.Join(track.Album.ArtistsStrings(), ", "))
- params.Add("duration", strconv.Itoa(track.Length))
-
- // make sure we provide a valid uuid, since some users may have an incorrect mbid in their tags
- if _, err := uuid.Parse(track.TagBrainzID); err == nil {
- params.Add("mbid", track.TagBrainzID)
- }
-
- params.Add("api_sig", getParamSignature(params, secret))
-
- _, err = s.client.makeRequest("POST", params)
- return err
-}
diff --git a/scrobble/lastfm/scrobbler_test.go b/scrobble/lastfm/scrobbler_test.go
deleted file mode 100644
index 0b288e6..0000000
--- a/scrobble/lastfm/scrobbler_test.go
+++ /dev/null
@@ -1,113 +0,0 @@
-package lastfm
-
-import (
- "net/http"
- "net/url"
- "testing"
- "time"
-
- _ "github.com/mattn/go-sqlite3"
- "github.com/stretchr/testify/require"
- "go.senan.xyz/gonic/db"
- "go.senan.xyz/gonic/scrobble/lastfm/mockclient"
-)
-
-func TestScrobble(t *testing.T) {
- // arrange
- t.Parallel()
- require := require.New(t)
-
- testDB, err := db.NewMock()
- require.NoError(err)
- err = testDB.Migrate(db.MigrationContext{})
- require.NoError(err)
-
- testDB.SetSetting(db.LastFMAPIKey, "apiKey1")
- testDB.SetSetting(db.LastFMSecret, "secret1")
-
- user := &db.User{
- LastFMSession: "lastFMSession1",
- }
-
- track := &db.Track{
- Album: &db.Album{
- TagTitle: "album1",
- Artists: []*db.Artist{{
- Name: "artist1",
- }},
- },
- Length: 100,
- TagBrainzID: "916b242d-d439-4ae4-a439-556eef99c06e",
- TagTitle: "title1",
- TagTrackArtist: "trackArtist1",
- TagTrackNumber: 1,
- }
-
- stamp := time.Date(2023, 8, 12, 12, 34, 1, 200, time.UTC)
-
- client := Client{mockclient.New(t, func(w http.ResponseWriter, r *http.Request) {
- require.Equal(http.MethodPost, r.Method)
- require.Equal(url.Values{
- "album": []string{"album1"},
- "albumArtist": []string{"artist1"},
- "api_key": []string{"apiKey1"},
- "api_sig": []string{"d235a0b911eb4923953f496c61a2a6af"},
- "artist": []string{"trackArtist1"},
- "duration": []string{"100"},
- "method": []string{"track.Scrobble"},
- "sk": []string{"lastFMSession1"},
- "mbid": []string{"916b242d-d439-4ae4-a439-556eef99c06e"},
- "timestamp": []string{"1691843641"},
- "track": []string{"title1"},
- "trackNumber": []string{"1"},
- }, r.URL.Query())
- require.Equal("/2.0/", r.URL.Path)
- require.Equal(baseURL, "https://"+r.Host+r.URL.Path)
-
- w.WriteHeader(http.StatusOK)
- w.Write(mockclient.ArtistGetTopTracksResponse)
- })}
-
- scrobbler := NewScrobbler(testDB, &client)
-
- // act
- err = scrobbler.Scrobble(user, track, stamp, true)
-
- // assert
- require.NoError(err)
-}
-
-func TestScrobbleReturnsWithoutLastFMSession(t *testing.T) {
- // arrange
- t.Parallel()
- require := require.New(t)
-
- scrobbler := Scrobbler{}
-
- // act
- err := scrobbler.Scrobble(&db.User{}, &db.Track{}, time.Now(), false)
-
- // assert
- require.NoError(err)
-}
-
-func TestScrobbleFailsWithoutLastFMAPIKey(t *testing.T) {
- // arrange
- t.Parallel()
- require := require.New(t)
-
- testDB, err := db.NewMock()
- require.NoError(err)
-
- user := &db.User{
- LastFMSession: "lastFMSession1",
- }
-
- scrobbler := NewScrobbler(testDB, nil)
-
- // act
- err = scrobbler.Scrobble(user, &db.Track{}, time.Now(), false)
-
- // assert
- require.Error(err)
-}
diff --git a/scrobble/listenbrainz/listenbrainz_test.go b/scrobble/listenbrainz/listenbrainz_test.go
deleted file mode 100644
index c6e5c46..0000000
--- a/scrobble/listenbrainz/listenbrainz_test.go
+++ /dev/null
@@ -1,148 +0,0 @@
-package listenbrainz
-
-import (
- "context"
- "crypto/tls"
- _ "embed"
- "io"
- "net"
- "net/http"
- "net/http/httptest"
- "testing"
- "time"
-
- "github.com/stretchr/testify/require"
- "go.senan.xyz/gonic/db"
-)
-
-func httpClientMock(handler http.Handler) (http.Client, func()) {
- server := httptest.NewTLSServer(handler)
- shutdown := http.Client{
- Transport: &http.Transport{
- DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
- return net.Dial(network, server.Listener.Addr().String())
- },
- TLSClientConfig: &tls.Config{
- InsecureSkipVerify: true, //nolint:gosec
- },
- },
- }
-
- return shutdown, server.Close
-}
-
-//go:embed testdata/submit_listens_request.json
-var submitListensRequest string
-
-func TestScrobble(t *testing.T) {
- t.Parallel()
- require := require.New(t)
-
- // arrange
- client, shutdown := httpClientMock(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- require.Equal(http.MethodPost, r.Method)
- require.Equal("/1/submit-listens", r.URL.Path)
- require.Equal("application/json", r.Header.Get("Content-Type"))
- require.Equal("Token token1", r.Header.Get("Authorization"))
- bodyBytes, err := io.ReadAll(r.Body)
- require.NoError(err)
- require.JSONEq(submitListensRequest, string(bodyBytes))
-
- w.WriteHeader(http.StatusOK)
- w.Write([]byte(`{"accepted": 1}`))
- }))
- defer shutdown()
-
- scrobbler := Scrobbler{
- httpClient: &client,
- }
-
- // act
- err := scrobbler.Scrobble(&db.User{
- ListenBrainzURL: "https://listenbrainz.org",
- ListenBrainzToken: "token1",
- }, &db.Track{
- Album: &db.Album{
- TagTitle: "album",
- },
- TagTitle: "title",
- TagTrackArtist: "artist",
- TagTrackNumber: 1,
- }, time.Unix(1683804525, 0), true)
-
- // assert
- require.NoError(err)
-}
-
-func TestScrobbleUnauthorized(t *testing.T) {
- t.Parallel()
- require := require.New(t)
-
- // arrange
- client, shutdown := httpClientMock(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- require.Equal(http.MethodPost, r.Method)
- require.Equal("/1/submit-listens", r.URL.Path)
- require.Equal("application/json", r.Header.Get("Content-Type"))
- require.Equal("Token token1", r.Header.Get("Authorization"))
-
- w.WriteHeader(http.StatusUnauthorized)
- w.Write([]byte(`{"code": 401, "error": "Invalid authorization token."}`))
- }))
- defer shutdown()
-
- scrobbler := Scrobbler{
- httpClient: &client,
- }
-
- // act
- err := scrobbler.Scrobble(&db.User{
- ListenBrainzURL: "https://listenbrainz.org",
- ListenBrainzToken: "token1",
- }, &db.Track{
- Album: &db.Album{
- TagTitle: "album",
- },
- TagTitle: "title",
- TagTrackArtist: "artist",
- TagTrackNumber: 1,
- }, time.Now(), true)
-
- // assert
- require.ErrorIs(err, ErrListenBrainz)
-}
-
-func TestScrobbleServerError(t *testing.T) {
- t.Parallel()
- require := require.New(t)
-
- // arrange
- client, shutdown := httpClientMock(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- require.Equal(http.MethodPost, r.Method)
- require.Equal("/1/submit-listens", r.URL.Path)
- require.Equal("application/json", r.Header.Get("Content-Type"))
- require.Equal("Token token1", r.Header.Get("Authorization"))
-
- w.WriteHeader(http.StatusInternalServerError)
- }))
- defer shutdown()
-
- scrobbler := Scrobbler{
- httpClient: &client,
- }
-
- // act
- err := scrobbler.Scrobble(&db.User{
- ListenBrainzURL: "https://listenbrainz.org",
- ListenBrainzToken: "token1",
- }, &db.Track{
- Album: &db.Album{
- TagTitle: "album",
- },
- TagTitle: "title",
- TagTrackArtist: "artist",
- TagTrackNumber: 1,
- }, time.Now(), true)
-
- // assert
- require.ErrorIs(err, ErrListenBrainz)
-}
diff --git a/scrobble/scrobble.go b/scrobble/scrobble.go
index 45700c2..8b8c9f6 100644
--- a/scrobble/scrobble.go
+++ b/scrobble/scrobble.go
@@ -6,6 +6,17 @@ import (
"go.senan.xyz/gonic/db"
)
+type Track struct {
+ Track string
+ Artist string
+ Album string
+ AlbumArtist string
+ TrackNumber uint
+ Duration time.Duration
+ MusicBrainzID string
+}
+
type Scrobbler interface {
- Scrobble(user *db.User, track *db.Track, stamp time.Time, submission bool) error
+ IsUserAuthenticated(user db.User) bool
+ Scrobble(user db.User, track Track, stamp time.Time, submission bool) error
}
diff --git a/server/ctrladmin/adminui/pages/home.tmpl b/server/ctrladmin/adminui/pages/home.tmpl
index fb46101..77d7b3f 100644
--- a/server/ctrladmin/adminui/pages/home.tmpl
+++ b/server/ctrladmin/adminui/pages/home.tmpl
@@ -7,12 +7,20 @@
"Desc" "total items found in all watched folders"
) }}
-
artists
-
{{ .ArtistCount }}
+
folders
+
{{ .Stats.Folders }}
albums
-
{{ .AlbumCount }}
+
{{ .Stats.Albums }}
+
artists
+
{{ .Stats.Artists }}
+
album artists
+
{{ .Stats.AlbumArtists }}
tracks
-
{{ .TrackCount }}
+
{{ .Stats.Tracks }}
+
internet radio stations
+
{{ .Stats.InternetRadioStations }}
+
podcasts
+
{{ .Stats.Podcasts }}
{{ end }}
@@ -52,7 +60,11 @@
{{ end }}
{{ range $folder := .RecentFolders }}
{{ $folder.RightPath }}
- {{ $folder.ModifiedAt | dateHuman }}
+ {{ if not $folder.ModifiedAt.IsZero }}
+ {{ $folder.ModifiedAt | dateHuman }}
+ {{ else }}
+
+ {{ end }}
{{ end }}
{{ if and (not .IsScanning) (.User.IsAdmin) }}
{{ if not .LastScanTime.IsZero }}
diff --git a/server/ctrladmin/ctrl.go b/server/ctrladmin/ctrl.go
index 4170bca..7331890 100644
--- a/server/ctrladmin/ctrl.go
+++ b/server/ctrladmin/ctrl.go
@@ -1,7 +1,9 @@
-// Package ctrladmin provides HTTP handlers for admin UI
package ctrladmin
import (
+ "bytes"
+ "context"
+ "embed"
"encoding/base64"
"encoding/gob"
"encoding/json"
@@ -11,22 +13,23 @@ import (
"net/http"
"net/url"
"strings"
+ "sync"
"time"
"github.com/Masterminds/sprig"
"github.com/dustin/go-humanize"
"github.com/fatih/structs"
"github.com/gorilla/sessions"
- "github.com/oxtoacart/bpool"
"github.com/philippta/go-template/html/template"
"github.com/sentriz/gormstore"
"go.senan.xyz/gonic"
"go.senan.xyz/gonic/db"
- "go.senan.xyz/gonic/podcasts"
- "go.senan.xyz/gonic/scrobble/lastfm"
+ "go.senan.xyz/gonic/handlerutil"
+ "go.senan.xyz/gonic/lastfm"
+ "go.senan.xyz/gonic/podcast"
+ "go.senan.xyz/gonic/scanner"
"go.senan.xyz/gonic/server/ctrladmin/adminui"
- "go.senan.xyz/gonic/server/ctrlbase"
)
type CtxKey int
@@ -36,6 +39,274 @@ const (
CtxSession
)
+type Controller struct {
+ *http.ServeMux
+
+ dbc *db.DB
+ sessDB *gormstore.Store
+ scanner *scanner.Scanner
+ podcasts *podcast.Podcasts
+ lastfmClient *lastfm.Client
+ resolveProxyPath ProxyPathResolver
+}
+
+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) (*Controller, error) {
+ c := Controller{
+ ServeMux: http.NewServeMux(),
+
+ dbc: dbc,
+ sessDB: sessDB,
+ scanner: scanner,
+ podcasts: podcasts,
+ lastfmClient: lastfmClient,
+ resolveProxyPath: resolveProxyPath,
+ }
+
+ resp := respHandler(adminui.TemplatesFS, resolveProxyPath)
+
+ baseChain := withSession(sessDB)
+ userChain := handlerutil.Chain(
+ baseChain,
+ withUserSession(dbc, resolveProxyPath),
+ )
+ adminChain := handlerutil.Chain(
+ userChain,
+ withAdminSession,
+ )
+
+ c.Handle("/static/", http.FileServer(http.FS(adminui.StaticFS)))
+
+ // public routes (creates session)
+ c.Handle("/login", baseChain(resp(c.ServeLogin)))
+ c.Handle("/login_do", baseChain(respRaw(c.ServeLoginDo)))
+
+ // user routes (if session is valid)
+ c.Handle("/logout", userChain(respRaw(c.ServeLogout)))
+ c.Handle("/home", userChain(resp(c.ServeHome)))
+ c.Handle("/ldap", userChain(resp(c.ServeLDAPConfig)))
+ c.Handle("/ldap_do", userChain(resp(c.ServeLDAPConfigDo)))
+ c.Handle("/change_username", userChain(resp(c.ServeChangeUsername)))
+ c.Handle("/change_username_do", userChain(resp(c.ServeChangeUsernameDo)))
+ c.Handle("/change_password", userChain(resp(c.ServeChangePassword)))
+ c.Handle("/change_password_do", userChain(resp(c.ServeChangePasswordDo)))
+ c.Handle("/change_avatar", userChain(resp(c.ServeChangeAvatar)))
+ c.Handle("/change_avatar_do", userChain(resp(c.ServeChangeAvatarDo)))
+ c.Handle("/delete_avatar_do", userChain(resp(c.ServeDeleteAvatarDo)))
+ c.Handle("/delete_user", userChain(resp(c.ServeDeleteUser)))
+ c.Handle("/delete_user_do", userChain(resp(c.ServeDeleteUserDo)))
+ c.Handle("/link_lastfm_do", userChain(resp(c.ServeLinkLastFMDo)))
+ c.Handle("/unlink_lastfm_do", userChain(resp(c.ServeUnlinkLastFMDo)))
+ c.Handle("/link_listenbrainz_do", userChain(resp(c.ServeLinkListenBrainzDo)))
+ c.Handle("/unlink_listenbrainz_do", userChain(resp(c.ServeUnlinkListenBrainzDo)))
+ c.Handle("/create_transcode_pref_do", userChain(resp(c.ServeCreateTranscodePrefDo)))
+ c.Handle("/delete_transcode_pref_do", userChain(resp(c.ServeDeleteTranscodePrefDo)))
+
+ // admin routes (if session is valid, and is admin)
+ c.Handle("/create_user", adminChain(resp(c.ServeCreateUser)))
+ c.Handle("/create_user_do", adminChain(resp(c.ServeCreateUserDo)))
+ c.Handle("/update_lastfm_api_key", adminChain(resp(c.ServeUpdateLastFMAPIKey)))
+ c.Handle("/update_lastfm_api_key_do", adminChain(resp(c.ServeUpdateLastFMAPIKeyDo)))
+ c.Handle("/start_scan_inc_do", adminChain(resp(c.ServeStartScanIncDo)))
+ c.Handle("/start_scan_full_do", adminChain(resp(c.ServeStartScanFullDo)))
+ c.Handle("/add_podcast_do", adminChain(resp(c.ServePodcastAddDo)))
+ c.Handle("/delete_podcast_do", adminChain(resp(c.ServePodcastDeleteDo)))
+ c.Handle("/download_podcast_do", adminChain(resp(c.ServePodcastDownloadDo)))
+ c.Handle("/update_podcast_do", adminChain(resp(c.ServePodcastUpdateDo)))
+ c.Handle("/add_internet_radio_station_do", adminChain(resp(c.ServeInternetRadioStationAddDo)))
+ c.Handle("/delete_internet_radio_station_do", adminChain(resp(c.ServeInternetRadioStationDeleteDo)))
+ c.Handle("/update_internet_radio_station_do", adminChain(resp(c.ServeInternetRadioStationUpdateDo)))
+
+ c.Handle("/", baseChain(resp(c.ServeNotFound)))
+
+ return &c, nil
+}
+
+func withSession(sessDB *gormstore.Store) handlerutil.Middleware {
+ return func(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ session, err := sessDB.Get(r, gonic.Name)
+ if err != nil {
+ http.Error(w, fmt.Sprintf("error getting session: %s", err), 500)
+ return
+ }
+ withSession := context.WithValue(r.Context(), CtxSession, session)
+ next.ServeHTTP(w, r.WithContext(withSession))
+ })
+ }
+}
+
+func withUserSession(dbc *db.DB, resolvePath func(string) string) handlerutil.Middleware {
+ return func(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ // session exists at this point
+ session := r.Context().Value(CtxSession).(*sessions.Session)
+ userID, ok := session.Values["user"].(int)
+ if !ok {
+ sessAddFlashW(session, []string{"you are not authenticated"})
+ sessLogSave(session, w, r)
+ http.Redirect(w, r, resolvePath("/admin/login"), http.StatusSeeOther)
+ return
+ }
+ // take username from sesion and add the user row to the context
+ user := dbc.GetUserByID(userID)
+ if user == nil {
+ // the username in the client's session no longer relates to a
+ // user in the database (maybe the user was deleted)
+ session.Options.MaxAge = -1
+ sessLogSave(session, w, r)
+ http.Redirect(w, r, "/", http.StatusSeeOther)
+ return
+ }
+ withUser := context.WithValue(r.Context(), CtxUser, user)
+ next.ServeHTTP(w, r.WithContext(withUser))
+ })
+ }
+}
+
+func withAdminSession(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ // session and user exist at this point
+ session := r.Context().Value(CtxSession).(*sessions.Session)
+ user := r.Context().Value(CtxUser).(*db.User)
+ if !user.IsAdmin {
+ sessAddFlashW(session, []string{"you are not an admin"})
+ sessLogSave(session, w, r)
+ http.Redirect(w, r, "/admin/login", http.StatusSeeOther)
+ return
+ }
+ next.ServeHTTP(w, r)
+ })
+}
+
+type Response struct {
+ // code is 200
+ template string
+ data *templateData
+ // code is 303
+ redirect string
+ flashN []string // normal
+ flashW []string // warning
+ // code is >= 400
+ code int
+ err string
+}
+
+type (
+ handlerAdmin func(r *http.Request) *Response
+)
+
+func respHandler(templateFS embed.FS, resolvePath func(string) string) func(next handlerAdmin) http.Handler {
+ tmpl := template.Must(template.
+ New("layout").
+ Funcs(template.FuncMap(sprig.FuncMap())).
+ Funcs(funcMap()).
+ Funcs(template.FuncMap{"path": resolvePath}).
+ ParseFS(templateFS, "*.tmpl", "**/*.tmpl"),
+ )
+ buffPool := sync.Pool{New: func() any { return new(bytes.Buffer) }}
+
+ return func(next handlerAdmin) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ resp := next(r)
+ session, ok := r.Context().Value(CtxSession).(*sessions.Session)
+ if ok {
+ sessAddFlashN(session, resp.flashN)
+ sessAddFlashW(session, resp.flashW)
+ if err := session.Save(r, w); err != nil {
+ http.Error(w, fmt.Sprintf("error saving session: %v", err), 500)
+ return
+ }
+ }
+ if resp.redirect != "" {
+ http.Redirect(w, r, resolvePath(resp.redirect), http.StatusSeeOther)
+ return
+ }
+ if resp.err != "" {
+ http.Error(w, resp.err, resp.code)
+ return
+ }
+ if resp.template == "" {
+ http.Error(w, "useless handler return", 500)
+ return
+ }
+
+ if resp.data == nil {
+ resp.data = &templateData{}
+ }
+ resp.data.Version = gonic.Version
+ if session != nil {
+ resp.data.Flashes = session.Flashes()
+ if err := session.Save(r, w); err != nil {
+ http.Error(w, fmt.Sprintf("error saving session: %v", err), 500)
+ return
+ }
+ }
+ if user, ok := r.Context().Value(CtxUser).(*db.User); ok {
+ resp.data.User = user
+ }
+
+ buff := buffPool.Get().(*bytes.Buffer)
+ defer buffPool.Put(buff)
+ buff.Reset()
+
+ if err := tmpl.ExecuteTemplate(buff, resp.template, resp.data); err != nil {
+ http.Error(w, fmt.Sprintf("executing template: %v", err), 500)
+ return
+ }
+
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ if resp.code != 0 {
+ w.WriteHeader(resp.code)
+ }
+ if _, err := buff.WriteTo(w); err != nil {
+ log.Printf("error writing to response buffer: %v\n", err)
+ }
+ })
+ }
+}
+
+func respRaw(h http.HandlerFunc) http.Handler {
+ return h // stub
+}
+
+type templateData struct {
+ // common
+ Flashes []interface{}
+ User *db.User
+ Version string
+
+ // home
+ Stats db.Stats
+ RequestRoot string
+ RecentFolders []*db.Album
+ AllUsers []*db.User
+ LastScanTime time.Time
+ IsScanning bool
+ TranscodePreferences []*db.TranscodePreference
+ TranscodeProfiles []string
+
+ CurrentLastFMAPIKey string
+ CurrentLastFMAPISecret string
+ DefaultListenBrainzURL string
+ SelectedUser *db.User
+
+
+ CurrentBindUID string
+ CurrentFQDN string
+ CurrentPort string
+ CurrentNoTLS string
+ CurrentBaseDN string
+ CurrentFilter string
+
+ Podcasts []*db.Podcast
+ InternetRadioStations []*db.InternetRadioStation
+
+ // avatar
+ Avatar []byte
+}
+
func funcMap() template.FuncMap {
return template.FuncMap{
"str": func(in any) string {
@@ -73,160 +344,7 @@ func funcMap() template.FuncMap {
}
}
-type Controller struct {
- *ctrlbase.Controller
- buffPool *bpool.BufferPool
- template *template.Template
- sessDB *gormstore.Store
- Podcasts *podcasts.Podcasts
- lastfmClient *lastfm.Client
-}
-
-func New(b *ctrlbase.Controller, sessDB *gormstore.Store, podcasts *podcasts.Podcasts, lastfmClient *lastfm.Client) (*Controller, error) {
- tmpl, err := template.
- New("layout").
- Funcs(template.FuncMap(sprig.FuncMap())).
- Funcs(funcMap()). // static
- Funcs(template.FuncMap{ // from base
- "path": b.Path,
- }).
- ParseFS(adminui.TemplatesFS, "*.tmpl", "**/*.tmpl")
- if err != nil {
- return nil, fmt.Errorf("build template: %w", err)
- }
- return &Controller{
- Controller: b,
- buffPool: bpool.NewBufferPool(64),
- template: tmpl,
- sessDB: sessDB,
- Podcasts: podcasts,
- lastfmClient: lastfmClient,
- }, nil
-}
-
-type templateData struct {
- // common
- Flashes []interface{}
- User *db.User
- Version string
- // home
- AlbumCount int
- ArtistCount int
- TrackCount int
- RequestRoot string
- RecentFolders []*db.Album
- AllUsers []*db.User
- LastScanTime time.Time
- IsScanning bool
- TranscodePreferences []*db.TranscodePreference
- TranscodeProfiles []string
-
- CurrentLastFMAPIKey string
- CurrentLastFMAPISecret string
- DefaultListenBrainzURL string
- SelectedUser *db.User
-
- Podcasts []*db.Podcast
- InternetRadioStations []*db.InternetRadioStation
-
- CurrentBindUID string
- CurrentFQDN string
- CurrentPort string
- CurrentNoTLS string
- CurrentBaseDN string
- CurrentFilter string
-
- // avatar
- Avatar []byte
-}
-
-type Response struct {
- // code is 200
- template string
- data *templateData
- // code is 303
- redirect string
- flashN []string // normal
- flashW []string // warning
- // code is >= 400
- code int
- err string
-}
-
-type (
- handlerAdmin func(r *http.Request) *Response
- handlerAdminRaw func(w http.ResponseWriter, r *http.Request)
-)
-
-func (c *Controller) H(h handlerAdmin) http.Handler {
- // TODO: break this up a bit
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- resp := h(r)
- session, ok := r.Context().Value(CtxSession).(*sessions.Session)
- if ok {
- sessAddFlashN(session, resp.flashN)
- sessAddFlashW(session, resp.flashW)
- if err := session.Save(r, w); err != nil {
- http.Error(w, fmt.Sprintf("error saving session: %v", err), 500)
- return
- }
- }
- if resp.redirect != "" {
- to := resp.redirect
- if strings.HasPrefix(to, "/") {
- to = c.Path(to)
- }
- http.Redirect(w, r, to, http.StatusSeeOther)
- return
- }
- if resp.err != "" {
- http.Error(w, resp.err, resp.code)
- return
- }
- if resp.template == "" {
- http.Error(w, "useless handler return", 500)
- return
- }
-
- if resp.data == nil {
- resp.data = &templateData{}
- }
- resp.data.Version = gonic.Version
- if session != nil {
- resp.data.Flashes = session.Flashes()
- if err := session.Save(r, w); err != nil {
- http.Error(w, fmt.Sprintf("error saving session: %v", err), 500)
- return
- }
- }
- if user, ok := r.Context().Value(CtxUser).(*db.User); ok {
- resp.data.User = user
- }
-
- buff := c.buffPool.Get()
- defer c.buffPool.Put(buff)
- if err := c.template.ExecuteTemplate(buff, resp.template, resp.data); err != nil {
- http.Error(w, fmt.Sprintf("executing template: %v", err), 500)
- return
- }
-
- w.Header().Set("Content-Type", "text/html; charset=utf-8")
- if resp.code != 0 {
- w.WriteHeader(resp.code)
- }
- if _, err := buff.WriteTo(w); err != nil {
- log.Printf("error writing to response buffer: %v\n", err)
- }
- })
-}
-
-func (c *Controller) HR(h handlerAdminRaw) http.Handler {
- return http.HandlerFunc(h)
-}
-
-// ## begin utilities
-// ## begin utilities
-// ## begin utilities
+// utilities
type FlashType string
@@ -276,9 +394,7 @@ func sessLogSave(s *sessions.Session, w http.ResponseWriter, r *http.Request) {
}
}
-// ## begin validation
-// ## begin validation
-// ## begin validation
+// validation
var (
errValiNoUsername = errors.New("please enter a username")
diff --git a/server/ctrladmin/handlers.go b/server/ctrladmin/handlers.go
index a8a1e4e..40a78bb 100644
--- a/server/ctrladmin/handlers.go
+++ b/server/ctrladmin/handlers.go
@@ -5,9 +5,7 @@ import (
"bytes"
"fmt"
"image"
- _ "image/gif" // to decode uploaded GIF avatars
"image/jpeg"
- _ "image/png" // to decode uploaded PNG avatars
"log"
"net/http"
"net/url"
@@ -19,19 +17,12 @@ import (
"github.com/nfnt/resize"
"go.senan.xyz/gonic/db"
+ "go.senan.xyz/gonic/handlerutil"
+ "go.senan.xyz/gonic/listenbrainz"
"go.senan.xyz/gonic/scanner"
- "go.senan.xyz/gonic/scrobble/listenbrainz"
"go.senan.xyz/gonic/transcode"
)
-func doScan(scanner *scanner.Scanner, opts scanner.ScanOptions) {
- go func() {
- if _, err := scanner.ScanAndClean(opts); err != nil {
- log.Printf("error while scanning: %v\n", err)
- }
- }()
-}
-
func (c *Controller) ServeNotFound(_ *http.Request) *Response {
return &Response{template: "not_found.tmpl", code: 404}
}
@@ -45,35 +36,33 @@ func (c *Controller) ServeHome(r *http.Request) *Response {
data := &templateData{}
// stats box
- c.DB.Model(&db.Artist{}).Count(&data.ArtistCount)
- c.DB.Model(&db.Album{}).Count(&data.AlbumCount)
- c.DB.Table("tracks").Count(&data.TrackCount)
+ data.Stats, _ = c.dbc.Stats()
// lastfm box
- data.RequestRoot = c.BaseURL(r)
- data.CurrentLastFMAPIKey, _ = c.DB.GetSetting(db.LastFMAPIKey)
+ data.RequestRoot = handlerutil.BaseURL(r)
+ data.CurrentLastFMAPIKey, _ = c.dbc.GetSetting(db.LastFMAPIKey)
data.DefaultListenBrainzURL = listenbrainz.BaseURL
// users box
- allUsersQ := c.DB.DB
+ allUsersQ := c.dbc.DB
if !user.IsAdmin {
allUsersQ = allUsersQ.Where("name=?", user.Name)
}
allUsersQ.Find(&data.AllUsers)
// recent folders box
- c.DB.
+ c.dbc.
Order("created_at DESC").
- Limit(20).
+ Limit(10).
Find(&data.RecentFolders)
- data.IsScanning = c.Scanner.IsScanning()
- if tStr, _ := c.DB.GetSetting(db.LastScanTime); tStr != "" {
+ data.IsScanning = c.scanner.IsScanning()
+ if tStr, _ := c.dbc.GetSetting(db.LastScanTime); tStr != "" {
i, _ := strconv.ParseInt(tStr, 10, 64)
data.LastScanTime = time.Unix(i, 0)
}
// transcoding box
- c.DB.
+ c.dbc.
Where("user_id=?", user.ID).
Find(&data.TranscodePreferences)
for profile := range transcode.UserProfiles {
@@ -81,10 +70,10 @@ func (c *Controller) ServeHome(r *http.Request) *Response {
}
sort.Strings(data.TranscodeProfiles)
// podcasts box
- c.DB.Find(&data.Podcasts)
+ c.dbc.Find(&data.Podcasts)
// internet radio box
- c.DB.Find(&data.InternetRadioStations)
+ c.dbc.Find(&data.InternetRadioStations)
return &Response{
template: "home.tmpl",
@@ -97,15 +86,7 @@ func (c *Controller) ServeLinkLastFMDo(r *http.Request) *Response {
if token == "" {
return &Response{code: 400, err: "please provide a token"}
}
- apiKey, err := c.DB.GetSetting(db.LastFMAPIKey)
- if err != nil {
- return &Response{redirect: r.Referer(), flashW: []string{fmt.Sprintf("couldn't get api key: %v", err)}}
- }
- secret, err := c.DB.GetSetting(db.LastFMSecret)
- if err != nil {
- return &Response{redirect: r.Referer(), flashW: []string{fmt.Sprintf("couldn't get secret: %v", err)}}
- }
- sessionKey, err := c.lastfmClient.GetSession(apiKey, secret, token)
+ sessionKey, err := c.lastfmClient.GetSession(token)
if err != nil {
return &Response{
redirect: "/admin/home",
@@ -114,7 +95,7 @@ func (c *Controller) ServeLinkLastFMDo(r *http.Request) *Response {
}
user := r.Context().Value(CtxUser).(*db.User)
user.LastFMSession = sessionKey
- if err := c.DB.Save(user).Error; err != nil {
+ if err := c.dbc.Save(user).Error; err != nil {
return &Response{redirect: r.Referer(), flashW: []string{fmt.Sprintf("save user: %v", err)}}
}
return &Response{redirect: "/admin/home"}
@@ -123,7 +104,7 @@ func (c *Controller) ServeLinkLastFMDo(r *http.Request) *Response {
func (c *Controller) ServeUnlinkLastFMDo(r *http.Request) *Response {
user := r.Context().Value(CtxUser).(*db.User)
user.LastFMSession = ""
- if err := c.DB.Save(user).Error; err != nil {
+ if err := c.dbc.Save(user).Error; err != nil {
return &Response{redirect: r.Referer(), flashW: []string{fmt.Sprintf("save user: %v", err)}}
}
return &Response{redirect: "/admin/home"}
@@ -141,7 +122,7 @@ func (c *Controller) ServeLinkListenBrainzDo(r *http.Request) *Response {
user := r.Context().Value(CtxUser).(*db.User)
user.ListenBrainzURL = url
user.ListenBrainzToken = token
- if err := c.DB.Save(user).Error; err != nil {
+ if err := c.dbc.Save(user).Error; err != nil {
return &Response{redirect: r.Referer(), flashW: []string{fmt.Sprintf("save user: %v", err)}}
}
return &Response{redirect: "/admin/home"}
@@ -151,7 +132,7 @@ func (c *Controller) ServeUnlinkListenBrainzDo(r *http.Request) *Response {
user := r.Context().Value(CtxUser).(*db.User)
user.ListenBrainzURL = ""
user.ListenBrainzToken = ""
- if err := c.DB.Save(user).Error; err != nil {
+ if err := c.dbc.Save(user).Error; err != nil {
return &Response{redirect: r.Referer(), flashW: []string{fmt.Sprintf("save user: %v", err)}}
}
return &Response{redirect: "/admin/home"}
@@ -302,7 +283,7 @@ func (c *Controller) ServeChangeUsernameDo(r *http.Request) *Response {
}
}
user.Name = usernameNew
- if err := c.DB.Save(user).Error; err != nil {
+ if err := c.dbc.Save(user).Error; err != nil {
return &Response{redirect: r.Referer(), flashW: []string{fmt.Sprintf("save username: %v", err)}}
}
return &Response{redirect: "/admin/home"}
@@ -335,7 +316,7 @@ func (c *Controller) ServeChangePasswordDo(r *http.Request) *Response {
}
}
user.Password = passwordOne
- if err := c.DB.Save(user).Error; err != nil {
+ if err := c.dbc.Save(user).Error; err != nil {
return &Response{redirect: r.Referer(), flashW: []string{fmt.Sprintf("save user: %v", err)}}
}
return &Response{redirect: "/admin/home"}
@@ -367,7 +348,7 @@ func (c *Controller) ServeChangeAvatarDo(r *http.Request) *Response {
}
}
user.Avatar = avatar
- if err := c.DB.Save(user).Error; err != nil {
+ if err := c.dbc.Save(user).Error; err != nil {
return &Response{redirect: r.Referer(), flashW: []string{fmt.Sprintf("save user: %v", err)}}
}
return &Response{
@@ -382,7 +363,7 @@ func (c *Controller) ServeDeleteAvatarDo(r *http.Request) *Response {
return &Response{code: 400, err: err.Error()}
}
user.Avatar = nil
- if err := c.DB.Save(user).Error; err != nil {
+ if err := c.dbc.Save(user).Error; err != nil {
return &Response{redirect: r.Referer(), flashW: []string{fmt.Sprintf("save user: %v", err)}}
}
return &Response{
@@ -415,7 +396,7 @@ func (c *Controller) ServeDeleteUserDo(r *http.Request) *Response {
flashW: []string{"can't delete the admin user"},
}
}
- if err := c.DB.Delete(user).Error; err != nil {
+ if err := c.dbc.Delete(user).Error; err != nil {
return &Response{redirect: r.Referer(), flashW: []string{fmt.Sprintf("delete user: %v", err)}}
}
return &Response{redirect: "/admin/home"}
@@ -445,10 +426,10 @@ func (c *Controller) ServeCreateUserDo(r *http.Request) *Response {
Name: username,
Password: passwordOne,
}
- if err := c.DB.Create(&user).Error; err != nil {
+ if err := c.dbc.Create(&user).Error; err != nil {
return &Response{
redirect: r.Referer(),
- flashW: []string{fmt.Sprintf("could not create user `%s`: %v", username, err)},
+ flashW: []string{fmt.Sprintf("could not create user %q: %v", username, err)},
}
}
return &Response{redirect: "/admin/home"}
@@ -457,10 +438,10 @@ func (c *Controller) ServeCreateUserDo(r *http.Request) *Response {
func (c *Controller) ServeUpdateLastFMAPIKey(r *http.Request) *Response {
data := &templateData{}
var err error
- if data.CurrentLastFMAPIKey, err = c.DB.GetSetting(db.LastFMAPIKey); err != nil {
+ if data.CurrentLastFMAPIKey, err = c.dbc.GetSetting(db.LastFMAPIKey); err != nil {
return &Response{redirect: r.Referer(), flashW: []string{fmt.Sprintf("couldn't get api key: %v", err)}}
}
- if data.CurrentLastFMAPISecret, err = c.DB.GetSetting(db.LastFMSecret); err != nil {
+ if data.CurrentLastFMAPISecret, err = c.dbc.GetSetting(db.LastFMSecret); err != nil {
return &Response{redirect: r.Referer(), flashW: []string{fmt.Sprintf("couldn't get secret: %v", err)}}
}
return &Response{
@@ -478,17 +459,17 @@ func (c *Controller) ServeUpdateLastFMAPIKeyDo(r *http.Request) *Response {
flashW: []string{err.Error()},
}
}
- if err := c.DB.SetSetting(db.LastFMAPIKey, apiKey); err != nil {
+ if err := c.dbc.SetSetting(db.LastFMAPIKey, apiKey); err != nil {
return &Response{redirect: r.Referer(), flashW: []string{fmt.Sprintf("couldn't set api key: %v", err)}}
}
- if err := c.DB.SetSetting(db.LastFMSecret, secret); err != nil {
+ if err := c.dbc.SetSetting(db.LastFMSecret, secret); err != nil {
return &Response{redirect: r.Referer(), flashW: []string{fmt.Sprintf("couldn't set secret: %v", err)}}
}
return &Response{redirect: "/admin/home"}
}
func (c *Controller) ServeStartScanIncDo(_ *http.Request) *Response {
- defer doScan(c.Scanner, scanner.ScanOptions{})
+ defer doScan(c.scanner, scanner.ScanOptions{})
return &Response{
redirect: "/admin/home",
flashN: []string{"incremental scan started. refresh for results"},
@@ -496,7 +477,7 @@ func (c *Controller) ServeStartScanIncDo(_ *http.Request) *Response {
}
func (c *Controller) ServeStartScanFullDo(_ *http.Request) *Response {
- defer doScan(c.Scanner, scanner.ScanOptions{IsFull: true})
+ defer doScan(c.scanner, scanner.ScanOptions{IsFull: true})
return &Response{
redirect: "/admin/home",
flashN: []string{"full scan started. refresh for results"},
@@ -518,7 +499,7 @@ func (c *Controller) ServeCreateTranscodePrefDo(r *http.Request) *Response {
Client: client,
Profile: profile,
}
- if err := c.DB.Create(&pref).Error; err != nil {
+ if err := c.dbc.Create(&pref).Error; err != nil {
return &Response{
redirect: "/admin/home",
flashW: []string{fmt.Sprintf("could not create preference: %v", err)},
@@ -533,7 +514,7 @@ func (c *Controller) ServeDeleteTranscodePrefDo(r *http.Request) *Response {
if client == "" {
return &Response{code: 400, err: "please provide a client"}
}
- c.DB.
+ c.dbc.
Where("user_id=? AND client=?", user.ID, client).
Delete(db.TranscodePreference{})
return &Response{
@@ -551,7 +532,7 @@ func (c *Controller) ServePodcastAddDo(r *http.Request) *Response {
flashW: []string{fmt.Sprintf("could not create feed: %v", err)},
}
}
- if _, err := c.Podcasts.AddNewPodcast(rssURL, feed); err != nil {
+ if _, err := c.podcasts.AddNewPodcast(rssURL, feed); err != nil {
return &Response{
redirect: "/admin/home",
flashW: []string{fmt.Sprintf("could not create feed: %v", err)},
@@ -567,7 +548,7 @@ func (c *Controller) ServePodcastDownloadDo(r *http.Request) *Response {
if err != nil {
return &Response{code: 400, err: "please provide a valid podcast id"}
}
- if err := c.Podcasts.DownloadPodcastAll(id); err != nil {
+ if err := c.podcasts.DownloadPodcastAll(id); err != nil {
return &Response{redirect: r.Referer(), flashW: []string{fmt.Sprintf("error downloading: %v", err)}}
}
return &Response{
@@ -591,7 +572,7 @@ func (c *Controller) ServePodcastUpdateDo(r *http.Request) *Response {
default:
return &Response{code: 400, err: "please provide a valid podcast download type"}
}
- if err := c.Podcasts.SetAutoDownload(id, setting); err != nil {
+ if err := c.podcasts.SetAutoDownload(id, setting); err != nil {
return &Response{
flashW: []string{fmt.Sprintf("could not update auto download setting: %v", err)},
code: 400,
@@ -608,7 +589,7 @@ func (c *Controller) ServePodcastDeleteDo(r *http.Request) *Response {
if err != nil {
return &Response{code: 400, err: "please provide a valid podcast id"}
}
- if err := c.Podcasts.DeletePodcast(id); err != nil {
+ if err := c.podcasts.DeletePodcast(id); err != nil {
return &Response{redirect: r.Referer(), flashW: []string{fmt.Sprintf("error deleting: %v", err)}}
}
return &Response{
@@ -639,7 +620,7 @@ func (c *Controller) ServeInternetRadioStationAddDo(r *http.Request) *Response {
station.StreamURL = streamURL
station.Name = name
station.HomepageURL = homepageURL
- if err := c.DB.Save(&station).Error; err != nil {
+ if err := c.dbc.Save(&station).Error; err != nil {
return &Response{redirect: r.Referer(), flashW: []string{fmt.Sprintf("error saving station: %v", err)}}
}
@@ -682,14 +663,14 @@ func (c *Controller) ServeInternetRadioStationUpdateDo(r *http.Request) *Respons
}
var station db.InternetRadioStation
- if err := c.DB.Where("id=?", stationID).First(&station).Error; err != nil {
+ if err := c.dbc.Where("id=?", stationID).First(&station).Error; err != nil {
return &Response{redirect: r.Referer(), flashW: []string{fmt.Sprintf("find station by id: %v", err)}}
}
station.StreamURL = streamURL
station.Name = name
station.HomepageURL = homepageURL
- if err := c.DB.Save(&station).Error; err != nil {
+ if err := c.dbc.Save(&station).Error; err != nil {
return &Response{code: 500, err: "please provide a valid internet radio station id"}
}
@@ -705,11 +686,11 @@ func (c *Controller) ServeInternetRadioStationDeleteDo(r *http.Request) *Respons
}
var station db.InternetRadioStation
- if err := c.DB.Where("id=?", stationID).First(&station).Error; err != nil {
+ if err := c.dbc.Where("id=?", stationID).First(&station).Error; err != nil {
return &Response{redirect: r.Referer(), flashW: []string{fmt.Sprintf("find station by id: %v", err)}}
}
- if err := c.DB.Where("id=?", stationID).Delete(&db.InternetRadioStation{}).Error; err != nil {
+ if err := c.dbc.Where("id=?", stationID).Delete(&db.InternetRadioStation{}).Error; err != nil {
return &Response{redirect: r.Referer(), flashW: []string{fmt.Sprintf("deleting radio station: %v", err)}}
}
@@ -748,6 +729,14 @@ func selectedUserIfAdmin(c *Controller, r *http.Request) (*db.User, error) {
if !user.IsAdmin && user.Name != selectedUsername {
return nil, fmt.Errorf("must be admin to perform actions for other users")
}
- selectedUser := c.DB.GetUserByName(selectedUsername)
+ selectedUser := c.dbc.GetUserByName(selectedUsername)
return selectedUser, nil
}
+
+func doScan(scanner *scanner.Scanner, opts scanner.ScanOptions) {
+ go func() {
+ if _, err := scanner.ScanAndClean(opts); err != nil {
+ log.Printf("error while scanning: %v\n", err)
+ }
+ }()
+}
diff --git a/server/ctrladmin/handlers_raw.go b/server/ctrladmin/handlers_raw.go
index adbf1eb..49d9e2a 100644
--- a/server/ctrladmin/handlers_raw.go
+++ b/server/ctrladmin/handlers_raw.go
@@ -16,7 +16,7 @@ func (c *Controller) ServeLoginDo(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, r.Referer(), http.StatusSeeOther)
return
}
- user := c.DB.GetUserByName(username)
+ user := c.dbc.GetUserByName(username)
if user == nil || password != user.Password {
sessAddFlashW(session, []string{"invalid username / password"})
sessLogSave(session, w, r)
@@ -28,12 +28,12 @@ func (c *Controller) ServeLoginDo(w http.ResponseWriter, r *http.Request) {
// session and put the row into the request context
session.Values["user"] = user.ID
sessLogSave(session, w, r)
- http.Redirect(w, r, c.Path("/admin/home"), http.StatusSeeOther)
+ http.Redirect(w, r, c.resolveProxyPath("/admin/home"), http.StatusSeeOther)
}
func (c *Controller) ServeLogout(w http.ResponseWriter, r *http.Request) {
session := r.Context().Value(CtxSession).(*sessions.Session)
session.Options.MaxAge = -1
sessLogSave(session, w, r)
- http.Redirect(w, r, c.Path("/admin/login"), http.StatusSeeOther)
+ http.Redirect(w, r, c.resolveProxyPath("/admin/login"), http.StatusSeeOther)
}
diff --git a/server/ctrladmin/middleware.go b/server/ctrladmin/middleware.go
deleted file mode 100644
index db50f64..0000000
--- a/server/ctrladmin/middleware.go
+++ /dev/null
@@ -1,65 +0,0 @@
-package ctrladmin
-
-import (
- "context"
- "fmt"
- "net/http"
-
- "github.com/gorilla/sessions"
-
- "go.senan.xyz/gonic"
- "go.senan.xyz/gonic/db"
-)
-
-func (c *Controller) WithSession(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- session, err := c.sessDB.Get(r, gonic.Name)
- if err != nil {
- http.Error(w, fmt.Sprintf("error getting session: %s", err), 500)
- return
- }
- withSession := context.WithValue(r.Context(), CtxSession, session)
- next.ServeHTTP(w, r.WithContext(withSession))
- })
-}
-
-func (c *Controller) WithUserSession(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- // session exists at this point
- session := r.Context().Value(CtxSession).(*sessions.Session)
- userID, ok := session.Values["user"].(int)
- if !ok {
- sessAddFlashW(session, []string{"you are not authenticated"})
- sessLogSave(session, w, r)
- http.Redirect(w, r, c.Path("/admin/login"), http.StatusSeeOther)
- return
- }
- // take username from sesion and add the user row to the context
- user := c.DB.GetUserByID(userID)
- if user == nil {
- // the username in the client's session no longer relates to a
- // user in the database (maybe the user was deleted)
- session.Options.MaxAge = -1
- sessLogSave(session, w, r)
- http.Redirect(w, r, c.Path("/admin/login"), http.StatusSeeOther)
- return
- }
- withUser := context.WithValue(r.Context(), CtxUser, user)
- next.ServeHTTP(w, r.WithContext(withUser))
- })
-}
-
-func (c *Controller) WithAdminSession(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- // session and user exist at this point
- session := r.Context().Value(CtxSession).(*sessions.Session)
- user := r.Context().Value(CtxUser).(*db.User)
- if !user.IsAdmin {
- sessAddFlashW(session, []string{"you are not an admin"})
- sessLogSave(session, w, r)
- http.Redirect(w, r, c.Path("/admin/login"), http.StatusSeeOther)
- return
- }
- next.ServeHTTP(w, r)
- })
-}
diff --git a/server/ctrladmin/routes.go b/server/ctrladmin/routes.go
deleted file mode 100644
index 194644a..0000000
--- a/server/ctrladmin/routes.go
+++ /dev/null
@@ -1,64 +0,0 @@
-package ctrladmin
-
-import (
- "net/http"
-
- "github.com/gorilla/mux"
- "go.senan.xyz/gonic/server/ctrladmin/adminui"
-)
-
-func AddRoutes(c *Controller, r *mux.Router) {
- // public routes (creates session)
- r.Use(c.WithSession)
- r.Handle("/login", c.H(c.ServeLogin))
- r.Handle("/login_do", c.HR(c.ServeLoginDo)) // "raw" handler, updates session
-
- staticHandler := http.StripPrefix("/admin", http.FileServer(http.FS(adminui.StaticFS)))
- r.PathPrefix("/static").Handler(staticHandler)
-
- // user routes (if session is valid)
- routUser := r.NewRoute().Subrouter()
- routUser.Use(c.WithUserSession)
- routUser.Handle("/logout", c.HR(c.ServeLogout)) // "raw" handler, updates session
- routUser.Handle("/home", c.H(c.ServeHome))
- routUser.Handle("/ldap", c.H(c.ServeLDAPConfig))
- routUser.Handle("/ldap_do", c.H(c.ServeLDAPConfigDo))
- routUser.Handle("/change_username", c.H(c.ServeChangeUsername))
- routUser.Handle("/change_username_do", c.H(c.ServeChangeUsernameDo))
- routUser.Handle("/change_password", c.H(c.ServeChangePassword))
- routUser.Handle("/change_password_do", c.H(c.ServeChangePasswordDo))
- routUser.Handle("/change_avatar", c.H(c.ServeChangeAvatar))
- routUser.Handle("/change_avatar_do", c.H(c.ServeChangeAvatarDo))
- routUser.Handle("/delete_avatar_do", c.H(c.ServeDeleteAvatarDo))
- routUser.Handle("/delete_user", c.H(c.ServeDeleteUser))
- routUser.Handle("/delete_user_do", c.H(c.ServeDeleteUserDo))
- routUser.Handle("/link_lastfm_do", c.H(c.ServeLinkLastFMDo))
- routUser.Handle("/unlink_lastfm_do", c.H(c.ServeUnlinkLastFMDo))
- routUser.Handle("/link_listenbrainz_do", c.H(c.ServeLinkListenBrainzDo))
- routUser.Handle("/unlink_listenbrainz_do", c.H(c.ServeUnlinkListenBrainzDo))
- routUser.Handle("/create_transcode_pref_do", c.H(c.ServeCreateTranscodePrefDo))
- routUser.Handle("/delete_transcode_pref_do", c.H(c.ServeDeleteTranscodePrefDo))
-
- // admin routes (if session is valid, and is admin)
- routAdmin := routUser.NewRoute().Subrouter()
- routAdmin.Use(c.WithAdminSession)
- routAdmin.Handle("/create_user", c.H(c.ServeCreateUser))
- routAdmin.Handle("/create_user_do", c.H(c.ServeCreateUserDo))
- routAdmin.Handle("/update_lastfm_api_key", c.H(c.ServeUpdateLastFMAPIKey))
- routAdmin.Handle("/update_lastfm_api_key_do", c.H(c.ServeUpdateLastFMAPIKeyDo))
- routAdmin.Handle("/start_scan_inc_do", c.H(c.ServeStartScanIncDo))
- routAdmin.Handle("/start_scan_full_do", c.H(c.ServeStartScanFullDo))
- routAdmin.Handle("/add_podcast_do", c.H(c.ServePodcastAddDo))
- routAdmin.Handle("/delete_podcast_do", c.H(c.ServePodcastDeleteDo))
- routAdmin.Handle("/download_podcast_do", c.H(c.ServePodcastDownloadDo))
- routAdmin.Handle("/update_podcast_do", c.H(c.ServePodcastUpdateDo))
- routAdmin.Handle("/add_internet_radio_station_do", c.H(c.ServeInternetRadioStationAddDo))
- routAdmin.Handle("/delete_internet_radio_station_do", c.H(c.ServeInternetRadioStationDeleteDo))
- routAdmin.Handle("/update_internet_radio_station_do", c.H(c.ServeInternetRadioStationUpdateDo))
-
- // middlewares should be run for not found handler
- // https://github.com/gorilla/mux/issues/416
- notFoundHandler := c.H(c.ServeNotFound)
- notFoundRoute := r.NewRoute().Handler(notFoundHandler)
- r.NotFoundHandler = notFoundRoute.GetHandler()
-}
diff --git a/server/ctrlbase/ctrl.go b/server/ctrlbase/ctrl.go
deleted file mode 100644
index 7d8e1b5..0000000
--- a/server/ctrlbase/ctrl.go
+++ /dev/null
@@ -1,119 +0,0 @@
-package ctrlbase
-
-import (
- "fmt"
- "log"
- "net/http"
- "path"
-
- "go.senan.xyz/gonic/db"
- "go.senan.xyz/gonic/playlist"
- "go.senan.xyz/gonic/scanner"
-)
-
-type statusWriter struct {
- http.ResponseWriter
- status int
-}
-
-func (w *statusWriter) WriteHeader(status int) {
- w.status = status
- w.ResponseWriter.WriteHeader(status)
-}
-
-func (w *statusWriter) Write(b []byte) (int, error) {
- if w.status == 0 {
- w.status = 200
- }
- return w.ResponseWriter.Write(b)
-}
-
-func statusToBlock(code int) string {
- var bg int
- switch {
- case 200 <= code && code <= 299:
- bg = 42 // bright green, ok
- case 300 <= code && code <= 399:
- bg = 46 // bright cyan, redirect
- case 400 <= code && code <= 499:
- bg = 43 // bright orange, client error
- case 500 <= code && code <= 599:
- bg = 41 // bright red, server error
- default:
- bg = 47 // bright white (grey)
- }
- return fmt.Sprintf("\u001b[%d;1m %d \u001b[0m", bg, code)
-}
-
-type Controller struct {
- DB *db.DB
- PlaylistStore *playlist.Store
- Scanner *scanner.Scanner
- ProxyPrefix string
-}
-
-// Path returns a URL path with the proxy prefix included
-func (c *Controller) Path(rel string) string {
- return path.Join(c.ProxyPrefix, rel)
-}
-
-func (c *Controller) BaseURL(r *http.Request) string {
- protocol := "http"
- if r.TLS != nil {
- protocol = "https"
- }
- scheme := firstExisting(
- protocol, // fallback
- r.Header.Get("X-Forwarded-Proto"),
- r.Header.Get("X-Forwarded-Scheme"),
- r.URL.Scheme,
- )
- host := firstExisting(
- "localhost:4747", // fallback
- r.Header.Get("X-Forwarded-Host"),
- r.Host,
- )
- return fmt.Sprintf("%s://%s", scheme, host)
-}
-
-func (c *Controller) WithLogging(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- // this is (should be) the first middleware. pass right though it
- // by calling `next` first instead of last. when it completes all
- // other middlewares and the custom ResponseWriter has been written
- sw := &statusWriter{ResponseWriter: w}
- next.ServeHTTP(sw, r)
-
- // sanitise password
- if q := r.URL.Query(); q.Get("p") != "" {
- q.Set("p", "REDACTED")
- r.URL.RawQuery = q.Encode()
- }
- log.Printf("response %s for `%v`", statusToBlock(sw.status), r.URL)
- })
-}
-
-func (c *Controller) WithCORS(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- w.Header().Set("Access-Control-Allow-Origin", "*")
- w.Header().Set("Access-Control-Allow-Methods",
- "POST, GET, OPTIONS, PUT, DELETE",
- )
- w.Header().Set("Access-Control-Allow-Headers",
- "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization",
- )
- if r.Method == "OPTIONS" {
- return
- }
- next.ServeHTTP(w, r)
- })
-}
-
-func firstExisting(or string, strings ...string) string {
- for _, s := range strings {
- if s != "" {
- return s
- }
- }
- return or
-}
diff --git a/server/ctrlbase/routes.go b/server/ctrlbase/routes.go
deleted file mode 100644
index 7ade2f1..0000000
--- a/server/ctrlbase/routes.go
+++ /dev/null
@@ -1,34 +0,0 @@
-package ctrlbase
-
-import (
- "fmt"
- "net/http"
-
- "github.com/gorilla/handlers"
- "github.com/gorilla/mux"
-)
-
-func AddRoutes(c *Controller, r *mux.Router, logHTTP bool) {
- if logHTTP {
- r.Use(c.WithLogging)
- }
- r.Use(c.WithCORS)
- r.Use(handlers.RecoveryHandler(handlers.PrintRecoveryStack(true)))
-
- r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
- adminHome := c.Path("/admin/home")
- http.Redirect(w, r, adminHome, http.StatusSeeOther)
- })
- // misc subsonic routes without /rest prefix
- r.HandleFunc("/settings.view", func(w http.ResponseWriter, r *http.Request) {
- adminHome := c.Path("/admin/home")
- http.Redirect(w, r, adminHome, http.StatusSeeOther)
- })
- r.HandleFunc("/musicFolderSettings.view", func(w http.ResponseWriter, r *http.Request) {
- restScan := c.Path(fmt.Sprintf("/rest/startScan.view?%s", r.URL.Query().Encode()))
- http.Redirect(w, r, restScan, http.StatusSeeOther)
- })
- r.HandleFunc("/ping", func(w http.ResponseWriter, r *http.Request) {
- fmt.Fprint(w, "OK")
- })
-}
diff --git a/server/ctrlsubsonic/ctrl.go b/server/ctrlsubsonic/ctrl.go
index 7fc9234..16851d5 100644
--- a/server/ctrlsubsonic/ctrl.go
+++ b/server/ctrlsubsonic/ctrl.go
@@ -1,7 +1,9 @@
-// Package ctrlsubsonic provides HTTP handlers for subsonic API
package ctrlsubsonic
import (
+ "context"
+ "crypto/md5"
+ "encoding/hex"
"encoding/json"
"encoding/xml"
"fmt"
@@ -9,12 +11,16 @@ import (
"log"
"net/http"
+ "go.senan.xyz/gonic/db"
+ "go.senan.xyz/gonic/handlerutil"
+ "go.senan.xyz/gonic/infocache/albuminfocache"
+ "go.senan.xyz/gonic/infocache/artistinfocache"
"go.senan.xyz/gonic/jukebox"
- "go.senan.xyz/gonic/podcasts"
+ "go.senan.xyz/gonic/lastfm"
+ "go.senan.xyz/gonic/playlist"
+ "go.senan.xyz/gonic/podcast"
+ "go.senan.xyz/gonic/scanner"
"go.senan.xyz/gonic/scrobble"
- "go.senan.xyz/gonic/scrobble/lastfm"
- "go.senan.xyz/gonic/server/ctrlbase"
- "go.senan.xyz/gonic/server/ctrlsubsonic/artistinfocache"
"go.senan.xyz/gonic/server/ctrlsubsonic/params"
"go.senan.xyz/gonic/server/ctrlsubsonic/spec"
"go.senan.xyz/gonic/transcode"
@@ -32,7 +38,7 @@ type MusicPath struct {
Alias, Path string
}
-func PathsOf(paths []MusicPath) []string {
+func MusicPaths(paths []MusicPath) []string {
var r []string
for _, p := range paths {
r = append(r, p.Path)
@@ -40,23 +46,346 @@ func PathsOf(paths []MusicPath) []string {
return r
}
+type ProxyPathResolver func(in string) string
+
type Controller struct {
- *ctrlbase.Controller
- MusicPaths []MusicPath
- PodcastsPath string
- CacheAudioPath string
- CacheCoverPath string
- Jukebox *jukebox.Jukebox
- Scrobblers []scrobble.Scrobbler
- Podcasts *podcasts.Podcasts
- Transcoder transcode.Transcoder
- LastFMClient *lastfm.Client
- ArtistInfoCache *artistinfocache.ArtistInfoCache
+ *http.ServeMux
+
+ dbc *db.DB
+ scanner *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
+ resolveProxyPath ProxyPathResolver
}
-type metaResponse struct {
- XMLName xml.Name `xml:"subsonic-response" json:"-"`
- *spec.Response `json:"subsonic-response"`
+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, resolveProxyPath ProxyPathResolver) (*Controller, error) {
+ c := Controller{
+ ServeMux: http.NewServeMux(),
+
+ dbc: dbc,
+ scanner: scannr,
+ musicPaths: musicPaths,
+ podcastsPath: podcastsPath,
+ cacheAudioPath: cacheAudioPath,
+ cacheCoverPath: cacheCoverPath,
+ jukebox: jukebox,
+ playlistStore: playlistStore,
+ scrobblers: scrobblers,
+ podcasts: podcasts,
+ transcoder: transcoder,
+ lastFMClient: lastFMClient,
+ artistInfoCache: artistInfoCache,
+ albumInfoCache: albumInfoCache,
+ resolveProxyPath: resolveProxyPath,
+ }
+
+ chain := handlerutil.Chain(
+ withParams,
+ withRequiredParams,
+ withUser(dbc),
+ )
+
+ c.Handle("/getLicense", chain(resp(c.ServeGetLicence)))
+ c.Handle("/ping", chain(resp(c.ServePing)))
+ c.Handle("/getOpenSubsonicExtensions", chain(resp(c.ServeGetOpenSubsonicExtensions)))
+
+ c.Handle("/getMusicFolders", chain(resp(c.ServeGetMusicFolders)))
+ c.Handle("/getScanStatus", chain(resp(c.ServeGetScanStatus)))
+ c.Handle("/scrobble", chain(resp(c.ServeScrobble)))
+ c.Handle("/startScan", chain(resp(c.ServeStartScan)))
+ c.Handle("/getUser", chain(resp(c.ServeGetUser)))
+ c.Handle("/getPlaylists", chain(resp(c.ServeGetPlaylists)))
+ c.Handle("/getPlaylist", chain(resp(c.ServeGetPlaylist)))
+ c.Handle("/createPlaylist", chain(resp(c.ServeCreatePlaylist)))
+ c.Handle("/updatePlaylist", chain(resp(c.ServeUpdatePlaylist)))
+ c.Handle("/deletePlaylist", chain(resp(c.ServeDeletePlaylist)))
+ c.Handle("/savePlayQueue", chain(resp(c.ServeSavePlayQueue)))
+ c.Handle("/getPlayQueue", chain(resp(c.ServeGetPlayQueue)))
+ c.Handle("/getSong", chain(resp(c.ServeGetSong)))
+ c.Handle("/getRandomSongs", chain(resp(c.ServeGetRandomSongs)))
+ c.Handle("/getSongsByGenre", chain(resp(c.ServeGetSongsByGenre)))
+ c.Handle("/jukeboxControl", chain(resp(c.ServeJukebox)))
+ c.Handle("/getBookmarks", chain(resp(c.ServeGetBookmarks)))
+ c.Handle("/createBookmark", chain(resp(c.ServeCreateBookmark)))
+ c.Handle("/deleteBookmark", chain(resp(c.ServeDeleteBookmark)))
+ c.Handle("/getTopSongs", chain(resp(c.ServeGetTopSongs)))
+ c.Handle("/getSimilarSongs", chain(resp(c.ServeGetSimilarSongs)))
+ c.Handle("/getSimilarSongs2", chain(resp(c.ServeGetSimilarSongsTwo)))
+ c.Handle("/getLyrics", chain(resp(c.ServeGetLyrics)))
+
+ // raw
+ c.Handle("/getCoverArt", chain(respRaw(c.ServeGetCoverArt)))
+ c.Handle("/stream", chain(respRaw(c.ServeStream)))
+ c.Handle("/download", chain(respRaw(c.ServeStream)))
+ c.Handle("/getAvatar", chain(respRaw(c.ServeGetAvatar)))
+
+ // browse by tag
+ c.Handle("/getAlbum", chain(resp(c.ServeGetAlbum)))
+ c.Handle("/getAlbumList2", chain(resp(c.ServeGetAlbumListTwo)))
+ c.Handle("/getArtist", chain(resp(c.ServeGetArtist)))
+ c.Handle("/getArtists", chain(resp(c.ServeGetArtists)))
+ c.Handle("/search3", chain(resp(c.ServeSearchThree)))
+ c.Handle("/getStarred2", chain(resp(c.ServeGetStarredTwo)))
+ c.Handle("/getArtistInfo2", chain(resp(c.ServeGetArtistInfoTwo)))
+ c.Handle("/getAlbumInfo2", chain(resp(c.ServeGetAlbumInfoTwo)))
+
+ // browse by folder
+ c.Handle("/getIndexes", chain(resp(c.ServeGetIndexes)))
+ c.Handle("/getMusicDirectory", chain(resp(c.ServeGetMusicDirectory)))
+ c.Handle("/getAlbumList", chain(resp(c.ServeGetAlbumList)))
+ c.Handle("/search2", chain(resp(c.ServeSearchTwo)))
+ c.Handle("/getGenres", chain(resp(c.ServeGetGenres)))
+ c.Handle("/getArtistInfo", chain(resp(c.ServeGetArtistInfo)))
+ c.Handle("/getStarred", chain(resp(c.ServeGetStarred)))
+
+ // star / rating
+ c.Handle("/star", chain(resp(c.ServeStar)))
+ c.Handle("/unstar", chain(resp(c.ServeUnstar)))
+ c.Handle("/setRating", chain(resp(c.ServeSetRating)))
+
+ // podcasts
+ c.Handle("/getPodcasts", chain(resp(c.ServeGetPodcasts)))
+ c.Handle("/getNewestPodcasts", chain(resp(c.ServeGetNewestPodcasts)))
+ c.Handle("/downloadPodcastEpisode", chain(resp(c.ServeDownloadPodcastEpisode)))
+ c.Handle("/createPodcastChannel", chain(resp(c.ServeCreatePodcastChannel)))
+ c.Handle("/refreshPodcasts", chain(resp(c.ServeRefreshPodcasts)))
+ c.Handle("/deletePodcastChannel", chain(resp(c.ServeDeletePodcastChannel)))
+ c.Handle("/deletePodcastEpisode", chain(resp(c.ServeDeletePodcastEpisode)))
+
+ // internet radio
+ c.Handle("/getInternetRadioStations", chain(resp(c.ServeGetInternetRadioStations)))
+ c.Handle("/createInternetRadioStation", chain(resp(c.ServeCreateInternetRadioStation)))
+ c.Handle("/updateInternetRadioStation", chain(resp(c.ServeUpdateInternetRadioStation)))
+ c.Handle("/deleteInternetRadioStation", chain(resp(c.ServeDeleteInternetRadioStation)))
+
+ c.Handle("/", chain(resp(c.ServeNotFound)))
+
+ return &c, nil
+}
+
+type (
+ handlerSubsonic func(r *http.Request) *spec.Response
+ handlerSubsonicRaw func(w http.ResponseWriter, r *http.Request) *spec.Response
+)
+
+func resp(h handlerSubsonic) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if err := writeResp(w, r, h(r)); err != nil {
+ log.Printf("error writing subsonic response: %v\n", err)
+ }
+ })
+}
+
+func respRaw(h handlerSubsonicRaw) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if err := writeResp(w, r, h(w, r)); err != nil {
+ log.Printf("error writing raw subsonic response: %v\n", err)
+ }
+ })
+}
+
+func withParams(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ params := params.New(r)
+ withParams := context.WithValue(r.Context(), CtxParams, params)
+ next.ServeHTTP(w, r.WithContext(withParams))
+ })
+}
+
+func withRequiredParams(next http.Handler) http.Handler {
+ requiredParameters := []string{
+ "u", "c",
+ }
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ params := r.Context().Value(CtxParams).(params.Params)
+ for _, req := range requiredParameters {
+ if _, err := params.Get(req); err != nil {
+ _ = writeResp(w, r, spec.NewError(10, "please provide a %q parameter", req))
+ return
+ }
+ }
+ next.ServeHTTP(w, r)
+ })
+}
+
+func (c *Controller) WithUser(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")
+ password, _ := params.Get("p")
+ token, _ := params.Get("t")
+ salt, _ := params.Get("s")
+
+ passwordAuth := token == "" && salt == ""
+ tokenAuth := password == ""
+ if tokenAuth == passwordAuth {
+ _ = writeResp(w, r, spec.NewError(10,
+ "please provide `t` and `s`, or just `p`"))
+ return
+ }
+ user := c.DB.GetUserByName(username)
+
+ newLDAPUser := false
+ if user == nil {
+ newLDAPUser = true
+
+ // Because the user wasn't found we can now try
+ // to use LDAP. ldapFQDN, err := c.DB.GetSetting("ldap_fqdn")
+ ldapFQDN, err := c.DB.GetSetting("ldap_fqdn")
+
+ if ldapFQDN != "" && err == nil {
+ // The configuration page wouldn't allow these setting to not be set
+ // while LDAP is enabled (a FQDN/IP is set).
+ bindUID, _ := c.DB.GetSetting("ldap_bind_user")
+ bindPWD, _ := c.DB.GetSetting("ldap_bind_user_password")
+ ldapPort, _ := c.DB.GetSetting("ldap_port")
+ baseDN, _ := c.DB.GetSetting("ldap_base_dn")
+ filter, _ := c.DB.GetSetting("ldap_filter")
+ tls, _ := c.DB.GetSetting("ldap_tls")
+
+ // Now, we can try to connect to the LDAP server.
+ l, err := createLDAPconnection(tls, ldapFQDN, ldapPort)
+ if err != nil {
+ // Return a generic error.
+ _ = writeResp(w, r, spec.NewError(0, "Failed to connect to LDAP server."))
+ return
+ }
+ defer l.Close()
+
+ // After we have a connection, let's try binding
+ _, err = l.SimpleBind(&ldap.SimpleBindRequest{
+ Username: fmt.Sprintf("uid=%s,%s", bindUID, baseDN),
+ Password: bindPWD,
+ })
+ if err != nil {
+ log.Println("Failed to bind to LDAP:", err)
+ _ = writeResp(w, r, spec.NewError(40, "Wrong username or password."))
+ return
+ }
+
+ searchReq := ldap.NewSearchRequest(
+ baseDN,
+ ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
+ fmt.Sprintf("(&%s(uid=%s))", filter, ldap.EscapeFilter(username)),
+ []string{"dn"},
+ nil,
+ )
+
+ result, err := l.Search(searchReq)
+ if err != nil {
+ log.Println("failed to query LDAP:", err)
+ }
+
+ if len(result.Entries) > 1 {
+ _ = writeResp(w, r, spec.NewError(40, "Ambiguous user: `%s`", username))
+ } else if len(result.Entries) == 1 {
+ user := db.User{
+ Name: username,
+ Password: "", // no password because we want auth to fail.
+ }
+
+ if err := c.DB.Create(&user).Error; err != nil {
+ fmt.Println("User created via LDAP:", username)
+ }
+ } else {
+ _ = writeResp(w, r, spec.NewError(40, "invalid username `%s`", username))
+ return
+ }
+ } else {
+ _ = writeResp(w, r, spec.NewError(40,
+ "invalid username `%s`", username))
+ return
+ }
+ }
+ var credsOk bool
+ if tokenAuth && !newLDAPUser && user != nil {
+ credsOk = checkCredsToken(user.Password, token, salt)
+ } else if !newLDAPUser && user != nil {
+ credsOk = checkCredsBasic(user.Password, password)
+ }
+ if !credsOk {
+ // Because internal authentication failed, we can now try to use LDAP, if
+ // it was enabled by the user.
+ ldapFQDN, err := c.DB.GetSetting("ldap_fqdn")
+
+ if ldapFQDN != "" && err == nil {
+ // The configuration page wouldn't allow these setting to not be set
+ // while LDAP is enabled (a FQDN/IP is set).
+ ldapPort, _ := c.DB.GetSetting("ldap_port")
+ baseDN, _ := c.DB.GetSetting("ldap_base_dn")
+ tls, _ := c.DB.GetSetting("ldap_tls")
+
+ // Now, we can try to connect to the LDAP server.
+ l, err := createLDAPconnection(tls, ldapFQDN, ldapPort)
+ if err != nil {
+ // Return a generic error.
+ _ = writeResp(w, r, spec.NewError(0, "Failed to connect to LDAP server."))
+ return
+ }
+ defer l.Close()
+
+ // After we have a connection, let's try binding
+ _, err = l.SimpleBind(&ldap.SimpleBindRequest{
+ Username: fmt.Sprintf("uid=%s,%s", username, baseDN),
+ Password: password,
+ })
+
+ if err == nil {
+ withUser := context.WithValue(r.Context(), CtxUser, user)
+ next.ServeHTTP(w, r.WithContext(withUser))
+ return
+ }
+ }
+
+ _ = writeResp(w, r, spec.NewError(40, "invalid password"))
+ return
+ }
+ withUser := context.WithValue(r.Context(), CtxUser, user)
+ next.ServeHTTP(w, r.WithContext(withUser))
+ })
+}
+
+func createLDAPconnection(tls string, fqdn string, port string) (*ldap.Conn, error) {
+ protocol := "ldap"
+ if tls == "true" {
+ protocol = "ldaps"
+ }
+
+ // Now, we can try to connect to the LDAP server.
+ l, err := ldap.DialURL(fmt.Sprintf("%s://%s:%s", protocol, fqdn, port))
+ if err != nil {
+ // Warn the server and return a generic error.
+ log.Println("Failed to connect to LDAP server", err)
+ return nil, err
+ }
+
+ return l, nil
+}
+
+func checkCredsToken(password, token, salt string) bool {
+ toHash := fmt.Sprintf("%s%s", password, salt)
+ hash := md5.Sum([]byte(toHash))
+ expToken := hex.EncodeToString(hash[:])
+ return token == expToken
+}
+
+func checkCredsBasic(password, given string) bool {
+ if len(given) >= 4 && given[:4] == "enc:" {
+ bytes, _ := hex.DecodeString(given[4:])
+ given = string(bytes)
+ }
+ return password == given
}
type errWriter struct {
@@ -79,8 +408,14 @@ func writeResp(w http.ResponseWriter, r *http.Request, resp *spec.Response) erro
log.Printf("subsonic error code %d: %s", resp.Error.Code, resp.Error.Message)
}
- res := metaResponse{Response: resp}
+ var res struct {
+ XMLName xml.Name `xml:"subsonic-response" json:"-"`
+ *spec.Response `json:"subsonic-response"`
+ }
+ res.Response = resp
+
params := r.Context().Value(CtxParams).(params.Params)
+
ew := &errWriter{w: w}
switch v, _ := params.Get("f"); v {
case "json":
@@ -90,6 +425,7 @@ func writeResp(w http.ResponseWriter, r *http.Request, resp *spec.Response) erro
return fmt.Errorf("marshal to json: %w", err)
}
ew.write(data)
+
case "jsonp":
w.Header().Set("Content-Type", "application/javascript")
data, err := json.Marshal(res)
@@ -102,34 +438,16 @@ func writeResp(w http.ResponseWriter, r *http.Request, resp *spec.Response) erro
ew.write([]byte("("))
ew.write(data)
ew.write([]byte(");"))
+
default:
w.Header().Set("Content-Type", "application/xml")
data, err := xml.MarshalIndent(res, "", " ")
if err != nil {
return fmt.Errorf("marshal to xml: %w", err)
}
+
ew.write(data)
}
+
return ew.err
}
-
-type (
- handlerSubsonic func(r *http.Request) *spec.Response
- handlerSubsonicRaw func(w http.ResponseWriter, r *http.Request) *spec.Response
-)
-
-func (c *Controller) H(h handlerSubsonic) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if err := writeResp(w, r, h(r)); err != nil {
- log.Printf("error writing subsonic response: %v\n", err)
- }
- })
-}
-
-func (c *Controller) HR(h handlerSubsonicRaw) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if err := writeResp(w, r, h(w, r)); err != nil {
- log.Printf("error writing raw subsonic response: %v\n", err)
- }
- })
-}
diff --git a/server/ctrlsubsonic/ctrl_test.go b/server/ctrlsubsonic/ctrl_test.go
index e296f80..b0e7fa7 100644
--- a/server/ctrlsubsonic/ctrl_test.go
+++ b/server/ctrlsubsonic/ctrl_test.go
@@ -1,3 +1,4 @@
+//nolint:thelper
package ctrlsubsonic
import (
@@ -8,7 +9,6 @@ import (
"net/http/httptest"
"net/url"
"os"
- "path"
"path/filepath"
"regexp"
"strings"
@@ -19,11 +19,16 @@ import (
"go.senan.xyz/gonic"
"go.senan.xyz/gonic/db"
"go.senan.xyz/gonic/mockfs"
- "go.senan.xyz/gonic/server/ctrlbase"
"go.senan.xyz/gonic/server/ctrlsubsonic/params"
"go.senan.xyz/gonic/transcode"
)
+func TestMain(m *testing.M) {
+ gonic.Version = ""
+ log.SetOutput(io.Discard)
+ os.Exit(m.Run())
+}
+
var testCamelExpr = regexp.MustCompile("([a-z0-9])([A-Z])")
const (
@@ -48,7 +53,7 @@ func makeGoldenPath(test string) string {
snake := testCamelExpr.ReplaceAllString(test, "${1}_${2}")
lower := strings.ToLower(snake)
relPath := strings.ReplaceAll(lower, "/", "_")
- return path.Join("testdata", relPath)
+ return filepath.Join("testdata", relPath)
}
func makeHTTPMock(query url.Values) (*httptest.ResponseRecorder, *http.Request) {
@@ -78,12 +83,16 @@ func makeHTTPMockWithAdmin(query url.Values) (*httptest.ResponseRecorder, *http.
return rr, req
}
-func runQueryCases(t *testing.T, contr *Controller, h handlerSubsonic, cases []*queryCase) {
+func runQueryCases(t *testing.T, h handlerSubsonic, cases []*queryCase) {
t.Helper()
for _, qc := range cases {
+ qc := qc
t.Run(qc.expectPath, func(t *testing.T) {
+ t.Helper()
+ t.Parallel()
+
rr, req := makeHTTPMock(qc.params)
- contr.H(h).ServeHTTP(rr, req)
+ resp(h).ServeHTTP(rr, req)
body := rr.Body.String()
if status := rr.Code; status != http.StatusOK {
t.Fatalf("didn't give a 200\n%s", body)
@@ -92,7 +101,7 @@ func runQueryCases(t *testing.T, contr *Controller, h handlerSubsonic, cases []*
goldenPath := makeGoldenPath(t.Name())
goldenRegen := os.Getenv("GONIC_REGEN")
if goldenRegen == "*" || (goldenRegen != "" && strings.HasPrefix(t.Name(), goldenRegen)) {
- _ = os.WriteFile(goldenPath, []byte(body), 0600)
+ _ = os.WriteFile(goldenPath, []byte(body), 0o600)
t.Logf("golden file %q regenerated for %s", goldenPath, t.Name())
t.SkipNow()
}
@@ -121,14 +130,13 @@ func runQueryCases(t *testing.T, contr *Controller, h handlerSubsonic, cases []*
}
}
-func makeController(t *testing.T) *Controller { return makec(t, []string{""}, false) }
-func makeControllerRoots(t *testing.T, r []string) *Controller { return makec(t, r, false) }
-func makeControllerAudio(t *testing.T) *Controller { return makec(t, []string{""}, true) }
+func makeController(tb testing.TB) *Controller { return makec(tb, []string{""}, false) }
+func makeControllerRoots(tb testing.TB, r []string) *Controller { return makec(tb, r, false) }
-func makec(t *testing.T, roots []string, audio bool) *Controller {
- t.Helper()
+func makec(tb testing.TB, roots []string, audio bool) *Controller {
+ tb.Helper()
- m := mockfs.NewWithDirs(t, roots)
+ m := mockfs.NewWithDirs(tb, roots)
for _, root := range roots {
m.AddItemsPrefixWithCovers(root)
if !audio {
@@ -147,18 +155,11 @@ func makec(t *testing.T, roots []string, audio bool) *Controller {
absRoots = append(absRoots, MusicPath{Path: filepath.Join(m.TmpDir(), root)})
}
- base := &ctrlbase.Controller{DB: m.DB()}
contr := &Controller{
- Controller: base,
- MusicPaths: absRoots,
- Transcoder: transcode.NewFFmpegTranscoder(),
+ dbc: m.DB(),
+ musicPaths: absRoots,
+ transcoder: transcode.NewFFmpegTranscoder(),
}
return contr
}
-
-func TestMain(m *testing.M) {
- gonic.Version = ""
- log.SetOutput(io.Discard)
- os.Exit(m.Run())
-}
diff --git a/server/ctrlsubsonic/handlers_bookmark.go b/server/ctrlsubsonic/handlers_bookmark.go
index 037a87f..7c6822b 100644
--- a/server/ctrlsubsonic/handlers_bookmark.go
+++ b/server/ctrlsubsonic/handlers_bookmark.go
@@ -15,7 +15,7 @@ import (
func (c *Controller) ServeGetBookmarks(r *http.Request) *spec.Response {
user := r.Context().Value(CtxUser).(*db.User)
bookmarks := []*db.Bookmark{}
- err := c.DB.
+ err := c.dbc.
Where("user_id=?", user.ID).
Find(&bookmarks).
Error
@@ -40,7 +40,7 @@ func (c *Controller) ServeGetBookmarks(r *http.Request) *spec.Response {
switch specid.IDT(bookmark.EntryIDType) {
case specid.Track:
var track db.Track
- err := c.DB.
+ err := c.dbc.
Preload("Album").
Find(&track, "id=?", bookmark.EntryID).
Error
@@ -64,14 +64,14 @@ func (c *Controller) ServeCreateBookmark(r *http.Request) *spec.Response {
return spec.NewError(10, "please provide an `id` parameter")
}
bookmark := &db.Bookmark{}
- c.DB.FirstOrCreate(bookmark, db.Bookmark{
+ c.dbc.FirstOrCreate(bookmark, db.Bookmark{
UserID: user.ID,
EntryIDType: string(id.Type),
EntryID: id.Value,
})
bookmark.Comment = params.GetOr("comment", "")
bookmark.Position = params.GetOrInt("position", 0)
- c.DB.Save(bookmark)
+ c.dbc.Save(bookmark)
return spec.NewResponse()
}
@@ -82,7 +82,7 @@ func (c *Controller) ServeDeleteBookmark(r *http.Request) *spec.Response {
if err != nil {
return spec.NewError(10, "please provide an `id` parameter")
}
- c.DB.
+ c.dbc.
Where("user_id=? AND entry_id_type=? AND entry_id=?", user.ID, id.Type, id.Value).
Delete(&db.Bookmark{})
return spec.NewResponse()
diff --git a/server/ctrlsubsonic/handlers_by_folder.go b/server/ctrlsubsonic/handlers_by_folder.go
index 6dd83a3..66f98e9 100644
--- a/server/ctrlsubsonic/handlers_by_folder.go
+++ b/server/ctrlsubsonic/handlers_by_folder.go
@@ -21,16 +21,16 @@ import (
func (c *Controller) ServeGetIndexes(r *http.Request) *spec.Response {
params := r.Context().Value(CtxParams).(params.Params)
user := r.Context().Value(CtxUser).(*db.User)
- rootQ := c.DB.
+ rootQ := c.dbc.
Select("id").
Model(&db.Album{}).
Where("parent_id IS NULL")
- if m := getMusicFolder(c.MusicPaths, params); m != "" {
+ if m := getMusicFolder(c.musicPaths, params); m != "" {
rootQ = rootQ.
Where("root_dir=?", m)
}
var folders []*db.Album
- c.DB.
+ c.dbc.
Select("*, count(sub.id) child_count").
Preload("AlbumStar", "user_id=?", user.ID).
Preload("AlbumRating", "user_id=?", user.ID).
@@ -70,13 +70,13 @@ func (c *Controller) ServeGetMusicDirectory(r *http.Request) *spec.Response {
user := r.Context().Value(CtxUser).(*db.User)
childrenObj := []*spec.TrackChild{}
folder := &db.Album{}
- c.DB.
+ c.dbc.
Preload("AlbumStar", "user_id=?", user.ID).
Preload("AlbumRating", "user_id=?", user.ID).
First(folder, id.Value)
// start looking for child childFolders in the current dir
var childFolders []*db.Album
- c.DB.
+ c.dbc.
Where("parent_id=?", id.Value).
Preload("AlbumStar", "user_id=?", user.ID).
Preload("AlbumRating", "user_id=?", user.ID).
@@ -87,16 +87,17 @@ func (c *Controller) ServeGetMusicDirectory(r *http.Request) *spec.Response {
}
// start looking for child childTracks in the current dir
var childTracks []*db.Track
- c.DB.
+ c.dbc.
Where("album_id=?", id.Value).
Preload("Album").
Preload("Album.Artists").
+ Preload("Artists").
Preload("TrackStar", "user_id=?", user.ID).
Preload("TrackRating", "user_id=?", user.ID).
Order("filename").
Find(&childTracks)
- transcodeMIME, transcodeSuffix := streamGetTransPrefProfile(c.DB, user.ID, params.GetOr("c", ""))
+ transcodeMeta := streamGetTranscodeMeta(c.dbc, user.ID, params.GetOr("c", ""))
for _, ch := range childTracks {
toAppend := spec.NewTCTrackByFolder(ch, folder)
@@ -105,8 +106,7 @@ func (c *Controller) ServeGetMusicDirectory(r *http.Request) *spec.Response {
toAppend.ContentType = "audio/mpeg"
toAppend.Suffix = "mp3"
}
- toAppend.TranscodedContentType = transcodeMIME
- toAppend.TranscodedSuffix = transcodeSuffix
+ toAppend.TranscodeMeta = transcodeMeta
childrenObj = append(childrenObj, toAppend)
}
// respond section
@@ -116,12 +116,12 @@ func (c *Controller) ServeGetMusicDirectory(r *http.Request) *spec.Response {
}
// ServeGetAlbumList handles the getAlbumList view.
-// changes to this function should be reflected in in _by_tags.go's
+// changes to this function should be reflected in _by_tags.go's
// getAlbumListTwo() function
func (c *Controller) ServeGetAlbumList(r *http.Request) *spec.Response {
params := r.Context().Value(CtxParams).(params.Params)
user := r.Context().Value(CtxUser).(*db.User)
- q := c.DB.DB
+ q := c.dbc.DB
switch v, _ := params.Get("type"); v {
case "alphabeticalByArtist":
q = q.Joins(`
@@ -131,8 +131,7 @@ func (c *Controller) ServeGetAlbumList(r *http.Request) *spec.Response {
case "alphabeticalByName":
q = q.Order("right_path")
case "byYear":
- y1, y2 :=
- params.GetOrInt("fromYear", 1800),
+ y1, y2 := params.GetOrInt("fromYear", 1800),
params.GetOrInt("toYear", 2200)
// support some clients sending wrong order like DSub
q = q.Where("tag_year BETWEEN ? AND ?", min(y1, y2), max(y1, y2))
@@ -161,11 +160,14 @@ func (c *Controller) ServeGetAlbumList(r *http.Request) *spec.Response {
case "starred":
q = q.Joins("JOIN album_stars ON albums.id=album_stars.album_id AND album_stars.user_id=?", user.ID)
q = q.Order("right_path")
+ case "highest":
+ q = q.Joins("JOIN album_ratings ON album_ratings.album_id=albums.id AND album_ratings.user_id=?", user.ID)
+ q = q.Order("album_ratings.rating DESC")
default:
- return spec.NewError(10, "unknown value `%s` for parameter 'type'", v)
+ return spec.NewError(10, "unknown value %q for parameter 'type'", v)
}
- if m := getMusicFolder(c.MusicPaths, params); m != "" {
+ if m := getMusicFolder(c.musicPaths, params); m != "" {
q = q.Where("root_dir=?", m)
}
var folders []*db.Album
@@ -207,16 +209,16 @@ func (c *Controller) ServeSearchTwo(r *http.Request) *spec.Response {
results := &spec.SearchResultTwo{}
// search "artists"
- rootQ := c.DB.
+ rootQ := c.dbc.
Select("id").
Model(&db.Album{}).
Where("parent_id IS NULL")
- if m := getMusicFolder(c.MusicPaths, params); m != "" {
+ if m := getMusicFolder(c.musicPaths, params); m != "" {
rootQ = rootQ.Where("root_dir=?", m)
}
var artists []*db.Album
- q := c.DB.Where(`parent_id IN ?`, rootQ.SubQuery())
+ q := c.dbc.Where(`parent_id IN ?`, rootQ.SubQuery())
for _, s := range queries {
q = q.Where(`right_path LIKE ? OR right_path_u_dec LIKE ?`, s, s)
}
@@ -233,15 +235,17 @@ func (c *Controller) ServeSearchTwo(r *http.Request) *spec.Response {
// search "albums"
var albums []*db.Album
- q = c.DB.Joins("JOIN album_artists ON album_artists.album_id=albums.id")
+ q = c.dbc.
+ Joins("JOIN album_artists ON album_artists.album_id=albums.id")
for _, s := range queries {
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).
Offset(params.GetOrInt("albumOffset", 0)).
Limit(params.GetOrInt("albumCount", 20))
- if m := getMusicFolder(c.MusicPaths, params); m != "" {
+ if m := getMusicFolder(c.musicPaths, params); m != "" {
q = q.Where("root_dir=?", m)
}
if err := q.Find(&albums).Error; err != nil {
@@ -253,15 +257,17 @@ func (c *Controller) ServeSearchTwo(r *http.Request) *spec.Response {
// search tracks
var tracks []*db.Track
- q = c.DB.Preload("Album")
+ q = c.dbc.Preload("Album")
for _, s := range queries {
q = q.Where(`filename LIKE ? OR filename LIKE ?`, s, s)
}
- q = q.Preload("TrackStar", "user_id=?", user.ID).
+ q = q.
+ Preload("Artists").
+ Preload("TrackStar", "user_id=?", user.ID).
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.musicPaths, params); m != "" {
q = q.
Joins("JOIN albums ON albums.id=tracks.album_id").
Where("albums.root_dir=?", m)
@@ -270,12 +276,11 @@ func (c *Controller) ServeSearchTwo(r *http.Request) *spec.Response {
return spec.NewError(0, "find tracks: %v", err)
}
- transcodeMIME, transcodeSuffix := streamGetTransPrefProfile(c.DB, user.ID, params.GetOr("c", ""))
+ transcodeMeta := streamGetTranscodeMeta(c.dbc, user.ID, params.GetOr("c", ""))
for _, t := range tracks {
track := spec.NewTCTrackByFolder(t, t.Album)
- track.TranscodedContentType = transcodeMIME
- track.TranscodedSuffix = transcodeSuffix
+ track.TranscodeMeta = transcodeMeta
results.Tracks = append(results.Tracks, track)
}
@@ -295,16 +300,16 @@ func (c *Controller) ServeGetStarred(r *http.Request) *spec.Response {
results := &spec.Starred{}
// "artists"
- rootQ := c.DB.
+ rootQ := c.dbc.
Select("id").
Model(&db.Album{}).
Where("parent_id IS NULL")
- if m := getMusicFolder(c.MusicPaths, params); m != "" {
+ if m := getMusicFolder(c.musicPaths, params); m != "" {
rootQ = rootQ.Where("root_dir=?", m)
}
var artists []*db.Album
- q := c.DB.
+ 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).
@@ -319,13 +324,13 @@ func (c *Controller) ServeGetStarred(r *http.Request) *spec.Response {
// "albums"
var albums []*db.Album
- q = c.DB.
+ 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).
Preload("AlbumStar", "user_id=?", user.ID).
Preload("AlbumRating", "user_id=?", user.ID)
- if m := getMusicFolder(c.MusicPaths, params); m != "" {
+ if m := getMusicFolder(c.musicPaths, params); m != "" {
q = q.Where("root_dir=?", m)
}
if err := q.Find(&albums).Error; err != nil {
@@ -337,13 +342,14 @@ func (c *Controller) ServeGetStarred(r *http.Request) *spec.Response {
// tracks
var tracks []*db.Track
- q = c.DB.
+ q = c.dbc.
Preload("Album").
Joins("JOIN track_stars ON tracks.id=track_stars.track_id").
Where("track_stars.user_id=?", user.ID).
+ 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.musicPaths, params); m != "" {
q = q.
Joins("JOIN albums ON albums.id=tracks.album_id").
Where("albums.root_dir=?", m)
@@ -352,12 +358,11 @@ func (c *Controller) ServeGetStarred(r *http.Request) *spec.Response {
return spec.NewError(0, "find tracks: %v", err)
}
- transcodeMIME, transcodeSuffix := streamGetTransPrefProfile(c.DB, user.ID, params.GetOr("c", ""))
+ transcodeMeta := streamGetTranscodeMeta(c.dbc, user.ID, params.GetOr("c", ""))
for _, t := range tracks {
track := spec.NewTCTrackByFolder(t, t.Album)
- track.TranscodedContentType = transcodeMIME
- track.TranscodedSuffix = transcodeSuffix
+ track.TranscodeMeta = transcodeMeta
results.Tracks = append(results.Tracks, track)
}
diff --git a/server/ctrlsubsonic/handlers_by_folder_test.go b/server/ctrlsubsonic/handlers_by_folder_test.go
index 4d6208c..0efc4e2 100644
--- a/server/ctrlsubsonic/handlers_by_folder_test.go
+++ b/server/ctrlsubsonic/handlers_by_folder_test.go
@@ -8,9 +8,9 @@ import (
)
func TestGetIndexes(t *testing.T) {
+ t.Parallel()
contr := makeControllerRoots(t, []string{"m-0", "m-1"})
-
- runQueryCases(t, contr, contr.ServeGetIndexes, []*queryCase{
+ runQueryCases(t, contr.ServeGetIndexes, []*queryCase{
{url.Values{}, "no_args", false},
{url.Values{"musicFolderId": {"0"}}, "with_music_folder_1", false},
{url.Values{"musicFolderId": {"1"}}, "with_music_folder_2", false},
@@ -18,9 +18,9 @@ func TestGetIndexes(t *testing.T) {
}
func TestGetMusicDirectory(t *testing.T) {
+ t.Parallel()
contr := makeController(t)
-
- runQueryCases(t, contr, contr.ServeGetMusicDirectory, []*queryCase{
+ runQueryCases(t, contr.ServeGetMusicDirectory, []*queryCase{
{url.Values{"id": {"al-2"}}, "without_tracks", false},
{url.Values{"id": {"al-3"}}, "with_tracks", false},
})
@@ -29,8 +29,7 @@ func TestGetMusicDirectory(t *testing.T) {
func TestGetAlbumList(t *testing.T) {
t.Parallel()
contr := makeController(t)
-
- runQueryCases(t, contr, contr.ServeGetAlbumList, []*queryCase{
+ runQueryCases(t, contr.ServeGetAlbumList, []*queryCase{
{url.Values{"type": {"alphabeticalByArtist"}}, "alpha_artist", false},
{url.Values{"type": {"alphabeticalByName"}}, "alpha_name", false},
{url.Values{"type": {"newest"}}, "newest", false},
@@ -41,8 +40,7 @@ func TestGetAlbumList(t *testing.T) {
func TestSearchTwo(t *testing.T) {
t.Parallel()
contr := makeController(t)
-
- runQueryCases(t, contr, contr.ServeSearchTwo, []*queryCase{
+ runQueryCases(t, contr.ServeSearchTwo, []*queryCase{
{url.Values{"query": {"art"}}, "q_art", false},
{url.Values{"query": {"alb"}}, "q_alb", false},
{url.Values{"query": {"tra"}}, "q_tra", false},
diff --git a/server/ctrlsubsonic/handlers_by_tags.go b/server/ctrlsubsonic/handlers_by_tags.go
index c308aec..1f45247 100644
--- a/server/ctrlsubsonic/handlers_by_tags.go
+++ b/server/ctrlsubsonic/handlers_by_tags.go
@@ -3,6 +3,7 @@ package ctrlsubsonic
import (
"errors"
"fmt"
+ "log"
"math"
"net/http"
"net/url"
@@ -13,6 +14,7 @@ import (
"github.com/jinzhu/gorm"
"go.senan.xyz/gonic/db"
+ "go.senan.xyz/gonic/handlerutil"
"go.senan.xyz/gonic/server/ctrlsubsonic/params"
"go.senan.xyz/gonic/server/ctrlsubsonic/spec"
"go.senan.xyz/gonic/server/ctrlsubsonic/specid"
@@ -22,17 +24,18 @@ func (c *Controller) ServeGetArtists(r *http.Request) *spec.Response {
params := r.Context().Value(CtxParams).(params.Params)
user := r.Context().Value(CtxUser).(*db.User)
var artists []*db.Artist
- q := c.DB.
- Select("*, count(sub.id) album_count").
+ q := c.dbc.
+ Select("*, count(album_artists.album_id) album_count").
Joins("JOIN album_artists ON album_artists.artist_id=artists.id").
- Joins("JOIN albums sub ON sub.id=album_artists.album_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 != "" {
- q = q.Where("sub.root_dir=?", m)
+ if m := getMusicFolder(c.musicPaths, params); m != "" {
+ q = q.
+ Joins("JOIN albums ON albums.id=album_artists.album_id").
+ Where("albums.root_dir=?", m)
}
if err := q.Find(&artists).Error; err != nil {
return spec.NewError(10, "error finding artists: %v", err)
@@ -65,28 +68,29 @@ func (c *Controller) ServeGetArtist(r *http.Request) *spec.Response {
if err != nil {
return spec.NewError(10, "please provide an `id` parameter")
}
- artist := &db.Artist{}
- c.DB.
- Preload("Albums", func(db *gorm.DB) *gorm.DB {
+ var artist db.Artist
+ c.dbc.
+ Preload("Appearances", func(db *gorm.DB) *gorm.DB {
return db.
Select("*, count(sub.id) child_count, sum(sub.length) duration").
Joins("LEFT JOIN tracks sub ON albums.id=sub.album_id").
Order("albums.right_path").
Group("albums.id")
}).
- Preload("Albums.Artists").
- Preload("Albums.Genres").
+ Preload("Appearances.Artists").
+ Preload("Appearances.Genres").
Preload("Info").
Preload("ArtistStar", "user_id=?", user.ID).
Preload("ArtistRating", "user_id=?", user.ID).
- First(artist, id.Value)
+ First(&artist, id.Value)
+
sub := spec.NewResponse()
- sub.Artist = spec.NewArtistByTags(artist)
- sub.Artist.Albums = make([]*spec.Album, len(artist.Albums))
- for i, album := range artist.Albums {
+ sub.Artist = spec.NewArtistByTags(&artist)
+ sub.Artist.Albums = make([]*spec.Album, len(artist.Appearances))
+ for i, album := range artist.Appearances {
sub.Artist.Albums[i] = spec.NewAlbumByTags(album, album.Artists)
}
- sub.Artist.AlbumCount = len(artist.Albums)
+ sub.Artist.AlbumCount = len(artist.Appearances)
return sub
}
@@ -98,7 +102,7 @@ func (c *Controller) ServeGetAlbum(r *http.Request) *spec.Response {
return spec.NewError(10, "please provide an `id` parameter")
}
album := &db.Album{}
- err = c.DB.
+ err = c.dbc.
Select("albums.*, count(tracks.id) child_count, sum(tracks.length) duration").
Joins("LEFT JOIN tracks ON tracks.album_id=albums.id").
Preload("Artists").
@@ -106,6 +110,7 @@ func (c *Controller) ServeGetAlbum(r *http.Request) *spec.Response {
Preload("Tracks", func(db *gorm.DB) *gorm.DB {
return db.
Order("tracks.tag_disc_number, tracks.tag_track_number").
+ Preload("Artists").
Preload("TrackStar", "user_id=?", user.ID).
Preload("TrackRating", "user_id=?", user.ID)
}).
@@ -120,18 +125,17 @@ func (c *Controller) ServeGetAlbum(r *http.Request) *spec.Response {
sub.Album = spec.NewAlbumByTags(album, album.Artists)
sub.Album.Tracks = make([]*spec.TrackChild, len(album.Tracks))
- transcodeMIME, transcodeSuffix := streamGetTransPrefProfile(c.DB, user.ID, params.GetOr("c", ""))
+ transcodeMeta := streamGetTranscodeMeta(c.dbc, user.ID, params.GetOr("c", ""))
for i, track := range album.Tracks {
sub.Album.Tracks[i] = spec.NewTrackByTags(track, album)
- sub.Album.Tracks[i].TranscodedContentType = transcodeMIME
- sub.Album.Tracks[i].TranscodedSuffix = transcodeSuffix
+ sub.Album.Tracks[i].TranscodeMeta = transcodeMeta
}
return sub
}
// ServeGetAlbumListTwo handles the getAlbumList2 view.
-// changes to this function should be reflected in in _by_folder.go's
+// changes to this function should be reflected in _by_folder.go's
// getAlbumList() function
func (c *Controller) ServeGetAlbumListTwo(r *http.Request) *spec.Response {
params := r.Context().Value(CtxParams).(params.Params)
@@ -140,7 +144,7 @@ func (c *Controller) ServeGetAlbumListTwo(r *http.Request) *spec.Response {
if err != nil {
return spec.NewError(10, "please provide a `type` parameter")
}
- q := c.DB.DB
+ q := c.dbc.DB
switch listType {
case "alphabeticalByArtist":
q = q.Joins("JOIN artists ON artists.id=album_artists.artist_id")
@@ -148,8 +152,7 @@ func (c *Controller) ServeGetAlbumListTwo(r *http.Request) *spec.Response {
case "alphabeticalByName":
q = q.Order("tag_title")
case "byYear":
- y1, y2 :=
- params.GetOrInt("fromYear", 1800),
+ y1, y2 := params.GetOrInt("fromYear", 1800),
params.GetOrInt("toYear", 2200)
// support some clients sending wrong order like DSub
q = q.Where("tag_year BETWEEN ? AND ?", min(y1, y2), max(y1, y2))
@@ -173,10 +176,13 @@ func (c *Controller) ServeGetAlbumListTwo(r *http.Request) *spec.Response {
case "starred":
q = q.Joins("JOIN album_stars ON albums.id=album_stars.album_id AND album_stars.user_id=?", user.ID)
q = q.Order("tag_title")
+ case "highest":
+ q = q.Joins("JOIN album_ratings ON album_ratings.album_id=albums.id AND album_ratings.user_id=?", user.ID)
+ q = q.Order("album_ratings.rating DESC")
default:
- return spec.NewError(10, "unknown value `%s` for parameter 'type'", listType)
+ return spec.NewError(10, "unknown value %q for parameter 'type'", listType)
}
- if m := getMusicFolder(c.MusicPaths, params); m != "" {
+ if m := getMusicFolder(c.musicPaths, params); m != "" {
q = q.Where("root_dir=?", m)
}
var albums []*db.Album
@@ -219,7 +225,7 @@ func (c *Controller) ServeSearchThree(r *http.Request) *spec.Response {
// search artists
var artists []*db.Artist
- q := c.DB.
+ q := c.dbc.
Select("*, count(albums.id) album_count").
Group("artists.id")
for _, s := range queries {
@@ -233,7 +239,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.musicPaths, params); m != "" {
q = q.Where("albums.root_dir=?", m)
}
if err := q.Find(&artists).Error; err != nil {
@@ -245,7 +251,7 @@ func (c *Controller) ServeSearchThree(r *http.Request) *spec.Response {
// search albums
var albums []*db.Album
- q = c.DB.
+ q = c.dbc.
Preload("Artists").
Preload("Genres").
Preload("AlbumStar", "user_id=?", user.ID).
@@ -256,7 +262,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.musicPaths, params); m != "" {
q = q.Where("root_dir=?", m)
}
if err := q.Find(&albums).Error; err != nil {
@@ -268,10 +274,11 @@ func (c *Controller) ServeSearchThree(r *http.Request) *spec.Response {
// search tracks
var tracks []*db.Track
- q = c.DB.
+ q = c.dbc.
Preload("Album").
Preload("Album.Artists").
Preload("Genres").
+ Preload("Artists").
Preload("TrackStar", "user_id=?", user.ID).
Preload("TrackRating", "user_id=?", user.ID)
for _, s := range queries {
@@ -279,7 +286,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.musicPaths, params); m != "" {
q = q.
Joins("JOIN albums ON albums.id=tracks.album_id").
Where("albums.root_dir=?", m)
@@ -288,12 +295,11 @@ func (c *Controller) ServeSearchThree(r *http.Request) *spec.Response {
return spec.NewError(0, "find tracks: %v", err)
}
- transcodeMIME, transcodeSuffix := streamGetTransPrefProfile(c.DB, user.ID, params.GetOr("c", ""))
+ transcodeMeta := streamGetTranscodeMeta(c.dbc, user.ID, params.GetOr("c", ""))
for _, t := range tracks {
track := spec.NewTrackByTags(t, t.Album)
- track.TranscodedContentType = transcodeMIME
- track.TranscodedSuffix = transcodeSuffix
+ track.TranscodeMeta = transcodeMeta
results.Tracks = append(results.Tracks, track)
}
@@ -310,25 +316,21 @@ func (c *Controller) ServeGetArtistInfoTwo(r *http.Request) *spec.Response {
}
var artist db.Artist
- err = c.DB.
+ err = c.dbc.
Where("id=?", id.Value).
Find(&artist).
Error
if errors.Is(err, gorm.ErrRecordNotFound) {
- return spec.NewError(70, "artist with id `%s` not found", id)
+ return spec.NewError(70, "artist with id %q not found", id)
}
sub := spec.NewResponse()
sub.ArtistInfoTwo = &spec.ArtistInfo{}
- apiKey, _ := c.DB.GetSetting(db.LastFMAPIKey)
- if apiKey == "" {
- return sub
- }
-
- info, err := c.ArtistInfoCache.GetOrLookup(r.Context(), apiKey, artist.ID)
+ info, err := c.artistInfoCache.GetOrLookup(r.Context(), artist.ID)
if err != nil {
- return spec.NewError(0, "fetching artist info: %v", err)
+ log.Printf("error fetching artist info from lastfm: %v", err)
+ return sub
}
sub.ArtistInfoTwo.Biography = info.Biography
@@ -354,13 +356,13 @@ func (c *Controller) ServeGetArtistInfoTwo(r *http.Request) *spec.Response {
break
}
var artist db.Artist
- err = c.DB.
+ err = c.dbc.
+ Preload("Info").
Select("artists.*, count(albums.id) album_count").
Where("name=?", similarName).
- Joins("LEFT JOIN album_artists ON album_artists.artist_id=artists.id").
- Joins("LEFT JOIN albums ON albums.id=album_artists.album_id").
+ Joins("LEFT JOIN artist_appearances ON artist_appearances.artist_id=artists.id").
+ Joins("LEFT JOIN albums ON albums.id=artist_appearances.album_id").
Group("artists.id").
- Preload("Info").
Find(&artist).
Error
if errors.Is(err, gorm.ErrRecordNotFound) && !inclNotPresent {
@@ -382,9 +384,41 @@ func (c *Controller) ServeGetArtistInfoTwo(r *http.Request) *spec.Response {
return sub
}
+func (c *Controller) ServeGetAlbumInfoTwo(r *http.Request) *spec.Response {
+ params := r.Context().Value(CtxParams).(params.Params)
+ id, err := params.GetID("id")
+ if err != nil {
+ return spec.NewError(10, "please provide an `id` parameter")
+ }
+
+ var album db.Album
+ err = c.dbc.
+ Where("id=?", id.Value).
+ Find(&album).
+ Error
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return spec.NewError(70, "album with id %q not found", id)
+ }
+
+ sub := spec.NewResponse()
+ sub.AlbumInfo = &spec.AlbumInfo{}
+
+ info, err := c.albumInfoCache.GetOrLookup(r.Context(), album.ID)
+ if err != nil {
+ log.Printf("error fetching album info from lastfm: %v", err)
+ return sub
+ }
+
+ sub.AlbumInfo.Notes = info.Notes
+ sub.AlbumInfo.MusicBrainzID = info.MusicBrainzID
+ sub.AlbumInfo.LastFMURL = info.LastFMURL
+
+ return sub
+}
+
func (c *Controller) ServeGetGenres(_ *http.Request) *spec.Response {
var genres []*db.Genre
- c.DB.
+ c.dbc.
Select(`*,
(SELECT count(1) FROM album_genres WHERE genre_id=genres.id) album_count,
(SELECT count(1) FROM track_genres WHERE genre_id=genres.id) track_count`).
@@ -408,17 +442,18 @@ func (c *Controller) ServeGetSongsByGenre(r *http.Request) *spec.Response {
return spec.NewError(10, "please provide an `genre` parameter")
}
var tracks []*db.Track
- q := c.DB.
+ q := c.dbc.
Joins("JOIN albums ON tracks.album_id=albums.id").
Joins("JOIN track_genres ON track_genres.track_id=tracks.id").
Joins("JOIN genres ON track_genres.genre_id=genres.id AND genres.name=?", genre).
Preload("Album").
Preload("Album.Artists").
+ Preload("Artists").
Preload("TrackStar", "user_id=?", user.ID).
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.musicPaths, params); m != "" {
q = q.Where("albums.root_dir=?", m)
}
q = q.Group("tracks.id")
@@ -430,12 +465,11 @@ func (c *Controller) ServeGetSongsByGenre(r *http.Request) *spec.Response {
List: make([]*spec.TrackChild, len(tracks)),
}
- transcodeMIME, transcodeSuffix := streamGetTransPrefProfile(c.DB, user.ID, params.GetOr("c", ""))
+ transcodeMeta := streamGetTranscodeMeta(c.dbc, user.ID, params.GetOr("c", ""))
for i, t := range tracks {
sub.TracksByGenre.List[i] = spec.NewTrackByTags(t, t.Album)
- sub.TracksByGenre.List[i].TranscodedContentType = transcodeMIME
- sub.TracksByGenre.List[i].TranscodedSuffix = transcodeSuffix
+ sub.TracksByGenre.List[i].TranscodeMeta = transcodeMeta
}
return sub
@@ -449,16 +483,18 @@ func (c *Controller) ServeGetStarredTwo(r *http.Request) *spec.Response {
// artists
var artists []*db.Artist
- q := c.DB.
+ q := c.dbc.
+ 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 album_artists ON album_artists.artist_id=artists.id").
- Joins("JOIN albums ON albums.id=album_artists.album_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.MusicPaths, params); m != "" {
+ if m := getMusicFolder(c.musicPaths, params); m != "" {
q = q.Where("albums.root_dir=?", m)
}
if err := q.Find(&artists).Error; err != nil {
@@ -470,13 +506,14 @@ func (c *Controller) ServeGetStarredTwo(r *http.Request) *spec.Response {
// albums
var albums []*db.Album
- q = c.DB.
+ q = c.dbc.
Joins("JOIN album_stars ON album_stars.album_id=albums.id").
Where("album_stars.user_id=?", user.ID).
+ Order("album_stars.star_date DESC").
Preload("Artists").
Preload("AlbumStar", "user_id=?", user.ID).
Preload("AlbumRating", "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)
}
if err := q.Find(&albums).Error; err != nil {
@@ -488,13 +525,16 @@ func (c *Controller) ServeGetStarredTwo(r *http.Request) *spec.Response {
// tracks
var tracks []*db.Track
- q = c.DB.
+ q = c.dbc.
Joins("JOIN track_stars ON tracks.id=track_stars.track_id").
Where("track_stars.user_id=?", user.ID).
+ Order("track_stars.star_date DESC").
Preload("Album").
+ Preload("Album.Artists").
+ 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.musicPaths, params); m != "" {
q = q.
Joins("JOIN albums ON albums.id=tracks.album_id").
Where("albums.root_dir=?", m)
@@ -503,12 +543,11 @@ func (c *Controller) ServeGetStarredTwo(r *http.Request) *spec.Response {
return spec.NewError(0, "find tracks: %v", err)
}
- transcodeMIME, transcodeSuffix := streamGetTransPrefProfile(c.DB, user.ID, params.GetOr("c", ""))
+ transcodeMeta := streamGetTranscodeMeta(c.dbc, user.ID, params.GetOr("c", ""))
for _, t := range tracks {
track := spec.NewTrackByTags(t, t.Album)
- track.TranscodedContentType = transcodeMIME
- track.TranscodedSuffix = transcodeSuffix
+ track.TranscodeMeta = transcodeMeta
results.Tracks = append(results.Tracks, track)
}
@@ -518,8 +557,8 @@ func (c *Controller) ServeGetStarredTwo(r *http.Request) *spec.Response {
}
func (c *Controller) genArtistCoverURL(r *http.Request, artist *db.Artist, size int) string {
- coverURL, _ := url.Parse(c.BaseURL(r))
- coverURL.Path = c.Path("/rest/getCoverArt")
+ coverURL, _ := url.Parse(handlerutil.BaseURL(r))
+ coverURL.Path = c.resolveProxyPath("/rest/getCoverArt")
query := r.URL.Query()
query.Set("id", artist.SID().String())
@@ -538,17 +577,14 @@ func (c *Controller) ServeGetTopSongs(r *http.Request) *spec.Response {
return spec.NewError(10, "please provide an `artist` parameter")
}
var artist db.Artist
- if err := c.DB.Where("name=?", artistName).Find(&artist).Error; err != nil {
+ if err := c.dbc.Where("name=?", artistName).Find(&artist).Error; err != nil {
return spec.NewError(0, "finding artist by name: %v", err)
}
- apiKey, _ := c.DB.GetSetting(db.LastFMAPIKey)
- if apiKey == "" {
- return spec.NewResponse()
- }
- info, err := c.ArtistInfoCache.GetOrLookup(r.Context(), apiKey, artist.ID)
+ info, err := c.artistInfoCache.GetOrLookup(r.Context(), artist.ID)
if err != nil {
- return spec.NewError(0, "fetching artist top tracks: %v", err)
+ log.Printf("error fetching artist info from lastfm: %v", err)
+ return spec.NewResponse()
}
sub := spec.NewResponse()
@@ -562,15 +598,17 @@ func (c *Controller) ServeGetTopSongs(r *http.Request) *spec.Response {
}
var tracks []*db.Track
- err = c.DB.
+ err = c.dbc.
+ Where("tracks.tag_title IN (?)", topTrackNames).
+ Joins("JOIN track_artists ON track_artists.track_id=tracks.id").
+ Joins("JOIN artists ON artists.id=track_artists.artist_id").
+ Where("artists.id=?", artist.ID).
Preload("Album").
- Joins("JOIN albums ON albums.id=tracks.album_id").
- Joins("JOIN album_artists ON album_artists.album_id=albums.id").
- Where("album_artists.artist_id=? AND tracks.tag_title IN (?)", artist.ID, topTrackNames).
- Limit(count).
+ Preload("Artists").
Preload("TrackStar", "user_id=?", user.ID).
Preload("TrackRating", "user_id=?", user.ID).
Group("tracks.id").
+ Limit(count).
Find(&tracks).
Error
if err != nil {
@@ -580,12 +618,11 @@ func (c *Controller) ServeGetTopSongs(r *http.Request) *spec.Response {
return sub
}
- transcodeMIME, transcodeSuffix := streamGetTransPrefProfile(c.DB, user.ID, params.GetOr("c", ""))
+ transcodeMeta := streamGetTranscodeMeta(c.dbc, user.ID, params.GetOr("c", ""))
for _, track := range tracks {
tc := spec.NewTrackByTags(track, track.Album)
- tc.TranscodedContentType = transcodeMIME
- tc.TranscodedSuffix = transcodeSuffix
+ tc.TranscodeMeta = transcodeMeta
sub.TopSongs.Tracks = append(sub.TopSongs.Tracks, tc)
}
return sub
@@ -599,13 +636,9 @@ func (c *Controller) ServeGetSimilarSongs(r *http.Request) *spec.Response {
if err != nil || id.Type != specid.Track {
return spec.NewError(10, "please provide an track `id` parameter")
}
- apiKey, _ := c.DB.GetSetting(db.LastFMAPIKey)
- if apiKey == "" {
- return spec.NewResponse()
- }
var track db.Track
- err = c.DB.
+ err = c.dbc.
Preload("Album").
Where("id=?", id.Value).
First(&track).
@@ -614,10 +647,12 @@ func (c *Controller) ServeGetSimilarSongs(r *http.Request) *spec.Response {
return spec.NewError(10, "couldn't find a track with that id")
}
- similarTracks, err := c.LastFMClient.TrackGetSimilarTracks(apiKey, track.TagTrackArtist, track.TagTitle)
+ similarTracks, err := c.lastFMClient.TrackGetSimilarTracks(track.TagTrackArtist, track.TagTitle)
if err != nil {
- return spec.NewError(0, "fetching track similar tracks: %v", err)
+ log.Printf("error fetching similar songs from lastfm: %v", err)
+ return spec.NewResponse()
}
+
if len(similarTracks.Tracks) == 0 {
return spec.NewError(70, "no similar songs found for track: %v", track.TagTitle)
}
@@ -628,9 +663,10 @@ func (c *Controller) ServeGetSimilarSongs(r *http.Request) *spec.Response {
}
var tracks []*db.Track
- err = c.DB.
+ err = c.dbc.
Select("tracks.*").
Preload("Album").
+ Preload("Artists").
Preload("TrackStar", "user_id=?", user.ID).
Preload("TrackRating", "user_id=?", user.ID).
Where("tracks.tag_title IN (?)", similarTrackNames).
@@ -650,12 +686,11 @@ func (c *Controller) ServeGetSimilarSongs(r *http.Request) *spec.Response {
Tracks: make([]*spec.TrackChild, len(tracks)),
}
- transcodeMIME, transcodeSuffix := streamGetTransPrefProfile(c.DB, user.ID, params.GetOr("c", ""))
+ transcodeMeta := streamGetTranscodeMeta(c.dbc, user.ID, params.GetOr("c", ""))
for i, track := range tracks {
sub.SimilarSongs.Tracks[i] = spec.NewTrackByTags(track, track.Album)
- sub.SimilarSongs.Tracks[i].TranscodedContentType = transcodeMIME
- sub.SimilarSongs.Tracks[i].TranscodedSuffix = transcodeSuffix
+ sub.SimilarSongs.Tracks[i].TranscodeMeta = transcodeMeta
}
return sub
}
@@ -669,23 +704,19 @@ func (c *Controller) ServeGetSimilarSongsTwo(r *http.Request) *spec.Response {
return spec.NewError(10, "please provide an artist `id` parameter")
}
- apiKey, _ := c.DB.GetSetting(db.LastFMAPIKey)
- if apiKey == "" {
- return spec.NewResponse()
- }
-
var artist db.Artist
- err = c.DB.
+ err = c.dbc.
Where("id=?", id.Value).
First(&artist).
Error
if errors.Is(err, gorm.ErrRecordNotFound) {
- return spec.NewError(0, "artist with id `%s` not found", id)
+ return spec.NewError(0, "artist with id %q not found", id)
}
- similarArtists, err := c.LastFMClient.ArtistGetSimilar(apiKey, artist.Name)
+ similarArtists, err := c.lastFMClient.ArtistGetSimilar(artist.Name)
if err != nil {
- return spec.NewError(0, "fetching artist similar artists: %v", err)
+ log.Printf("error fetching artist info from lastfm: %v", err)
+ return spec.NewResponse()
}
if len(similarArtists.Artists) == 0 {
return spec.NewError(0, "no similar artist found for: %v", artist.Name)
@@ -697,12 +728,13 @@ func (c *Controller) ServeGetSimilarSongsTwo(r *http.Request) *spec.Response {
}
var tracks []*db.Track
- err = c.DB.
+ err = c.dbc.
Preload("Album").
+ Preload("Artists").
Preload("TrackStar", "user_id=?", user.ID).
Preload("TrackRating", "user_id=?", user.ID).
- Joins("JOIN album_artists ON album_artists.album_id=tracks.album_id").
- Joins("JOIN artists ON artists.id=album_artists.artist_id").
+ Joins("JOIN track_artists ON track_artists.track_id=tracks.id").
+ Joins("JOIN artists ON artists.id=track_artists.artist_id").
Where("artists.name IN (?)", artistNames).
Order(gorm.Expr("random()")).
Group("tracks.id").
@@ -721,12 +753,10 @@ func (c *Controller) ServeGetSimilarSongsTwo(r *http.Request) *spec.Response {
Tracks: make([]*spec.TrackChild, len(tracks)),
}
- transcodeMIME, transcodeSuffix := streamGetTransPrefProfile(c.DB, user.ID, params.GetOr("c", ""))
-
+ transcodeMeta := streamGetTranscodeMeta(c.dbc, user.ID, params.GetOr("c", ""))
for i, track := range tracks {
sub.SimilarSongsTwo.Tracks[i] = spec.NewTrackByTags(track, track.Album)
- sub.SimilarSongsTwo.Tracks[i].TranscodedContentType = transcodeMIME
- sub.SimilarSongsTwo.Tracks[i].TranscodedSuffix = transcodeSuffix
+ sub.SimilarSongsTwo.Tracks[i].TranscodeMeta = transcodeMeta
}
return sub
}
@@ -754,33 +784,33 @@ func (c *Controller) ServeStar(r *http.Request) *spec.Response {
stardate := time.Now()
for _, id := range starIDsOfType(params, specid.Album) {
var albumstar db.AlbumStar
- _ = c.DB.Where("user_id=? AND album_id=?", user.ID, id).First(&albumstar).Error
+ _ = c.dbc.Where("user_id=? AND album_id=?", user.ID, id).First(&albumstar).Error
albumstar.UserID = user.ID
albumstar.AlbumID = id
albumstar.StarDate = stardate
- if err := c.DB.Save(&albumstar).Error; err != nil {
+ if err := c.dbc.Save(&albumstar).Error; err != nil {
return spec.NewError(0, "save album star: %v", err)
}
}
for _, id := range starIDsOfType(params, specid.Artist) {
var artiststar db.ArtistStar
- _ = c.DB.Where("user_id=? AND artist_id=?", user.ID, id).First(&artiststar).Error
+ _ = c.dbc.Where("user_id=? AND artist_id=?", user.ID, id).First(&artiststar).Error
artiststar.UserID = user.ID
artiststar.ArtistID = id
artiststar.StarDate = stardate
- if err := c.DB.Save(&artiststar).Error; err != nil {
+ if err := c.dbc.Save(&artiststar).Error; err != nil {
return spec.NewError(0, "save artist star: %v", err)
}
}
for _, id := range starIDsOfType(params, specid.Track) {
var trackstar db.TrackStar
- _ = c.DB.Where("user_id=? AND track_id=?", user.ID, id).First(&trackstar).Error
+ _ = c.dbc.Where("user_id=? AND track_id=?", user.ID, id).First(&trackstar).Error
trackstar.UserID = user.ID
trackstar.TrackID = id
trackstar.StarDate = stardate
- if err := c.DB.Save(&trackstar).Error; err != nil {
+ if err := c.dbc.Save(&trackstar).Error; err != nil {
return spec.NewError(0, "save track star: %v", err)
}
}
@@ -793,19 +823,19 @@ func (c *Controller) ServeUnstar(r *http.Request) *spec.Response {
user := r.Context().Value(CtxUser).(*db.User)
for _, id := range starIDsOfType(params, specid.Album) {
- if err := c.DB.Where("user_id=? AND album_id=?", user.ID, id).Delete(db.AlbumStar{}).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
+ if err := c.dbc.Where("user_id=? AND album_id=?", user.ID, id).Delete(db.AlbumStar{}).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
return spec.NewError(0, "delete album star: %v", err)
}
}
for _, id := range starIDsOfType(params, specid.Artist) {
- if err := c.DB.Where("user_id=? AND artist_id=?", user.ID, id).Delete(db.ArtistStar{}).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
+ if err := c.dbc.Where("user_id=? AND artist_id=?", user.ID, id).Delete(db.ArtistStar{}).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
return spec.NewError(0, "delete artist star: %v", err)
}
}
for _, id := range starIDsOfType(params, specid.Track) {
- if err := c.DB.Where("user_id=? AND track_id=?", user.ID, id).Delete(db.TrackStar{}).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
+ if err := c.dbc.Where("user_id=? AND track_id=?", user.ID, id).Delete(db.TrackStar{}).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
return spec.NewError(0, "delete track star: %v", err)
}
}
@@ -830,95 +860,95 @@ func (c *Controller) ServeSetRating(r *http.Request) *spec.Response {
switch id.Type {
case specid.Album:
var album db.Album
- err := c.DB.Where("id=?", id.Value).First(&album).Error
+ err := c.dbc.Where("id=?", id.Value).First(&album).Error
if err != nil {
return spec.NewError(0, "fetch album: %v", err)
}
var albumRating db.AlbumRating
- if err := c.DB.Where("user_id=? AND album_id=?", user.ID, id.Value).First(&albumRating).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
+ if err := c.dbc.Where("user_id=? AND album_id=?", user.ID, id.Value).First(&albumRating).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
return spec.NewError(0, "fetch album rating: %v", err)
}
switch {
case rating == 0 && albumRating.AlbumID == album.ID:
- if err := c.DB.Delete(&albumRating).Error; err != nil {
+ if err := c.dbc.Delete(&albumRating).Error; err != nil {
return spec.NewError(0, "delete album rating: %v", err)
}
case rating > 0:
albumRating.UserID = user.ID
albumRating.AlbumID = id.Value
albumRating.Rating = rating
- if err := c.DB.Save(&albumRating).Error; err != nil {
+ if err := c.dbc.Save(&albumRating).Error; err != nil {
return spec.NewError(0, "save album rating: %v", err)
}
}
var averageRating float64
- if err := c.DB.Model(db.AlbumRating{}).Select("coalesce(avg(rating), 0)").Where("album_id=?", id.Value).Row().Scan(&averageRating); err != nil {
+ if err := c.dbc.Model(db.AlbumRating{}).Select("coalesce(avg(rating), 0)").Where("album_id=?", id.Value).Row().Scan(&averageRating); err != nil {
return spec.NewError(0, "find average album rating: %v", err)
}
album.AverageRating = math.Trunc(averageRating*100) / 100
- if err := c.DB.Save(&album).Error; err != nil {
+ if err := c.dbc.Save(&album).Error; err != nil {
return spec.NewError(0, "save album: %v", err)
}
case specid.Artist:
var artist db.Artist
- err := c.DB.Where("id=?", id.Value).First(&artist).Error
+ err := c.dbc.Where("id=?", id.Value).First(&artist).Error
if err != nil {
return spec.NewError(0, "fetch artist: %v", err)
}
var artistRating db.ArtistRating
- if err := c.DB.Where("user_id=? AND artist_id=?", user.ID, id.Value).First(&artistRating).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
+ if err := c.dbc.Where("user_id=? AND artist_id=?", user.ID, id.Value).First(&artistRating).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
return spec.NewError(0, "fetch artist rating: %v", err)
}
switch {
case rating == 0 && artistRating.ArtistID == artist.ID:
- if err := c.DB.Delete(&artistRating).Error; err != nil {
+ if err := c.dbc.Delete(&artistRating).Error; err != nil {
return spec.NewError(0, "delete artist rating: %v", err)
}
case rating > 0:
artistRating.UserID = user.ID
artistRating.ArtistID = id.Value
artistRating.Rating = rating
- if err := c.DB.Save(&artistRating).Error; err != nil {
+ if err := c.dbc.Save(&artistRating).Error; err != nil {
return spec.NewError(0, "save artist rating: %v", err)
}
}
var averageRating float64
- if err := c.DB.Model(db.ArtistRating{}).Select("coalesce(avg(rating), 0)").Where("artist_id=?", id.Value).Row().Scan(&averageRating); err != nil {
+ if err := c.dbc.Model(db.ArtistRating{}).Select("coalesce(avg(rating), 0)").Where("artist_id=?", id.Value).Row().Scan(&averageRating); err != nil {
return spec.NewError(0, "find average artist rating: %v", err)
}
artist.AverageRating = math.Trunc(averageRating*100) / 100
- if err := c.DB.Save(&artist).Error; err != nil {
+ if err := c.dbc.Save(&artist).Error; err != nil {
return spec.NewError(0, "save artist: %v", err)
}
case specid.Track:
var track db.Track
- err := c.DB.Where("id=?", id.Value).First(&track).Error
+ err := c.dbc.Where("id=?", id.Value).First(&track).Error
if err != nil {
return spec.NewError(0, "fetch track: %v", err)
}
var trackRating db.TrackRating
- if err := c.DB.Where("user_id=? AND track_id=?", user.ID, id.Value).First(&trackRating).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
+ if err := c.dbc.Where("user_id=? AND track_id=?", user.ID, id.Value).First(&trackRating).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
return spec.NewError(0, "fetch track rating: %v", err)
}
switch {
case rating == 0 && trackRating.TrackID == track.ID:
- if err := c.DB.Delete(&trackRating).Error; err != nil {
+ if err := c.dbc.Delete(&trackRating).Error; err != nil {
return spec.NewError(0, "delete track rating: %v", err)
}
case rating > 0:
trackRating.UserID = user.ID
trackRating.TrackID = id.Value
trackRating.Rating = rating
- if err := c.DB.Save(&trackRating).Error; err != nil {
+ if err := c.dbc.Save(&trackRating).Error; err != nil {
return spec.NewError(0, "save track rating: %v", err)
}
}
var averageRating float64
- if err := c.DB.Model(db.TrackRating{}).Select("coalesce(avg(rating), 0)").Where("track_id=?", id.Value).Row().Scan(&averageRating); err != nil {
+ if err := c.dbc.Model(db.TrackRating{}).Select("coalesce(avg(rating), 0)").Where("track_id=?", id.Value).Row().Scan(&averageRating); err != nil {
return spec.NewError(0, "find average track rating: %v", err)
}
track.AverageRating = math.Trunc(averageRating*100) / 100
- if err := c.DB.Save(&track).Error; err != nil {
+ if err := c.dbc.Save(&track).Error; err != nil {
return spec.NewError(0, "save track: %v", err)
}
default:
diff --git a/server/ctrlsubsonic/handlers_by_tags_test.go b/server/ctrlsubsonic/handlers_by_tags_test.go
index 7ea1bf8..cc71485 100644
--- a/server/ctrlsubsonic/handlers_by_tags_test.go
+++ b/server/ctrlsubsonic/handlers_by_tags_test.go
@@ -8,8 +8,7 @@ import (
func TestGetArtists(t *testing.T) {
t.Parallel()
contr := makeControllerRoots(t, []string{"m-0", "m-1"})
-
- runQueryCases(t, contr, contr.ServeGetArtists, []*queryCase{
+ runQueryCases(t, contr.ServeGetArtists, []*queryCase{
{url.Values{}, "no_args", false},
{url.Values{"musicFolderId": {"0"}}, "with_music_folder_1", false},
{url.Values{"musicFolderId": {"1"}}, "with_music_folder_2", false},
@@ -19,8 +18,7 @@ func TestGetArtists(t *testing.T) {
func TestGetArtist(t *testing.T) {
t.Parallel()
contr := makeController(t)
-
- runQueryCases(t, contr, contr.ServeGetArtist, []*queryCase{
+ runQueryCases(t, contr.ServeGetArtist, []*queryCase{
{url.Values{"id": {"ar-1"}}, "id_one", false},
{url.Values{"id": {"ar-2"}}, "id_two", false},
{url.Values{"id": {"ar-3"}}, "id_three", false},
@@ -30,8 +28,7 @@ func TestGetArtist(t *testing.T) {
func TestGetAlbum(t *testing.T) {
t.Parallel()
contr := makeController(t)
-
- runQueryCases(t, contr, contr.ServeGetAlbum, []*queryCase{
+ runQueryCases(t, contr.ServeGetAlbum, []*queryCase{
{url.Values{"id": {"al-2"}}, "without_cover", false},
{url.Values{"id": {"al-3"}}, "with_cover", false},
})
@@ -40,8 +37,7 @@ func TestGetAlbum(t *testing.T) {
func TestGetAlbumListTwo(t *testing.T) {
t.Parallel()
contr := makeController(t)
-
- runQueryCases(t, contr, contr.ServeGetAlbumListTwo, []*queryCase{
+ runQueryCases(t, contr.ServeGetAlbumListTwo, []*queryCase{
{url.Values{"type": {"alphabeticalByArtist"}}, "alpha_artist", false},
{url.Values{"type": {"alphabeticalByName"}}, "alpha_name", false},
{url.Values{"type": {"newest"}}, "newest", false},
@@ -52,8 +48,7 @@ func TestGetAlbumListTwo(t *testing.T) {
func TestSearchThree(t *testing.T) {
t.Parallel()
contr := makeController(t)
-
- runQueryCases(t, contr, contr.ServeSearchThree, []*queryCase{
+ runQueryCases(t, contr.ServeSearchThree, []*queryCase{
{url.Values{"query": {"art"}}, "q_art", false},
{url.Values{"query": {"alb"}}, "q_alb", false},
{url.Values{"query": {"tit"}}, "q_tra", false},
diff --git a/server/ctrlsubsonic/handlers_common.go b/server/ctrlsubsonic/handlers_common.go
index f617f0a..e41d0f5 100644
--- a/server/ctrlsubsonic/handlers_common.go
+++ b/server/ctrlsubsonic/handlers_common.go
@@ -6,39 +6,24 @@ import (
"log"
"math"
"net/http"
+ "os"
"path/filepath"
+ "sync"
"time"
"unicode"
+ "github.com/google/uuid"
"github.com/jinzhu/gorm"
"go.senan.xyz/gonic/db"
"go.senan.xyz/gonic/scanner"
+ "go.senan.xyz/gonic/scrobble"
"go.senan.xyz/gonic/server/ctrlsubsonic/params"
"go.senan.xyz/gonic/server/ctrlsubsonic/spec"
"go.senan.xyz/gonic/server/ctrlsubsonic/specid"
"go.senan.xyz/gonic/server/ctrlsubsonic/specidpaths"
)
-func lowerUDecOrHash(in string) string {
- lower := unicode.ToLower(rune(in[0]))
- if !unicode.IsLetter(lower) {
- return "#"
- }
- return string(lower)
-}
-
-func getMusicFolder(musicPaths []MusicPath, p params.Params) string {
- idx, err := p.GetInt("musicFolderId")
- if err != nil {
- return ""
- }
- if idx < 0 || idx >= len(musicPaths) {
- return ""
- }
- return musicPaths[idx].Path
-}
-
func (c *Controller) ServeGetLicence(_ *http.Request) *spec.Response {
sub := spec.NewResponse()
sub.Licence = &spec.Licence{
@@ -51,35 +36,87 @@ func (c *Controller) ServePing(_ *http.Request) *spec.Response {
return spec.NewResponse()
}
+func (c *Controller) ServeGetOpenSubsonicExtensions(_ *http.Request) *spec.Response {
+ sub := spec.NewResponse()
+ sub.OpenSubsonicExtensions = &spec.OpenSubsonicExtensions{
+ {Name: "transcodeOffset", Versions: []int{1}},
+ }
+ return sub
+}
+
func (c *Controller) ServeScrobble(r *http.Request) *spec.Response {
user := r.Context().Value(CtxUser).(*db.User)
params := r.Context().Value(CtxParams).(params.Params)
id, err := params.GetID("id")
- if err != nil || id.Type != specid.Track {
- return spec.NewError(10, "please provide a track `id` track parameter")
- }
-
- track := &db.Track{}
- if err := c.DB.Preload("Album").Preload("Album.Artists").First(track, id.Value).Error; err != nil {
- return spec.NewError(0, "error finding track: %v", err)
+ if err != nil {
+ return spec.NewError(10, "please provide a `id` parameter")
}
optStamp := params.GetOrTime("time", time.Now())
optSubmission := params.GetOrBool("submission", true)
- if err := streamUpdateStats(c.DB, user.ID, track, optStamp); err != nil {
- return spec.NewError(0, "error updating stats: %v", err)
- }
+ var scrobbleTrack scrobble.Track
- var scrobbleErrs []error
- for _, scrobbler := range c.Scrobblers {
- if err := scrobbler.Scrobble(user, track, optStamp, optSubmission); err != nil {
- scrobbleErrs = append(scrobbleErrs, err)
+ switch id.Type {
+ case specid.Track:
+ var track db.Track
+ if err := c.dbc.Preload("Album").Preload("Album.Artists").First(&track, id.Value).Error; err != nil {
+ return spec.NewError(0, "error finding track: %v", err)
+ }
+ if track.Album == nil {
+ return spec.NewError(0, "track has no album %d", track.ID)
+ }
+
+ scrobbleTrack.Track = track.TagTitle
+ scrobbleTrack.Artist = track.TagTrackArtist
+ scrobbleTrack.Album = track.Album.TagTitle
+ scrobbleTrack.AlbumArtist = track.Album.TagAlbumArtist
+ scrobbleTrack.TrackNumber = uint(track.TagTrackNumber)
+ scrobbleTrack.Duration = time.Second * time.Duration(track.Length)
+ if _, err := uuid.Parse(track.TagBrainzID); err == nil {
+ scrobbleTrack.MusicBrainzID = track.TagBrainzID
+ }
+
+ if err := scrobbleStatsUpdateTrack(c.dbc, &track, user.ID, optStamp); err != nil {
+ return spec.NewError(0, "error updating stats: %v", err)
+ }
+
+ case specid.PodcastEpisode:
+ var podcastEpisode db.PodcastEpisode
+ if err := c.dbc.Preload("Podcast").First(&podcastEpisode, id.Value).Error; err != nil {
+ return spec.NewError(0, "error finding podcast episode: %v", err)
+ }
+
+ if err := scrobbleStatsUpdatePodcastEpisode(c.dbc, id.Value); err != nil {
+ return spec.NewError(0, "error updating stats: %v", err)
}
}
- if len(scrobbleErrs) > 0 {
- return spec.NewError(0, "error when submitting: %v", errors.Join(scrobbleErrs...))
+
+ if scrobbleTrack.Track == "" {
+ return spec.NewResponse()
+ }
+
+ var wg sync.WaitGroup
+
+ scrobbleErrs := make([]error, len(c.scrobblers))
+ for i := range c.scrobblers {
+ if !c.scrobblers[i].IsUserAuthenticated(*user) {
+ continue
+ }
+ wg.Add(1)
+ go func(i int) {
+ defer wg.Done()
+ if err := c.scrobblers[i].Scrobble(*user, scrobbleTrack, optStamp, optSubmission); err != nil {
+ scrobbleErrs[i] = err
+ }
+ }(i)
+ }
+
+ wg.Wait()
+
+ if err := errors.Join(scrobbleErrs...); err != nil {
+ return spec.NewError(0, "error when submitting: %v", err)
}
return spec.NewResponse()
@@ -88,7 +125,7 @@ func (c *Controller) ServeScrobble(r *http.Request) *spec.Response {
func (c *Controller) ServeGetMusicFolders(_ *http.Request) *spec.Response {
sub := spec.NewResponse()
sub.MusicFolders = &spec.MusicFolders{}
- for i, mp := range c.MusicPaths {
+ for i, mp := range c.musicPaths {
alias := mp.Alias
if alias == "" {
alias = filepath.Base(mp.Path)
@@ -100,7 +137,7 @@ func (c *Controller) ServeGetMusicFolders(_ *http.Request) *spec.Response {
func (c *Controller) ServeStartScan(r *http.Request) *spec.Response {
go func() {
- if _, err := c.Scanner.ScanAndClean(scanner.ScanOptions{}); err != nil {
+ if _, err := c.scanner.ScanAndClean(scanner.ScanOptions{}); err != nil {
log.Printf("error while scanning: %v\n", err)
}
}()
@@ -109,13 +146,13 @@ func (c *Controller) ServeStartScan(r *http.Request) *spec.Response {
func (c *Controller) ServeGetScanStatus(_ *http.Request) *spec.Response {
var trackCount int
- if err := c.DB.Model(db.Track{}).Count(&trackCount).Error; err != nil {
+ if err := c.dbc.Model(db.Track{}).Count(&trackCount).Error; err != nil {
return spec.NewError(0, "error finding track count: %v", err)
}
sub := spec.NewResponse()
sub.ScanStatus = &spec.ScanStatus{
- Scanning: c.Scanner.IsScanning(),
+ Scanning: c.scanner.IsScanning(),
Count: trackCount,
}
return sub
@@ -130,8 +167,8 @@ func (c *Controller) ServeGetUser(r *http.Request) *spec.Response {
sub.User = &spec.User{
Username: user.Name,
AdminRole: user.IsAdmin,
- JukeboxRole: c.Jukebox != nil,
- PodcastRole: c.Podcasts != nil,
+ JukeboxRole: c.jukebox != nil,
+ PodcastRole: c.podcasts != nil,
DownloadRole: true,
ScrobblingEnabled: hasLastFM || hasListenBrainz,
Folder: []int{1},
@@ -147,7 +184,7 @@ func (c *Controller) ServeGetPlayQueue(r *http.Request) *spec.Response {
params := r.Context().Value(CtxParams).(params.Params)
user := r.Context().Value(CtxUser).(*db.User)
var queue db.PlayQueue
- err := c.DB.
+ err := c.dbc.
Where("user_id=?", user.ID).
Find(&queue).
Error
@@ -165,33 +202,28 @@ func (c *Controller) ServeGetPlayQueue(r *http.Request) *spec.Response {
trackIDs := queue.GetItems()
sub.PlayQueue.List = make([]*spec.TrackChild, len(trackIDs))
- transcodeMIME, transcodeSuffix := streamGetTransPrefProfile(c.DB, user.ID, params.GetOr("c", ""))
+ transcodeMeta := streamGetTranscodeMeta(c.dbc, user.ID, params.GetOr("c", ""))
for i, id := range trackIDs {
switch id.Type {
case specid.Track:
track := db.Track{}
- c.DB.
+ c.dbc.
Where("id=?", id.Value).
Preload("Album").
+ Preload("Artists").
Preload("TrackStar", "user_id=?", user.ID).
Preload("TrackRating", "user_id=?", user.ID).
Find(&track)
sub.PlayQueue.List[i] = spec.NewTCTrackByFolder(&track, track.Album)
- sub.PlayQueue.List[i].TranscodedContentType = transcodeMIME
- sub.PlayQueue.List[i].TranscodedSuffix = transcodeSuffix
+ sub.PlayQueue.List[i].TranscodeMeta = transcodeMeta
case specid.PodcastEpisode:
pe := db.PodcastEpisode{}
- c.DB.
+ c.dbc.
Where("id=?", id.Value).
Find(&pe)
- p := db.Podcast{}
- c.DB.
- Where("id=?", pe.PodcastID).
- Find(&p)
- sub.PlayQueue.List[i] = spec.NewTCPodcastEpisode(&pe, &p)
- sub.PlayQueue.List[i].TranscodedContentType = transcodeMIME
- sub.PlayQueue.List[i].TranscodedSuffix = transcodeSuffix
+ sub.PlayQueue.List[i] = spec.NewTCPodcastEpisode(&pe)
+ sub.PlayQueue.List[i].TranscodeMeta = transcodeMeta
}
}
return sub
@@ -214,13 +246,13 @@ func (c *Controller) ServeSavePlayQueue(r *http.Request) *spec.Response {
}
user := r.Context().Value(CtxUser).(*db.User)
var queue db.PlayQueue
- c.DB.Where("user_id=?", user.ID).First(&queue)
+ c.dbc.Where("user_id=?", user.ID).First(&queue)
queue.UserID = user.ID
queue.Current = params.GetOrID("current", specid.ID{}).String()
queue.Position = params.GetOrInt("position", 0)
queue.ChangedBy = params.GetOr("c", "") // must exist, middleware checks
queue.SetItems(trackIDs)
- c.DB.Save(&queue)
+ c.dbc.Save(&queue)
return spec.NewResponse()
}
@@ -232,10 +264,11 @@ func (c *Controller) ServeGetSong(r *http.Request) *spec.Response {
return spec.NewError(10, "provide an `id` parameter")
}
var track db.Track
- err = c.DB.
+ err = c.dbc.
Where("id=?", id.Value).
Preload("Album").
Preload("Album.Artists").
+ Preload("Artists").
Preload("TrackStar", "user_id=?", user.ID).
Preload("TrackRating", "user_id=?", user.ID).
First(&track).
@@ -243,8 +276,14 @@ func (c *Controller) ServeGetSong(r *http.Request) *spec.Response {
if errors.Is(err, gorm.ErrRecordNotFound) {
return spec.NewError(10, "couldn't find a track with that id")
}
+
+ transcodeMeta := streamGetTranscodeMeta(c.dbc, user.ID, params.GetOr("c", ""))
+
sub := spec.NewResponse()
sub.Track = spec.NewTrackByTags(&track, track.Album)
+
+ sub.Track.TranscodeMeta = transcodeMeta
+
return sub
}
@@ -252,10 +291,11 @@ func (c *Controller) ServeGetRandomSongs(r *http.Request) *spec.Response {
params := r.Context().Value(CtxParams).(params.Params)
user := r.Context().Value(CtxUser).(*db.User)
var tracks []*db.Track
- q := c.DB.DB.
+ q := c.dbc.DB.
Limit(params.GetOrInt("size", 10)).
Preload("Album").
Preload("Album.Artists").
+ Preload("Artists").
Preload("TrackStar", "user_id=?", user.ID).
Preload("TrackRating", "user_id=?", user.ID).
Joins("JOIN albums ON tracks.album_id=albums.id").
@@ -270,7 +310,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.musicPaths, params); m != "" {
q = q.Where("albums.root_dir=?", m)
}
if err := q.Find(&tracks).Error; err != nil {
@@ -280,12 +320,11 @@ func (c *Controller) ServeGetRandomSongs(r *http.Request) *spec.Response {
sub.RandomTracks = &spec.RandomTracks{}
sub.RandomTracks.List = make([]*spec.TrackChild, len(tracks))
- transcodeMIME, transcodeSuffix := streamGetTransPrefProfile(c.DB, user.ID, params.GetOr("c", ""))
+ transcodeMeta := streamGetTranscodeMeta(c.dbc, user.ID, params.GetOr("c", ""))
for i, track := range tracks {
sub.RandomTracks.List[i] = spec.NewTrackByTags(track, track.Album)
- sub.RandomTracks.List[i].TranscodedContentType = transcodeMIME
- sub.RandomTracks.List[i].TranscodedSuffix = transcodeSuffix
+ sub.RandomTracks.List[i].TranscodeMeta = transcodeMeta
}
return sub
}
@@ -297,7 +336,7 @@ func (c *Controller) ServeJukebox(r *http.Request) *spec.Response { // nolint:go
trackPaths := func(ids []specid.ID) ([]string, error) {
var paths []string
for _, id := range ids {
- r, err := specidpaths.Locate(c.DB, c.PodcastsPath, id)
+ r, err := specidpaths.Locate(c.dbc, id)
if err != nil {
return nil, fmt.Errorf("find track by id: %w", err)
}
@@ -306,7 +345,7 @@ func (c *Controller) ServeJukebox(r *http.Request) *spec.Response { // nolint:go
return paths, nil
}
getSpecStatus := func() (*spec.JukeboxStatus, error) {
- status, err := c.Jukebox.GetStatus()
+ status, err := c.jukebox.GetStatus()
if err != nil {
return nil, fmt.Errorf("get status: %w", err)
}
@@ -319,12 +358,12 @@ func (c *Controller) ServeJukebox(r *http.Request) *spec.Response { // nolint:go
}
getSpecPlaylist := func() ([]*spec.TrackChild, error) {
var ret []*spec.TrackChild
- playlist, err := c.Jukebox.GetPlaylist()
+ playlist, err := c.jukebox.GetPlaylist()
if err != nil {
return nil, fmt.Errorf("get playlist: %w", err)
}
for _, path := range playlist {
- file, err := specidpaths.Lookup(c.DB, PathsOf(c.MusicPaths), c.PodcastsPath, path)
+ file, err := specidpaths.Lookup(c.dbc, MusicPaths(c.musicPaths), c.podcastsPath, path)
if err != nil {
return nil, fmt.Errorf("fetch track: %w", err)
}
@@ -344,7 +383,7 @@ func (c *Controller) ServeJukebox(r *http.Request) *spec.Response { // nolint:go
if err != nil {
return spec.NewError(0, "error creating playlist items: %v", err)
}
- if err := c.Jukebox.SetPlaylist(paths); err != nil {
+ if err := c.jukebox.SetPlaylist(paths); err != nil {
return spec.NewError(0, "error setting playlist: %v", err)
}
case "add":
@@ -353,11 +392,11 @@ func (c *Controller) ServeJukebox(r *http.Request) *spec.Response { // nolint:go
if err != nil {
return spec.NewError(10, "error creating playlist items: %v", err)
}
- if err := c.Jukebox.AppendToPlaylist(paths); err != nil {
+ if err := c.jukebox.AppendToPlaylist(paths); err != nil {
return spec.NewError(0, "error appending to playlist: %v", err)
}
case "clear":
- if err := c.Jukebox.ClearPlaylist(); err != nil {
+ if err := c.jukebox.ClearPlaylist(); err != nil {
return spec.NewError(0, "error clearing playlist: %v", err)
}
case "remove":
@@ -365,15 +404,15 @@ func (c *Controller) ServeJukebox(r *http.Request) *spec.Response { // nolint:go
if err != nil {
return spec.NewError(10, "please provide an id for remove actions")
}
- if err := c.Jukebox.RemovePlaylistIndex(index); err != nil {
+ if err := c.jukebox.RemovePlaylistIndex(index); err != nil {
return spec.NewError(0, "error removing: %v", err)
}
case "stop":
- if err := c.Jukebox.Pause(); err != nil {
+ if err := c.jukebox.Pause(); err != nil {
return spec.NewError(0, "error stopping: %v", err)
}
case "start":
- if err := c.Jukebox.Play(); err != nil {
+ if err := c.jukebox.Play(); err != nil {
return spec.NewError(0, "error starting: %v", err)
}
case "skip":
@@ -382,7 +421,7 @@ func (c *Controller) ServeJukebox(r *http.Request) *spec.Response { // nolint:go
return spec.NewError(10, "please provide an index for skip actions")
}
offset, _ := params.GetInt("offset")
- if err := c.Jukebox.SkipToPlaylistIndex(index, offset); err != nil {
+ if err := c.jukebox.SkipToPlaylistIndex(index, offset); err != nil {
return spec.NewError(0, "error skipping: %v", err)
}
case "get":
@@ -405,7 +444,7 @@ func (c *Controller) ServeJukebox(r *http.Request) *spec.Response { // nolint:go
if err != nil {
return spec.NewError(10, "please provide a valid gain param")
}
- if err := c.Jukebox.SetVolumePct(int(math.Min(gain, 1) * 100)); err != nil {
+ if err := c.jukebox.SetVolumePct(int(math.Min(gain, 1) * 100)); err != nil {
return spec.NewError(0, "error setting gain: %v", err)
}
}
@@ -424,3 +463,56 @@ func (c *Controller) ServeGetLyrics(_ *http.Request) *spec.Response {
sub.Lyrics = &spec.Lyrics{}
return sub
}
+
+func scrobbleStatsUpdateTrack(dbc *db.DB, track *db.Track, userID int, playTime time.Time) error {
+ var play db.Play
+ if err := dbc.Where("album_id=? AND user_id=?", track.AlbumID, userID).First(&play).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
+ return fmt.Errorf("find stat: %w", err)
+ }
+
+ play.AlbumID = track.AlbumID
+ play.UserID = userID
+ play.Count++ // for getAlbumList?type=frequent
+ play.Length += track.Length
+ if playTime.After(play.Time) {
+ play.Time = playTime // for getAlbumList?type=recent
+ }
+
+ if err := dbc.Save(&play).Error; err != nil {
+ return fmt.Errorf("save stat: %w", err)
+ }
+ return nil
+}
+
+func scrobbleStatsUpdatePodcastEpisode(dbc *db.DB, peID int) error {
+ var pe db.PodcastEpisode
+ if err := dbc.Where("id=?", peID).First(&pe).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
+ return fmt.Errorf("find podcast episode: %w", err)
+ }
+
+ pe.ModifiedAt = time.Now()
+
+ if err := dbc.Save(&pe).Error; err != nil {
+ return fmt.Errorf("save podcast episode: %w", err)
+ }
+ return nil
+}
+
+func getMusicFolder(musicPaths []MusicPath, p params.Params) string {
+ idx, err := p.GetInt("musicFolderId")
+ if err != nil {
+ return ""
+ }
+ if idx < 0 || idx >= len(musicPaths) {
+ return os.DevNull
+ }
+ return musicPaths[idx].Path
+}
+
+func lowerUDecOrHash(in string) string {
+ lower := unicode.ToLower(rune(in[0]))
+ if !unicode.IsLetter(lower) {
+ return "#"
+ }
+ return string(lower)
+}
diff --git a/server/ctrlsubsonic/handlers_internet_radio.go b/server/ctrlsubsonic/handlers_internet_radio.go
index f2fc21f..0d03eec 100644
--- a/server/ctrlsubsonic/handlers_internet_radio.go
+++ b/server/ctrlsubsonic/handlers_internet_radio.go
@@ -11,7 +11,7 @@ import (
func (c *Controller) ServeGetInternetRadioStations(_ *http.Request) *spec.Response {
var stations []*db.InternetRadioStation
- if err := c.DB.Find(&stations).Error; err != nil {
+ if err := c.dbc.Find(&stations).Error; err != nil {
return spec.NewError(0, "find stations: %v", err)
}
sub := spec.NewResponse()
@@ -55,7 +55,7 @@ func (c *Controller) ServeCreateInternetRadioStation(r *http.Request) *spec.Resp
station.Name = name
station.HomepageURL = homepageURL
- if err := c.DB.Save(&station).Error; err != nil {
+ if err := c.dbc.Save(&station).Error; err != nil {
return spec.NewError(0, "save station: %v", err)
}
@@ -92,7 +92,7 @@ func (c *Controller) ServeUpdateInternetRadioStation(r *http.Request) *spec.Resp
}
var station db.InternetRadioStation
- if err := c.DB.Where("id=?", stationID.Value).First(&station).Error; err != nil {
+ if err := c.dbc.Where("id=?", stationID.Value).First(&station).Error; err != nil {
return spec.NewError(70, "id not found: %v", err)
}
@@ -100,7 +100,7 @@ func (c *Controller) ServeUpdateInternetRadioStation(r *http.Request) *spec.Resp
station.Name = name
station.HomepageURL = homepageURL
- if err := c.DB.Save(&station).Error; err != nil {
+ if err := c.dbc.Save(&station).Error; err != nil {
return spec.NewError(0, "save station: %v", err)
}
return spec.NewResponse()
@@ -119,11 +119,11 @@ func (c *Controller) ServeDeleteInternetRadioStation(r *http.Request) *spec.Resp
}
var station db.InternetRadioStation
- if err := c.DB.Where("id=?", stationID.Value).First(&station).Error; err != nil {
+ if err := c.dbc.Where("id=?", stationID.Value).First(&station).Error; err != nil {
return spec.NewError(70, "id not found: %v", err)
}
- if err := c.DB.Delete(&station).Error; err != nil {
+ if err := c.dbc.Delete(&station).Error; err != nil {
return spec.NewError(70, "id not found: %v", err)
}
diff --git a/server/ctrlsubsonic/handlers_internet_radio_test.go b/server/ctrlsubsonic/handlers_internet_radio_test.go
index 18a0b4f..c266ad5 100644
--- a/server/ctrlsubsonic/handlers_internet_radio_test.go
+++ b/server/ctrlsubsonic/handlers_internet_radio_test.go
@@ -1,7 +1,9 @@
+//nolint:tparallel,paralleltest,thelper
package ctrlsubsonic
import (
"encoding/json"
+ "errors"
"net/http"
"net/http/httptest"
"net/url"
@@ -37,8 +39,10 @@ const (
newstation1HomepageURL = "https://www.kcrw.com/music/shows/eclectic24"
)
-const newstation2StreamURL = "http://media.kcrw.com/pls/kcrwsantabarbara.pls"
-const newstation2Name = "KCRW Santa Barbara"
+const (
+ newstation2StreamURL = "http://media.kcrw.com/pls/kcrwsantabarbara.pls"
+ newstation2Name = "KCRW Santa Barbara"
+)
const station3ID = "ir-3"
@@ -48,16 +52,18 @@ func TestInternetRadio(t *testing.T) {
t.Parallel()
contr := makeController(t)
- t.Run("TestInternetRadioInitialEmpty", func(t *testing.T) { testInternetRadioInitialEmpty(t, contr) })
- t.Run("TestInternetRadioBadCreates", func(t *testing.T) { testInternetRadioBadCreates(t, contr) })
- t.Run("TestInternetRadioInitialAdds", func(t *testing.T) { testInternetRadioInitialAdds(t, contr) })
- t.Run("TestInternetRadioUpdateHomepage", func(t *testing.T) { testInternetRadioUpdateHomepage(t, contr) })
- t.Run("TestInternetRadioNotAdmin", func(t *testing.T) { testInternetRadioNotAdmin(t, contr) })
- t.Run("TestInternetRadioUpdates", func(t *testing.T) { testInternetRadioUpdates(t, contr) })
- t.Run("TestInternetRadioDeletes", func(t *testing.T) { testInternetRadioDeletes(t, contr) })
+ t.Run("initial empty", func(t *testing.T) { testInternetRadioInitialEmpty(t, contr) })
+ t.Run("bad creates", func(t *testing.T) { testInternetRadioBadCreates(t, contr) })
+ t.Run("initial adds", func(t *testing.T) { testInternetRadioInitialAdds(t, contr) })
+ t.Run("update home page", func(t *testing.T) { testInternetRadioUpdateHomepage(t, contr) })
+ t.Run("not admin", func(t *testing.T) { testInternetRadioNotAdmin(t, contr) })
+ t.Run("updates", func(t *testing.T) { testInternetRadioUpdates(t, contr) })
+ t.Run("deletes", func(t *testing.T) { testInternetRadioDeletes(t, contr) })
}
-func runTestCase(t *testing.T, contr *Controller, h handlerSubsonic, q url.Values, admin bool) *spec.SubsonicResponse {
+func runTestCase(t *testing.T, h handlerSubsonic, q url.Values, admin bool) *spec.SubsonicResponse {
+ t.Helper()
+
var rr *httptest.ResponseRecorder
var req *http.Request
@@ -66,7 +72,7 @@ func runTestCase(t *testing.T, contr *Controller, h handlerSubsonic, q url.Value
} else {
rr, req = makeHTTPMock(q)
}
- contr.H(h).ServeHTTP(rr, req)
+ resp(h).ServeHTTP(rr, req)
body := rr.Body.String()
if status := rr.Code; status != http.StatusOK {
t.Fatalf("didn't give a 200\n%s", body)
@@ -74,18 +80,17 @@ func runTestCase(t *testing.T, contr *Controller, h handlerSubsonic, q url.Value
var response spec.SubsonicResponse
if err := json.Unmarshal(rr.Body.Bytes(), &response); err != nil {
- switch ty := err.(type) {
- case *json.SyntaxError:
- jsn := body[0:ty.Offset]
- jsn += "<--(Invalid Character)"
- t.Fatalf("invalid character at offset %v\n %s", ty.Offset, jsn)
- case *json.UnmarshalTypeError:
- jsn := body[0:ty.Offset]
- jsn += "<--(Invalid Type)"
- t.Fatalf("invalid type at offset %v\n %s", ty.Offset, jsn)
- default:
- t.Fatalf("json unmarshal failed: %s", err.Error())
+ var jsonSyntaxError *json.SyntaxError
+ if errors.As(err, &jsonSyntaxError) {
+ t.Fatalf("invalid character at offset %v\n %s <--", jsonSyntaxError.Offset, body[0:jsonSyntaxError.Offset])
}
+
+ var jsonUnmarshalTypeError *json.UnmarshalTypeError
+ if errors.As(err, &jsonSyntaxError) {
+ t.Fatalf("invalid type at offset %v\n %s <--", jsonUnmarshalTypeError.Offset, body[0:jsonUnmarshalTypeError.Offset])
+ }
+
+ t.Fatalf("json unmarshal failed: %v", err)
}
return &response
@@ -129,29 +134,29 @@ func testInternetRadioBadCreates(t *testing.T, contr *Controller) {
var response *spec.SubsonicResponse
// no parameters
- response = runTestCase(t, contr, contr.ServeCreateInternetRadioStation, url.Values{}, true)
+ response = runTestCase(t, contr.ServeCreateInternetRadioStation, url.Values{}, true)
checkMissingParameter(t, response)
// just one required parameter
- response = runTestCase(t, contr, contr.ServeCreateInternetRadioStation,
+ response = runTestCase(t, contr.ServeCreateInternetRadioStation,
url.Values{"streamUrl": {station1StreamURL}}, true)
checkMissingParameter(t, response)
- response = runTestCase(t, contr, contr.ServeCreateInternetRadioStation,
+ response = runTestCase(t, contr.ServeCreateInternetRadioStation,
url.Values{"name": {station1Name}}, true)
checkMissingParameter(t, response)
// bad URLs
- response = runTestCase(t, contr, contr.ServeCreateInternetRadioStation,
+ response = runTestCase(t, contr.ServeCreateInternetRadioStation,
url.Values{"streamUrl": {station1StreamURL}, "name": {station1Name}, "homepageUrl": {notAURL}}, true)
checkBadParameter(t, response)
- response = runTestCase(t, contr, contr.ServeCreateInternetRadioStation,
+ response = runTestCase(t, contr.ServeCreateInternetRadioStation,
url.Values{"streamUrl": {notAURL}, "name": {station1Name}, "homepageUrl": {station1HomepageURL}}, true)
checkBadParameter(t, response)
// check for empty get after
- response = runTestCase(t, contr, contr.ServeGetInternetRadioStations, url.Values{}, false) // no need to be admin
+ response = runTestCase(t, contr.ServeGetInternetRadioStations, url.Values{}, false) // no need to be admin
checkSuccess(t, response)
if (response.Response.InternetRadioStations == nil) || (len(response.Response.InternetRadioStations.List) != 0) {
@@ -161,7 +166,7 @@ func testInternetRadioBadCreates(t *testing.T, contr *Controller) {
func testInternetRadioInitialEmpty(t *testing.T, contr *Controller) {
// check for empty get on new DB
- response := runTestCase(t, contr, contr.ServeGetInternetRadioStations, url.Values{}, false) // no need to be admin
+ response := runTestCase(t, contr.ServeGetInternetRadioStations, url.Values{}, false) // no need to be admin
checkSuccess(t, response)
if (response.Response.InternetRadioStations == nil) || (len(response.Response.InternetRadioStations.List) != 0) {
@@ -171,15 +176,15 @@ func testInternetRadioInitialEmpty(t *testing.T, contr *Controller) {
func testInternetRadioInitialAdds(t *testing.T, contr *Controller) {
// successful adds and read back
- response := runTestCase(t, contr, contr.ServeCreateInternetRadioStation,
+ response := runTestCase(t, contr.ServeCreateInternetRadioStation,
url.Values{"streamUrl": {station1StreamURL}, "name": {station1Name}, "homepageUrl": {station1HomepageURL}}, true)
checkSuccess(t, response)
- response = runTestCase(t, contr, contr.ServeCreateInternetRadioStation,
+ response = runTestCase(t, contr.ServeCreateInternetRadioStation,
url.Values{"streamUrl": {station2StreamURL}, "name": {station2Name}}, true) // NOTE: no homepage Url
checkSuccess(t, response)
- response = runTestCase(t, contr, contr.ServeGetInternetRadioStations, url.Values{}, false) // no need to be admin
+ response = runTestCase(t, contr.ServeGetInternetRadioStations, url.Values{}, false) // no need to be admin
checkSuccess(t, response)
if response.Response.InternetRadioStations == nil {
@@ -202,16 +207,16 @@ func testInternetRadioInitialAdds(t *testing.T, contr *Controller) {
func testInternetRadioUpdateHomepage(t *testing.T, contr *Controller) {
// update empty homepage URL without other parameters (fails)
- response := runTestCase(t, contr, contr.ServeUpdateInternetRadioStation,
+ response := runTestCase(t, contr.ServeUpdateInternetRadioStation,
url.Values{"id": {station2ID}, "homepageUrl": {station2HomepageURL}}, true)
checkMissingParameter(t, response)
// update empty homepage URL properly and read back
- response = runTestCase(t, contr, contr.ServeUpdateInternetRadioStation,
+ response = runTestCase(t, contr.ServeUpdateInternetRadioStation,
url.Values{"id": {station2ID}, "streamUrl": {station2StreamURL}, "name": {station2Name}, "homepageUrl": {station2HomepageURL}}, true)
checkSuccess(t, response)
- response = runTestCase(t, contr, contr.ServeGetInternetRadioStations, url.Values{}, false) // no need to be admin
+ response = runTestCase(t, contr.ServeGetInternetRadioStations, url.Values{}, false) // no need to be admin
checkSuccess(t, response)
if response.Response.InternetRadioStations == nil {
@@ -234,19 +239,19 @@ func testInternetRadioUpdateHomepage(t *testing.T, contr *Controller) {
func testInternetRadioNotAdmin(t *testing.T, contr *Controller) {
// create, update, delete w/o admin privileges (fails and does not modify data)
- response := runTestCase(t, contr, contr.ServeCreateInternetRadioStation,
+ response := runTestCase(t, contr.ServeCreateInternetRadioStation,
url.Values{"streamUrl": {station1StreamURL}, "name": {station1Name}, "homepageUrl": {station1HomepageURL}}, false)
checkNotAdmin(t, response)
- response = runTestCase(t, contr, contr.ServeUpdateInternetRadioStation,
+ response = runTestCase(t, contr.ServeUpdateInternetRadioStation,
url.Values{"id": {station1ID}, "streamUrl": {newstation1StreamURL}, "name": {newstation1Name}, "homepageUrl": {newstation1HomepageURL}}, false)
checkNotAdmin(t, response)
- response = runTestCase(t, contr, contr.ServeDeleteInternetRadioStation,
+ response = runTestCase(t, contr.ServeDeleteInternetRadioStation,
url.Values{"id": {station1ID}}, false)
checkNotAdmin(t, response)
- response = runTestCase(t, contr, contr.ServeGetInternetRadioStations, url.Values{}, false) // no need to be admin
+ response = runTestCase(t, contr.ServeGetInternetRadioStations, url.Values{}, false) // no need to be admin
checkSuccess(t, response)
if response.Response.InternetRadioStations == nil {
@@ -269,11 +274,11 @@ func testInternetRadioNotAdmin(t *testing.T, contr *Controller) {
func testInternetRadioUpdates(t *testing.T, contr *Controller) {
// replace station 1 and read back
- response := runTestCase(t, contr, contr.ServeUpdateInternetRadioStation,
+ response := runTestCase(t, contr.ServeUpdateInternetRadioStation,
url.Values{"id": {station1ID}, "streamUrl": {newstation1StreamURL}, "name": {newstation1Name}, "homepageUrl": {newstation1HomepageURL}}, true)
checkSuccess(t, response)
- response = runTestCase(t, contr, contr.ServeGetInternetRadioStations, url.Values{}, false) // no need to be admin
+ response = runTestCase(t, contr.ServeGetInternetRadioStations, url.Values{}, false) // no need to be admin
checkSuccess(t, response)
if response.Response.InternetRadioStations == nil {
@@ -294,11 +299,11 @@ func testInternetRadioUpdates(t *testing.T, contr *Controller) {
}
// update station 2 but without homepage URL and read back
- response = runTestCase(t, contr, contr.ServeUpdateInternetRadioStation,
+ response = runTestCase(t, contr.ServeUpdateInternetRadioStation,
url.Values{"id": {station2ID}, "streamUrl": {newstation2StreamURL}, "name": {newstation2Name}}, true)
checkSuccess(t, response)
- response = runTestCase(t, contr, contr.ServeGetInternetRadioStations, url.Values{}, false) // no need to be admin
+ response = runTestCase(t, contr.ServeGetInternetRadioStations, url.Values{}, false) // no need to be admin
checkSuccess(t, response)
if response.Response.InternetRadioStations == nil {
@@ -321,11 +326,11 @@ func testInternetRadioUpdates(t *testing.T, contr *Controller) {
func testInternetRadioDeletes(t *testing.T, contr *Controller) {
// delete non-existent station 3 (fails and does not modify data)
- response := runTestCase(t, contr, contr.ServeDeleteInternetRadioStation,
+ response := runTestCase(t, contr.ServeDeleteInternetRadioStation,
url.Values{"id": {station3ID}}, true)
checkBadParameter(t, response)
- response = runTestCase(t, contr, contr.ServeGetInternetRadioStations, url.Values{}, false) // no need to be admin
+ response = runTestCase(t, contr.ServeGetInternetRadioStations, url.Values{}, false) // no need to be admin
checkSuccess(t, response)
if response.Response.InternetRadioStations == nil {
@@ -346,11 +351,11 @@ func testInternetRadioDeletes(t *testing.T, contr *Controller) {
}
// delete station 1 and recheck
- response = runTestCase(t, contr, contr.ServeDeleteInternetRadioStation,
+ response = runTestCase(t, contr.ServeDeleteInternetRadioStation,
url.Values{"id": {station1ID}}, true)
checkSuccess(t, response)
- response = runTestCase(t, contr, contr.ServeGetInternetRadioStations, url.Values{}, false) // no need to be admin
+ response = runTestCase(t, contr.ServeGetInternetRadioStations, url.Values{}, false) // no need to be admin
checkSuccess(t, response)
if response.Response.InternetRadioStations == nil {
@@ -367,11 +372,11 @@ func testInternetRadioDeletes(t *testing.T, contr *Controller) {
}
// delete station 2 and check that they're all gone
- response = runTestCase(t, contr, contr.ServeDeleteInternetRadioStation,
+ response = runTestCase(t, contr.ServeDeleteInternetRadioStation,
url.Values{"id": {station2ID}}, true)
checkSuccess(t, response)
- response = runTestCase(t, contr, contr.ServeGetInternetRadioStations, url.Values{}, false) // no need to be admin
+ response = runTestCase(t, contr.ServeGetInternetRadioStations, url.Values{}, false) // no need to be admin
checkSuccess(t, response)
if (response.Response.InternetRadioStations == nil) || (len(response.Response.InternetRadioStations.List) != 0) {
diff --git a/server/ctrlsubsonic/handlers_playlist.go b/server/ctrlsubsonic/handlers_playlist.go
index bc3c101..de03430 100644
--- a/server/ctrlsubsonic/handlers_playlist.go
+++ b/server/ctrlsubsonic/handlers_playlist.go
@@ -22,7 +22,7 @@ import (
func (c *Controller) ServeGetPlaylists(r *http.Request) *spec.Response {
params := r.Context().Value(CtxParams).(params.Params)
user := r.Context().Value(CtxUser).(*db.User)
- paths, err := c.PlaylistStore.List()
+ paths, err := c.playlistStore.List()
if err != nil {
return spec.NewError(0, "error listing playlists: %v", err)
}
@@ -31,7 +31,7 @@ func (c *Controller) ServeGetPlaylists(r *http.Request) *spec.Response {
List: []*spec.Playlist{},
}
for _, path := range paths {
- playlist, err := c.PlaylistStore.Read(path)
+ playlist, err := c.playlistStore.Read(path)
if err != nil {
return spec.NewError(0, "error reading playlist %q: %v", path, err)
}
@@ -54,7 +54,7 @@ func (c *Controller) ServeGetPlaylist(r *http.Request) *spec.Response {
if err != nil {
return spec.NewError(10, "please provide an `id` parameter")
}
- playlist, err := c.PlaylistStore.Read(playlistIDDecode(playlistID))
+ playlist, err := c.playlistStore.Read(playlistIDDecode(playlistID))
if err != nil {
return spec.NewError(70, "playlist with id %s not found", playlistID)
}
@@ -75,7 +75,7 @@ func (c *Controller) ServeCreatePlaylist(r *http.Request) *spec.Response {
playlistPath := playlistIDDecode(playlistID)
var playlist playlistp.Playlist
- if pl, _ := c.PlaylistStore.Read(playlistPath); pl != nil {
+ if pl, _ := c.playlistStore.Read(playlistPath); pl != nil {
playlist = *pl
}
@@ -94,7 +94,7 @@ func (c *Controller) ServeCreatePlaylist(r *http.Request) *spec.Response {
playlist.Items = nil
ids := params.GetOrIDList("songId", nil)
for _, id := range ids {
- r, err := specidpaths.Locate(c.DB, c.PodcastsPath, id)
+ r, err := specidpaths.Locate(c.dbc, id)
if err != nil {
return spec.NewError(0, "lookup id %v: %v", id, err)
}
@@ -104,7 +104,7 @@ func (c *Controller) ServeCreatePlaylist(r *http.Request) *spec.Response {
if playlistPath == "" {
playlistPath = playlistp.NewPath(user.ID, fmt.Sprint(time.Now().UnixMilli()))
}
- 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)
}
@@ -123,7 +123,7 @@ func (c *Controller) ServeUpdatePlaylist(r *http.Request) *spec.Response {
playlistID := params.GetFirstOr( /* default */ "", "id", "playlistId")
playlistPath := playlistIDDecode(playlistID)
- playlist, err := c.PlaylistStore.Read(playlistPath)
+ playlist, err := c.playlistStore.Read(playlistPath)
if err != nil {
return spec.NewError(0, "find playlist: %v", err)
}
@@ -154,7 +154,7 @@ func (c *Controller) ServeUpdatePlaylist(r *http.Request) *spec.Response {
// add items
if ids, err := params.GetIDList("songIdToAdd"); err == nil {
for _, id := range ids {
- item, err := specidpaths.Locate(c.DB, c.PodcastsPath, id)
+ item, err := specidpaths.Locate(c.dbc, id)
if err != nil {
return spec.NewError(0, "locate id %q: %v", id, err)
}
@@ -162,7 +162,7 @@ func (c *Controller) ServeUpdatePlaylist(r *http.Request) *spec.Response {
}
}
- 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.NewResponse()
@@ -171,7 +171,7 @@ func (c *Controller) ServeUpdatePlaylist(r *http.Request) *spec.Response {
func (c *Controller) ServeDeletePlaylist(r *http.Request) *spec.Response {
params := r.Context().Value(CtxParams).(params.Params)
playlistID := params.GetFirstOr( /* default */ "", "id", "playlistId")
- if err := c.PlaylistStore.Delete(playlistIDDecode(playlistID)); err != nil {
+ if err := c.playlistStore.Delete(playlistIDDecode(playlistID)); err != nil {
return spec.NewError(0, "delete playlist: %v", err)
}
return spec.NewResponse()
@@ -180,6 +180,7 @@ func (c *Controller) ServeDeletePlaylist(r *http.Request) *spec.Response {
func playlistIDEncode(path string) string {
return base64.URLEncoding.EncodeToString([]byte(path))
}
+
func playlistIDDecode(id string) string {
path, _ := base64.URLEncoding.DecodeString(id)
return string(path)
@@ -187,7 +188,7 @@ func playlistIDDecode(id string) string {
func playlistRender(c *Controller, params params.Params, playlistID string, playlist *playlistp.Playlist, withItems bool) (*spec.Playlist, error) {
user := &db.User{}
- if err := c.DB.Where("id=?", playlist.UserID).Find(user).Error; err != nil {
+ if err := c.dbc.Where("id=?", playlist.UserID).Find(user).Error; err != nil {
return nil, fmt.Errorf("find user by id: %w", err)
}
@@ -204,10 +205,10 @@ func playlistRender(c *Controller, params params.Params, playlistID string, play
return resp, nil
}
- transcodeMIME, transcodeSuffix := streamGetTransPrefProfile(c.DB, user.ID, params.GetOr("c", ""))
+ transcodeMeta := streamGetTranscodeMeta(c.dbc, user.ID, params.GetOr("c", ""))
for _, path := range playlist.Items {
- file, err := specidpaths.Lookup(c.DB, PathsOf(c.MusicPaths), c.PodcastsPath, path)
+ file, err := specidpaths.Lookup(c.dbc, MusicPaths(c.musicPaths), c.podcastsPath, path)
if err != nil {
log.Printf("error looking up path %q: %s", path, err)
continue
@@ -217,27 +218,22 @@ func playlistRender(c *Controller, params params.Params, playlistID string, play
switch id := file.SID(); id.Type {
case specid.Track:
var track db.Track
- if err := c.DB.Where("id=?", id.Value).Preload("Album").Preload("Album.Artists").Preload("TrackStar", "user_id=?", user.ID).Preload("TrackRating", "user_id=?", user.ID).Find(&track).Error; errors.Is(err, gorm.ErrRecordNotFound) {
+ if err := c.dbc.Where("id=?", id.Value).Preload("Album").Preload("Album.Artists").Preload("Artists").Preload("TrackStar", "user_id=?", user.ID).Preload("TrackRating", "user_id=?", user.ID).Find(&track).Error; errors.Is(err, gorm.ErrRecordNotFound) {
return nil, fmt.Errorf("load track by id: %w", err)
}
trch = spec.NewTCTrackByFolder(&track, track.Album)
resp.Duration += track.Length
case specid.PodcastEpisode:
var pe db.PodcastEpisode
- if err := c.DB.Where("id=?", id.Value).Find(&pe).Error; errors.Is(err, gorm.ErrRecordNotFound) {
+ if err := c.dbc.Preload("Podcast").Where("id=?", id.Value).Find(&pe).Error; errors.Is(err, gorm.ErrRecordNotFound) {
return nil, fmt.Errorf("load podcast episode by id: %w", err)
}
- var p db.Podcast
- if err := c.DB.Where("id=?", pe.PodcastID).Find(&p).Error; errors.Is(err, gorm.ErrRecordNotFound) {
- return nil, fmt.Errorf("load podcast by id: %w", err)
- }
- trch = spec.NewTCPodcastEpisode(&pe, &p)
+ trch = spec.NewTCPodcastEpisode(&pe)
resp.Duration += pe.Length
default:
continue
}
- trch.TranscodedContentType = transcodeMIME
- trch.TranscodedSuffix = transcodeSuffix
+ trch.TranscodeMeta = transcodeMeta
resp.List = append(resp.List, trch)
}
diff --git a/server/ctrlsubsonic/handlers_podcast.go b/server/ctrlsubsonic/handlers_podcast.go
index 90f827a..3af4852 100644
--- a/server/ctrlsubsonic/handlers_podcast.go
+++ b/server/ctrlsubsonic/handlers_podcast.go
@@ -15,7 +15,7 @@ func (c *Controller) ServeGetPodcasts(r *http.Request) *spec.Response {
params := r.Context().Value(CtxParams).(params.Params)
isIncludeEpisodes := params.GetOrBool("includeEpisodes", true)
id, _ := params.GetID("id")
- podcasts, err := c.Podcasts.GetPodcastOrAll(id.Value, isIncludeEpisodes)
+ podcasts, err := c.podcasts.GetPodcastOrAll(id.Value, isIncludeEpisodes)
if err != nil {
return spec.NewError(10, "failed get podcast(s): %s", err)
}
@@ -31,7 +31,7 @@ func (c *Controller) ServeGetPodcasts(r *http.Request) *spec.Response {
func (c *Controller) ServeGetNewestPodcasts(r *http.Request) *spec.Response {
params := r.Context().Value(CtxParams).(params.Params)
count := params.GetOrInt("count", 10)
- episodes, err := c.Podcasts.GetNewestPodcastEpisodes(count)
+ episodes, err := c.podcasts.GetNewestPodcastEpisodes(count)
if err != nil {
return spec.NewError(10, "failed get podcast(s): %s", err)
}
@@ -53,7 +53,7 @@ func (c *Controller) ServeDownloadPodcastEpisode(r *http.Request) *spec.Response
if err != nil || id.Type != specid.PodcastEpisode {
return spec.NewError(10, "please provide a valid podcast episode id")
}
- if err := c.Podcasts.DownloadEpisode(id.Value); err != nil {
+ if err := c.podcasts.DownloadEpisode(id.Value); err != nil {
return spec.NewError(10, "failed to download episode: %s", err)
}
return spec.NewResponse()
@@ -71,7 +71,7 @@ func (c *Controller) ServeCreatePodcastChannel(r *http.Request) *spec.Response {
if err != nil {
return spec.NewError(10, "failed to parse feed: %s", err)
}
- if _, err = c.Podcasts.AddNewPodcast(rssURL, feed); err != nil {
+ if _, err = c.podcasts.AddNewPodcast(rssURL, feed); err != nil {
return spec.NewError(10, "failed to add feed: %s", err)
}
return spec.NewResponse()
@@ -82,7 +82,7 @@ func (c *Controller) ServeRefreshPodcasts(r *http.Request) *spec.Response {
if !user.IsAdmin {
return spec.NewError(50, "user not admin")
}
- if err := c.Podcasts.RefreshPodcasts(); err != nil {
+ if err := c.podcasts.RefreshPodcasts(); err != nil {
return spec.NewError(10, "failed to refresh feeds: %s", err)
}
return spec.NewResponse()
@@ -98,7 +98,7 @@ func (c *Controller) ServeDeletePodcastChannel(r *http.Request) *spec.Response {
if err != nil || id.Type != specid.Podcast {
return spec.NewError(10, "please provide a valid podcast id")
}
- if err := c.Podcasts.DeletePodcast(id.Value); err != nil {
+ if err := c.podcasts.DeletePodcast(id.Value); err != nil {
return spec.NewError(10, "failed to delete podcast: %s", err)
}
return spec.NewResponse()
@@ -114,7 +114,7 @@ func (c *Controller) ServeDeletePodcastEpisode(r *http.Request) *spec.Response {
if err != nil || id.Type != specid.PodcastEpisode {
return spec.NewError(10, "please provide a valid podcast episode id")
}
- if err := c.Podcasts.DeletePodcastEpisode(id.Value); err != nil {
+ if err := c.podcasts.DeletePodcastEpisode(id.Value); err != nil {
return spec.NewError(10, "failed to delete podcast: %s", err)
}
return spec.NewResponse()
diff --git a/server/ctrlsubsonic/handlers_raw.go b/server/ctrlsubsonic/handlers_raw.go
index c21ad33..4389e19 100644
--- a/server/ctrlsubsonic/handlers_raw.go
+++ b/server/ctrlsubsonic/handlers_raw.go
@@ -9,14 +9,14 @@ import (
"log"
"net/http"
"os"
- "path"
+ "path/filepath"
"time"
"github.com/disintegration/imaging"
"github.com/jinzhu/gorm"
"go.senan.xyz/gonic/db"
- "go.senan.xyz/gonic/server/ctrlsubsonic/artistinfocache"
+ "go.senan.xyz/gonic/infocache/artistinfocache"
"go.senan.xyz/gonic/server/ctrlsubsonic/params"
"go.senan.xyz/gonic/server/ctrlsubsonic/spec"
"go.senan.xyz/gonic/server/ctrlsubsonic/specid"
@@ -30,110 +30,72 @@ import (
// b) return a non-nil spec.Response
// _but not both_
-func streamGetTransPref(dbc *db.DB, userID int, client string) (*db.TranscodePreference, error) {
- var pref db.TranscodePreference
- err := dbc.
- Where("user_id=?", userID).
- Where("client COLLATE NOCASE IN (?)", []string{"*", client}).
- Order("client DESC"). // ensure "*" is last if it's there
- First(&pref).
- Error
- if errors.Is(err, gorm.ErrRecordNotFound) {
- return nil, nil
- }
- if err != nil {
- return nil, fmt.Errorf("find transcode preference: %w", err)
- }
- return &pref, nil
-}
-
-func streamGetTransPrefProfile(dbc *db.DB, userID int, client string) (mime string, suffix string) {
- pref, _ := streamGetTransPref(dbc, userID, client)
- if pref == nil {
- return "", ""
- }
- profile, ok := transcode.UserProfiles[pref.Profile]
- if !ok {
- return "", ""
- }
- return profile.MIME(), profile.Suffix()
-}
-
-var errUnknownMediaType = fmt.Errorf("media type is unknown")
-
-func streamUpdateStats(dbc *db.DB, userID int, track *db.Track, playTime time.Time) error {
- var play db.Play
- err := dbc.
- Where("album_id=? AND user_id=?", track.AlbumID, userID).
- First(&play).
- Error
- if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
- return fmt.Errorf("find stat: %w", err)
- }
-
- play.AlbumID = track.AlbumID
- play.UserID = userID
- play.Count++ // for getAlbumList?type=frequent
- play.Length += track.Length
- if playTime.After(play.Time) {
- play.Time = playTime // for getAlbumList?type=recent
- }
-
- if err := dbc.Save(&play).Error; err != nil {
- return fmt.Errorf("save stat: %w", err)
- }
- return nil
-}
-
-func streamUpdatePodcastEpisodeStats(dbc *db.DB, peID int) error {
- var pe db.PodcastEpisode
- err := dbc.
- Where("id=?", peID).
- First(&pe).
- Error
- if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
- return fmt.Errorf("find podcast episode: %w", err)
- }
-
- pe.ModifiedAt = time.Now()
-
- if err := dbc.Save(&pe).Error; err != nil {
- return fmt.Errorf("save podcast episode: %w", err)
- }
- return nil
-}
-
const (
coverDefaultSize = 600
coverCacheFormat = "png"
)
+func (c *Controller) ServeGetCoverArt(w http.ResponseWriter, r *http.Request) *spec.Response {
+ params := r.Context().Value(CtxParams).(params.Params)
+ id, err := params.GetID("id")
+ if err != nil {
+ return spec.NewError(10, "please provide an `id` parameter")
+ }
+ size := params.GetOrInt("size", coverDefaultSize)
+ cachePath := filepath.Join(
+ c.cacheCoverPath,
+ fmt.Sprintf("%s-%d.%s", id.String(), size, coverCacheFormat),
+ )
+ _, err = os.Stat(cachePath)
+ switch {
+ case os.IsNotExist(err):
+ reader, err := coverFor(c.dbc, c.artistInfoCache, id)
+ if err != nil {
+ return spec.NewError(10, "couldn't find cover %q: %v", id, err)
+ }
+ defer reader.Close()
+
+ if err := coverScaleAndSave(reader, cachePath, size); err != nil {
+ log.Printf("error scaling cover: %v", err)
+ return nil
+ }
+ case err != nil:
+ log.Printf("error stating %q: %v", cachePath, err)
+ return nil
+ }
+
+ w.Header().Set("Cache-Control", "public, max-age=3600")
+ http.ServeFile(w, r, cachePath)
+
+ return nil
+}
+
var (
errCoverNotFound = errors.New("could not find a cover with that id")
errCoverEmpty = errors.New("no cover found")
)
// TODO: can we use specidpaths.Locate here?
-func coverFor(dbc *db.DB, artistInfoCache *artistinfocache.ArtistInfoCache, podcastPath string, id specid.ID) (io.ReadCloser, error) {
+func coverFor(dbc *db.DB, artistInfoCache *artistinfocache.ArtistInfoCache, id specid.ID) (io.ReadCloser, error) {
switch id.Type {
case specid.Album:
return coverForAlbum(dbc, id.Value)
case specid.Artist:
return coverForArtist(artistInfoCache, id.Value)
case specid.Podcast:
- return coverForPodcast(dbc, podcastPath, id.Value)
+ return coverForPodcast(dbc, id.Value)
case specid.PodcastEpisode:
- return coverGetPathPodcastEpisode(dbc, podcastPath, id.Value)
+ return coverGetPathPodcastEpisode(dbc, id.Value)
default:
return nil, errCoverNotFound
}
}
func coverForAlbum(dbc *db.DB, id int) (*os.File, error) {
- folder := &db.Album{}
+ var folder db.Album
err := dbc.DB.
Select("id, root_dir, left_path, right_path, cover").
- First(folder, id).
+ First(&folder, id).
Error
if err != nil {
return nil, fmt.Errorf("select album: %w", err)
@@ -141,7 +103,7 @@ func coverForAlbum(dbc *db.DB, id int) (*os.File, error) {
if folder.Cover == "" {
return nil, errCoverEmpty
}
- return os.Open(path.Join(folder.RootDir, folder.LeftPath, folder.RightPath, folder.Cover))
+ return os.Open(filepath.Join(folder.RootDir, folder.LeftPath, folder.RightPath, folder.Cover))
}
func coverForArtist(artistInfoCache *artistinfocache.ArtistInfoCache, id int) (io.ReadCloser, error) {
@@ -159,39 +121,33 @@ func coverForArtist(artistInfoCache *artistinfocache.ArtistInfoCache, id int) (i
return resp.Body, nil
}
-func coverForPodcast(dbc *db.DB, podcastPath string, id int) (*os.File, error) {
- podcast := &db.Podcast{}
+func coverForPodcast(dbc *db.DB, id int) (*os.File, error) {
+ var podcast db.Podcast
err := dbc.
- First(podcast, id).
+ First(&podcast, id).
Error
if err != nil {
return nil, fmt.Errorf("select podcast: %w", err)
}
- if podcast.ImagePath == "" {
+ if podcast.Image == "" {
return nil, errCoverEmpty
}
- return os.Open(path.Join(podcastPath, podcast.ImagePath))
+ return os.Open(filepath.Join(podcast.RootDir, podcast.Image))
}
-func coverGetPathPodcastEpisode(dbc *db.DB, podcastPath string, id int) (*os.File, error) {
- episode := &db.PodcastEpisode{}
+func coverGetPathPodcastEpisode(dbc *db.DB, id int) (*os.File, error) {
+ var pe db.PodcastEpisode
err := dbc.
- First(episode, id).
+ Preload("Podcast").
+ First(&pe, id).
Error
if err != nil {
return nil, fmt.Errorf("select episode: %w", err)
}
- podcast := &db.Podcast{}
- err = dbc.
- First(podcast, episode.PodcastID).
- Error
- if err != nil {
- return nil, fmt.Errorf("select podcast: %w", err)
- }
- if podcast.ImagePath == "" {
+ if pe.Podcast == nil || pe.Podcast.Image == "" {
return nil, errCoverEmpty
}
- return os.Open(path.Join(podcastPath, podcast.ImagePath))
+ return os.Open(filepath.Join(pe.Podcast.RootDir, pe.Podcast.Image))
}
func coverScaleAndSave(reader io.Reader, cachePath string, size int) error {
@@ -205,46 +161,11 @@ func coverScaleAndSave(reader io.Reader, cachePath string, size int) error {
width = src.Bounds().Dx()
}
if err = imaging.Save(imaging.Resize(src, width, 0, imaging.Lanczos), cachePath); err != nil {
- return fmt.Errorf("caching `%s`: %w", cachePath, err)
+ return fmt.Errorf("caching %q: %w", cachePath, err)
}
return nil
}
-func (c *Controller) ServeGetCoverArt(w http.ResponseWriter, r *http.Request) *spec.Response {
- params := r.Context().Value(CtxParams).(params.Params)
- id, err := params.GetID("id")
- if err != nil {
- return spec.NewError(10, "please provide an `id` parameter")
- }
- size := params.GetOrInt("size", coverDefaultSize)
- cachePath := path.Join(
- c.CacheCoverPath,
- fmt.Sprintf("%s-%d.%s", id.String(), size, coverCacheFormat),
- )
- _, err = os.Stat(cachePath)
- switch {
- case os.IsNotExist(err):
- reader, err := coverFor(c.DB, c.ArtistInfoCache, c.PodcastsPath, id)
- if err != nil {
- return spec.NewError(10, "couldn't find cover `%s`: %v", id, err)
- }
- defer reader.Close()
-
- if err := coverScaleAndSave(reader, cachePath, size); err != nil {
- log.Printf("error scaling cover: %v", err)
- return nil
- }
- case err != nil:
- log.Printf("error stating `%s`: %v", cachePath, err)
- return nil
- }
-
- w.Header().Set("Cache-Control", "public, max-age=3600")
- http.ServeFile(w, r, cachePath)
-
- return nil
-}
-
func (c *Controller) ServeStream(w http.ResponseWriter, r *http.Request) *spec.Response {
params := r.Context().Value(CtxParams).(params.Params)
user := r.Context().Value(CtxUser).(*db.User)
@@ -253,7 +174,7 @@ func (c *Controller) ServeStream(w http.ResponseWriter, r *http.Request) *spec.R
return spec.NewError(10, "please provide an `id` parameter")
}
- file, err := specidpaths.Locate(c.DB, c.PodcastsPath, id)
+ file, err := specidpaths.Locate(c.dbc, id)
if err != nil {
return spec.NewError(0, "error looking up id %s: %v", id, err)
}
@@ -263,31 +184,16 @@ func (c *Controller) ServeStream(w http.ResponseWriter, r *http.Request) *spec.R
return spec.NewError(0, "type of id does not contain audio")
}
- if track, ok := audioFile.(*db.Track); ok && track.Album != nil {
- defer func() {
- if err := streamUpdateStats(c.DB, user.ID, track, time.Now()); err != nil {
- log.Printf("error updating track status: %v", err)
- }
- }()
- }
-
- if pe, ok := audioFile.(*db.PodcastEpisode); ok {
- defer func() {
- if err := streamUpdatePodcastEpisodeStats(c.DB, pe.ID); err != nil {
- log.Printf("error updating podcast episode status: %v", err)
- }
- }()
- }
-
maxBitRate, _ := params.GetInt("maxBitRate")
format, _ := params.Get("format")
+ timeOffset, _ := params.GetInt("timeOffset")
if format == "raw" || maxBitRate >= audioFile.AudioBitrate() {
http.ServeFile(w, r, file.AbsPath())
return nil
}
- pref, err := streamGetTransPref(c.DB, user.ID, params.GetOr("c", ""))
+ pref, err := streamGetTransodePreference(c.dbc, user.ID, params.GetOr("c", ""))
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
return spec.NewError(0, "couldn't find transcode preference: %v", err)
}
@@ -303,11 +209,14 @@ func (c *Controller) ServeStream(w http.ResponseWriter, r *http.Request) *spec.R
if maxBitRate > 0 && int(profile.BitRate()) > maxBitRate {
profile = transcode.WithBitrate(profile, transcode.BitRate(maxBitRate))
}
+ if timeOffset > 0 {
+ profile = transcode.WithSeek(profile, time.Second*time.Duration(timeOffset))
+ }
log.Printf("trancoding to %q with max bitrate %dk", profile.MIME(), profile.BitRate())
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) {
return spec.NewError(0, "error transcoding: %v", err)
}
@@ -324,10 +233,42 @@ func (c *Controller) ServeGetAvatar(w http.ResponseWriter, r *http.Request) *spe
if err != nil {
return spec.NewError(10, "please provide an `username` parameter")
}
- reqUser := c.DB.GetUserByName(username)
+ reqUser := c.dbc.GetUserByName(username)
if (user != reqUser) && !user.IsAdmin {
return spec.NewError(50, "user not admin")
}
http.ServeContent(w, r, "", time.Now(), bytes.NewReader(reqUser.Avatar))
return nil
}
+
+func streamGetTransodePreference(dbc *db.DB, userID int, client string) (*db.TranscodePreference, error) {
+ var pref db.TranscodePreference
+ err := dbc.
+ Where("user_id=?", userID).
+ Where("client COLLATE NOCASE IN (?)", []string{"*", client}).
+ Order("client DESC"). // ensure "*" is last if it's there
+ First(&pref).
+ Error
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, fmt.Errorf("find transcode preference: %w", err)
+ }
+ return &pref, nil
+}
+
+func streamGetTranscodeMeta(dbc *db.DB, userID int, client string) spec.TranscodeMeta {
+ pref, _ := streamGetTransodePreference(dbc, userID, client)
+ if pref == nil {
+ return spec.TranscodeMeta{}
+ }
+ profile, ok := transcode.UserProfiles[pref.Profile]
+ if !ok {
+ return spec.TranscodeMeta{}
+ }
+ return spec.TranscodeMeta{
+ TranscodedContentType: profile.MIME(),
+ TranscodedSuffix: profile.Suffix(),
+ }
+}
diff --git a/server/ctrlsubsonic/middleware.go b/server/ctrlsubsonic/middleware.go
deleted file mode 100644
index a9ec70e..0000000
--- a/server/ctrlsubsonic/middleware.go
+++ /dev/null
@@ -1,211 +0,0 @@
-package ctrlsubsonic
-
-import (
- "context"
- "crypto/md5"
- "encoding/hex"
- "fmt"
- "log"
- "net/http"
-
- "go.senan.xyz/gonic/db"
- "go.senan.xyz/gonic/server/ctrlsubsonic/params"
- "go.senan.xyz/gonic/server/ctrlsubsonic/spec"
-
- "github.com/go-ldap/ldap"
-)
-
-func checkCredsToken(password, token, salt string) bool {
- toHash := fmt.Sprintf("%s%s", password, salt)
- hash := md5.Sum([]byte(toHash))
- expToken := hex.EncodeToString(hash[:])
- return token == expToken
-}
-
-func checkCredsBasic(password, given string) bool {
- if len(given) >= 4 && given[:4] == "enc:" {
- bytes, _ := hex.DecodeString(given[4:])
- given = string(bytes)
- }
- return password == given
-}
-
-func (c *Controller) WithParams(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- params := params.New(r)
- withParams := context.WithValue(r.Context(), CtxParams, params)
- next.ServeHTTP(w, r.WithContext(withParams))
- })
-}
-
-func (c *Controller) WithRequiredParams(next http.Handler) http.Handler {
- requiredParameters := []string{
- "u", "c",
- }
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- params := r.Context().Value(CtxParams).(params.Params)
- for _, req := range requiredParameters {
- if _, err := params.Get(req); err != nil {
- _ = writeResp(w, r, spec.NewError(10,
- "please provide a `%s` parameter", req))
- return
- }
- }
- next.ServeHTTP(w, r)
- })
-}
-
-func (c *Controller) WithUser(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")
- password, _ := params.Get("p")
- token, _ := params.Get("t")
- salt, _ := params.Get("s")
-
- passwordAuth := token == "" && salt == ""
- tokenAuth := password == ""
- if tokenAuth == passwordAuth {
- _ = writeResp(w, r, spec.NewError(10,
- "please provide `t` and `s`, or just `p`"))
- return
- }
- user := c.DB.GetUserByName(username)
-
- newLDAPUser := false
- if user == nil {
- newLDAPUser = true
-
- // Because the user wasn't found we can now try
- // to use LDAP. ldapFQDN, err := c.DB.GetSetting("ldap_fqdn")
- ldapFQDN, err := c.DB.GetSetting("ldap_fqdn")
-
- if ldapFQDN != "" && err == nil {
- // The configuration page wouldn't allow these setting to not be set
- // while LDAP is enabled (a FQDN/IP is set).
- bindUID, _ := c.DB.GetSetting("ldap_bind_user")
- bindPWD, _ := c.DB.GetSetting("ldap_bind_user_password")
- ldapPort, _ := c.DB.GetSetting("ldap_port")
- baseDN, _ := c.DB.GetSetting("ldap_base_dn")
- filter, _ := c.DB.GetSetting("ldap_filter")
- tls, _ := c.DB.GetSetting("ldap_tls")
-
- // Now, we can try to connect to the LDAP server.
- l, err := createLDAPconnection(tls, ldapFQDN, ldapPort)
- if err != nil {
- // Return a generic error.
- _ = writeResp(w, r, spec.NewError(0, "Failed to connect to LDAP server."))
- return
- }
- defer l.Close()
-
- // After we have a connection, let's try binding
- _, err = l.SimpleBind(&ldap.SimpleBindRequest{
- Username: fmt.Sprintf("uid=%s,%s", bindUID, baseDN),
- Password: bindPWD,
- })
- if err != nil {
- log.Println("Failed to bind to LDAP:", err)
- _ = writeResp(w, r, spec.NewError(40, "Wrong username or password."))
- return
- }
-
- searchReq := ldap.NewSearchRequest(
- baseDN,
- ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
- fmt.Sprintf("(&%s(uid=%s))", filter, ldap.EscapeFilter(username)),
- []string{"dn"},
- nil,
- )
-
- result, err := l.Search(searchReq)
- if err != nil {
- log.Println("failed to query LDAP:", err)
- }
-
- if len(result.Entries) > 1 {
- _ = writeResp(w, r, spec.NewError(40, "Ambiguous user: `%s`", username))
- } else if len(result.Entries) == 1 {
- user := db.User{
- Name: username,
- Password: "", // no password because we want auth to fail.
- }
-
- if err := c.DB.Create(&user).Error; err != nil {
- fmt.Println("User created via LDAP:", username)
- }
- } else {
- _ = writeResp(w, r, spec.NewError(40, "invalid username `%s`", username))
- return
- }
- } else {
- _ = writeResp(w, r, spec.NewError(40,
- "invalid username `%s`", username))
- return
- }
- }
- var credsOk bool
- if tokenAuth && !newLDAPUser && user != nil {
- credsOk = checkCredsToken(user.Password, token, salt)
- } else if !newLDAPUser && user != nil {
- credsOk = checkCredsBasic(user.Password, password)
- }
- if !credsOk {
- // Because internal authentication failed, we can now try to use LDAP, if
- // it was enabled by the user.
- ldapFQDN, err := c.DB.GetSetting("ldap_fqdn")
-
- if ldapFQDN != "" && err == nil {
- // The configuration page wouldn't allow these setting to not be set
- // while LDAP is enabled (a FQDN/IP is set).
- ldapPort, _ := c.DB.GetSetting("ldap_port")
- baseDN, _ := c.DB.GetSetting("ldap_base_dn")
- tls, _ := c.DB.GetSetting("ldap_tls")
-
- // Now, we can try to connect to the LDAP server.
- l, err := createLDAPconnection(tls, ldapFQDN, ldapPort)
- if err != nil {
- // Return a generic error.
- _ = writeResp(w, r, spec.NewError(0, "Failed to connect to LDAP server."))
- return
- }
- defer l.Close()
-
- // After we have a connection, let's try binding
- _, err = l.SimpleBind(&ldap.SimpleBindRequest{
- Username: fmt.Sprintf("uid=%s,%s", username, baseDN),
- Password: password,
- })
-
- if err == nil {
- withUser := context.WithValue(r.Context(), CtxUser, user)
- next.ServeHTTP(w, r.WithContext(withUser))
- return
- }
- }
-
- _ = writeResp(w, r, spec.NewError(40, "invalid password"))
- return
- }
- withUser := context.WithValue(r.Context(), CtxUser, user)
- next.ServeHTTP(w, r.WithContext(withUser))
- })
-}
-
-func createLDAPconnection(tls string, fqdn string, port string) (*ldap.Conn, error) {
- protocol := "ldap"
- if tls == "true" {
- protocol = "ldaps"
- }
-
- // Now, we can try to connect to the LDAP server.
- l, err := ldap.DialURL(fmt.Sprintf("%s://%s:%s", protocol, fqdn, port))
- if err != nil {
- // Warn the server and return a generic error.
- log.Println("Failed to connect to LDAP server", err)
- return nil, err
- }
-
- return l, nil
-}
\ No newline at end of file
diff --git a/server/ctrlsubsonic/params/params.go b/server/ctrlsubsonic/params/params.go
index 93312ce..022c4e2 100644
--- a/server/ctrlsubsonic/params/params.go
+++ b/server/ctrlsubsonic/params/params.go
@@ -35,100 +35,7 @@ import (
"go.senan.xyz/gonic/server/ctrlsubsonic/specid"
)
-var (
- ErrNoValues = errors.New("no values provided")
-)
-
-// some thin wrappers
-// may be needed when cleaning up parse() below
-func parseStr(in string) (string, error) { return in, nil }
-func parseInt(in string) (int, error) { return strconv.Atoi(in) }
-func parseFloat(in string) (float64, error) { return strconv.ParseFloat(in, 64) }
-func parseID(in string) (specid.ID, error) { return specid.New(in) }
-func parseBool(in string) (bool, error) { return strconv.ParseBool(in) }
-
-func parseTime(in string) (time.Time, error) {
- ms, err := strconv.Atoi(in)
- if err != nil {
- return time.Time{}, err
- }
- ns := int64(ms) * 1e6
- return time.Unix(0, ns), nil
-}
-
-func parse(values []string, i interface{}) error {
- if len(values) == 0 {
- return ErrNoValues
- }
- var err error
- switch v := i.(type) {
-
- // *T
- case *string:
- *v, err = parseStr(values[0])
- case *int:
- *v, err = parseInt(values[0])
- case *float64:
- *v, err = parseFloat(values[0])
- case *specid.ID:
- *v, err = parseID(values[0])
- case *bool:
- *v, err = parseBool(values[0])
- case *time.Time:
- *v, err = parseTime(values[0])
-
- // *[]T
- case *[]string:
- for _, value := range values {
- parsed, err := parseStr(value)
- if err != nil {
- return err
- }
- *v = append(*v, parsed)
- }
- case *[]int:
- for _, value := range values {
- parsed, err := parseInt(value)
- if err != nil {
- return err
- }
- *v = append(*v, parsed)
- }
- case *[]float64:
- for _, value := range values {
- parsed, err := parseFloat(value)
- if err != nil {
- return err
- }
- *v = append(*v, parsed)
- }
- case *[]specid.ID:
- for _, value := range values {
- parsed, err := parseID(value)
- if err != nil {
- return err
- }
- *v = append(*v, parsed)
- }
- case *[]bool:
- for _, value := range values {
- parsed, err := parseBool(value)
- if err != nil {
- return err
- }
- *v = append(*v, parsed)
- }
- case *[]time.Time:
- for _, value := range values {
- parsed, err := parseTime(value)
- if err != nil {
- return err
- }
- *v = append(*v, parsed)
- }
- }
- return err
-}
+var ErrNoValues = errors.New("no values provided")
type Params url.Values
@@ -464,3 +371,93 @@ func (p Params) GetFirstOrTime(or time.Time, keys ...string) time.Time {
}
return or
}
+
+// some thin wrappers
+// may be needed when cleaning up parse() below
+func parseStr(in string) (string, error) { return in, nil }
+func parseInt(in string) (int, error) { return strconv.Atoi(in) }
+func parseFloat(in string) (float64, error) { return strconv.ParseFloat(in, 64) }
+func parseID(in string) (specid.ID, error) { return specid.New(in) }
+func parseBool(in string) (bool, error) { return strconv.ParseBool(in) }
+
+func parseTime(in string) (time.Time, error) {
+ ms, err := strconv.Atoi(in)
+ if err != nil {
+ return time.Time{}, err
+ }
+ ns := int64(ms) * 1e6
+ return time.Unix(0, ns), nil
+}
+
+func parse(values []string, i interface{}) error {
+ if len(values) == 0 {
+ return ErrNoValues
+ }
+ var err error
+ switch v := i.(type) {
+ // *T
+ case *string:
+ *v, err = parseStr(values[0])
+ case *int:
+ *v, err = parseInt(values[0])
+ case *float64:
+ *v, err = parseFloat(values[0])
+ case *specid.ID:
+ *v, err = parseID(values[0])
+ case *bool:
+ *v, err = parseBool(values[0])
+ case *time.Time:
+ *v, err = parseTime(values[0])
+
+ // *[]T
+ case *[]string:
+ for _, value := range values {
+ parsed, err := parseStr(value)
+ if err != nil {
+ return err
+ }
+ *v = append(*v, parsed)
+ }
+ case *[]int:
+ for _, value := range values {
+ parsed, err := parseInt(value)
+ if err != nil {
+ return err
+ }
+ *v = append(*v, parsed)
+ }
+ case *[]float64:
+ for _, value := range values {
+ parsed, err := parseFloat(value)
+ if err != nil {
+ return err
+ }
+ *v = append(*v, parsed)
+ }
+ case *[]specid.ID:
+ for _, value := range values {
+ parsed, err := parseID(value)
+ if err != nil {
+ return err
+ }
+ *v = append(*v, parsed)
+ }
+ case *[]bool:
+ for _, value := range values {
+ parsed, err := parseBool(value)
+ if err != nil {
+ return err
+ }
+ *v = append(*v, parsed)
+ }
+ case *[]time.Time:
+ for _, value := range values {
+ parsed, err := parseTime(value)
+ if err != nil {
+ return err
+ }
+ *v = append(*v, parsed)
+ }
+ }
+ return err
+}
diff --git a/server/ctrlsubsonic/routes.go b/server/ctrlsubsonic/routes.go
deleted file mode 100644
index 1770614..0000000
--- a/server/ctrlsubsonic/routes.go
+++ /dev/null
@@ -1,86 +0,0 @@
-package ctrlsubsonic
-
-import "github.com/gorilla/mux"
-
-func AddRoutes(c *Controller, r *mux.Router) {
- r.Use(c.WithParams)
- r.Use(c.WithRequiredParams)
- r.Use(c.WithUser)
-
- // common
- r.Handle("/getLicense{_:(?:\\.view)?}", c.H(c.ServeGetLicence))
- r.Handle("/getMusicFolders{_:(?:\\.view)?}", c.H(c.ServeGetMusicFolders))
- r.Handle("/getScanStatus{_:(?:\\.view)?}", c.H(c.ServeGetScanStatus))
- r.Handle("/ping{_:(?:\\.view)?}", c.H(c.ServePing))
- r.Handle("/scrobble{_:(?:\\.view)?}", c.H(c.ServeScrobble))
- r.Handle("/startScan{_:(?:\\.view)?}", c.H(c.ServeStartScan))
- r.Handle("/getUser{_:(?:\\.view)?}", c.H(c.ServeGetUser))
- r.Handle("/getPlaylists{_:(?:\\.view)?}", c.H(c.ServeGetPlaylists))
- r.Handle("/getPlaylist{_:(?:\\.view)?}", c.H(c.ServeGetPlaylist))
- r.Handle("/createPlaylist{_:(?:\\.view)?}", c.H(c.ServeCreatePlaylist))
- r.Handle("/updatePlaylist{_:(?:\\.view)?}", c.H(c.ServeUpdatePlaylist))
- r.Handle("/deletePlaylist{_:(?:\\.view)?}", c.H(c.ServeDeletePlaylist))
- r.Handle("/savePlayQueue{_:(?:\\.view)?}", c.H(c.ServeSavePlayQueue))
- r.Handle("/getPlayQueue{_:(?:\\.view)?}", c.H(c.ServeGetPlayQueue))
- r.Handle("/getSong{_:(?:\\.view)?}", c.H(c.ServeGetSong))
- r.Handle("/getRandomSongs{_:(?:\\.view)?}", c.H(c.ServeGetRandomSongs))
- r.Handle("/getSongsByGenre{_:(?:\\.view)?}", c.H(c.ServeGetSongsByGenre))
- r.Handle("/jukeboxControl{_:(?:\\.view)?}", c.H(c.ServeJukebox))
- r.Handle("/getBookmarks{_:(?:\\.view)?}", c.H(c.ServeGetBookmarks))
- r.Handle("/createBookmark{_:(?:\\.view)?}", c.H(c.ServeCreateBookmark))
- r.Handle("/deleteBookmark{_:(?:\\.view)?}", c.H(c.ServeDeleteBookmark))
- r.Handle("/getTopSongs{_:(?:\\.view)?}", c.H(c.ServeGetTopSongs))
- r.Handle("/getSimilarSongs{_:(?:\\.view)?}", c.H(c.ServeGetSimilarSongs))
- r.Handle("/getSimilarSongs2{_:(?:\\.view)?}", c.H(c.ServeGetSimilarSongsTwo))
- r.Handle("/getLyrics{_:(?:\\.view)?}", c.H(c.ServeGetLyrics))
-
- // raw
- r.Handle("/getCoverArt{_:(?:\\.view)?}", c.HR(c.ServeGetCoverArt))
- r.Handle("/stream{_:(?:\\.view)?}", c.HR(c.ServeStream))
- r.Handle("/download{_:(?:\\.view)?}", c.HR(c.ServeStream))
- r.Handle("/getAvatar{_:(?:\\.view)?}", c.HR(c.ServeGetAvatar))
-
- // browse by tag
- r.Handle("/getAlbum{_:(?:\\.view)?}", c.H(c.ServeGetAlbum))
- r.Handle("/getAlbumList2{_:(?:\\.view)?}", c.H(c.ServeGetAlbumListTwo))
- r.Handle("/getArtist{_:(?:\\.view)?}", c.H(c.ServeGetArtist))
- r.Handle("/getArtists{_:(?:\\.view)?}", c.H(c.ServeGetArtists))
- r.Handle("/search3{_:(?:\\.view)?}", c.H(c.ServeSearchThree))
- r.Handle("/getArtistInfo2{_:(?:\\.view)?}", c.H(c.ServeGetArtistInfoTwo))
- r.Handle("/getStarred2{_:(?:\\.view)?}", c.H(c.ServeGetStarredTwo))
-
- // browse by folder
- r.Handle("/getIndexes{_:(?:\\.view)?}", c.H(c.ServeGetIndexes))
- r.Handle("/getMusicDirectory{_:(?:\\.view)?}", c.H(c.ServeGetMusicDirectory))
- r.Handle("/getAlbumList{_:(?:\\.view)?}", c.H(c.ServeGetAlbumList))
- r.Handle("/search2{_:(?:\\.view)?}", c.H(c.ServeSearchTwo))
- r.Handle("/getGenres{_:(?:\\.view)?}", c.H(c.ServeGetGenres))
- r.Handle("/getArtistInfo{_:(?:\\.view)?}", c.H(c.ServeGetArtistInfo))
- r.Handle("/getStarred{_:(?:\\.view)?}", c.H(c.ServeGetStarred))
-
- // star / rating
- r.Handle("/star{_:(?:\\.view)?}", c.H(c.ServeStar))
- r.Handle("/unstar{_:(?:\\.view)?}", c.H(c.ServeUnstar))
- r.Handle("/setRating{_:(?:\\.view)?}", c.H(c.ServeSetRating))
-
- // podcasts
- r.Handle("/getPodcasts{_:(?:\\.view)?}", c.H(c.ServeGetPodcasts))
- r.Handle("/getNewestPodcasts{_:(?:\\.view)?}", c.H(c.ServeGetNewestPodcasts))
- r.Handle("/downloadPodcastEpisode{_:(?:\\.view)?}", c.H(c.ServeDownloadPodcastEpisode))
- r.Handle("/createPodcastChannel{_:(?:\\.view)?}", c.H(c.ServeCreatePodcastChannel))
- r.Handle("/refreshPodcasts{_:(?:\\.view)?}", c.H(c.ServeRefreshPodcasts))
- r.Handle("/deletePodcastChannel{_:(?:\\.view)?}", c.H(c.ServeDeletePodcastChannel))
- r.Handle("/deletePodcastEpisode{_:(?:\\.view)?}", c.H(c.ServeDeletePodcastEpisode))
-
- // internet radio
- r.Handle("/getInternetRadioStations{_:(?:\\.view)?}", c.H(c.ServeGetInternetRadioStations))
- r.Handle("/createInternetRadioStation{_:(?:\\.view)?}", c.H(c.ServeCreateInternetRadioStation))
- r.Handle("/updateInternetRadioStation{_:(?:\\.view)?}", c.H(c.ServeUpdateInternetRadioStation))
- r.Handle("/deleteInternetRadioStation{_:(?:\\.view)?}", c.H(c.ServeDeleteInternetRadioStation))
-
- // middlewares should be run for not found handler
- // https://github.com/gorilla/mux/issues/416
- notFoundHandler := c.H(c.ServeNotFound)
- notFoundRoute := r.NewRoute().Handler(notFoundHandler)
- r.NotFoundHandler = notFoundRoute.GetHandler()
-}
diff --git a/server/ctrlsubsonic/spec/construct_by_folder.go b/server/ctrlsubsonic/spec/construct_by_folder.go
index 9cc65a6..dc65d4a 100644
--- a/server/ctrlsubsonic/spec/construct_by_folder.go
+++ b/server/ctrlsubsonic/spec/construct_by_folder.go
@@ -1,8 +1,7 @@
package spec
import (
- "path"
- "strings"
+ "path/filepath"
"go.senan.xyz/gonic/db"
)
@@ -13,6 +12,8 @@ func NewAlbumByFolder(f *db.Album) *Album {
ID: f.SID(),
IsDir: true,
ParentID: f.ParentSID(),
+ Album: f.RightPath,
+ Name: f.RightPath,
Title: f.RightPath,
TrackCount: f.ChildCount,
Duration: f.Duration,
@@ -62,14 +63,13 @@ func NewTCTrackByFolder(t *db.Track, parent *db.Album) *TrackChild {
Title: t.TagTitle,
TrackNumber: t.TagTrackNumber,
DiscNumber: t.TagDiscNumber,
- Path: path.Join(
+ Path: filepath.Join(
parent.LeftPath,
parent.RightPath,
t.Filename,
),
ParentID: parent.SID(),
Duration: t.Length,
- Genre: strings.Join(t.GenreStrings(), ", "),
Year: parent.TagYear,
Bitrate: t.Bitrate,
IsDir: false,
@@ -92,24 +92,36 @@ func NewTCTrackByFolder(t *db.Track, parent *db.Album) *TrackChild {
if t.TrackRating != nil {
trCh.UserRating = t.TrackRating.Rating
}
+ if len(t.Genres) > 0 {
+ trCh.Genre = t.Genres[0].Name
+ }
+ for _, g := range t.Genres {
+ trCh.Genres = append(trCh.Genres, &GenreRef{Name: g.Name})
+ }
+ for _, a := range t.Artists {
+ trCh.Artists = append(trCh.Artists, &ArtistRef{ID: a.SID(), Name: a.Name})
+ }
return trCh
}
-func NewTCPodcastEpisode(pe *db.PodcastEpisode, parent *db.Podcast) *TrackChild {
+func NewTCPodcastEpisode(pe *db.PodcastEpisode) *TrackChild {
trCh := &TrackChild{
ID: pe.SID(),
ContentType: pe.MIME(),
Suffix: pe.Ext(),
Size: pe.Size,
Title: pe.Title,
- Path: pe.Path,
- ParentID: parent.SID(),
+ ParentID: pe.SID(),
Duration: pe.Length,
Bitrate: pe.Bitrate,
IsDir: false,
Type: "podcastepisode",
CreatedAt: pe.CreatedAt,
}
+ if pe.Podcast != nil {
+ trCh.ParentID = pe.Podcast.SID()
+ trCh.Path = pe.AbsPath()
+ }
return trCh
}
diff --git a/server/ctrlsubsonic/spec/construct_by_tags.go b/server/ctrlsubsonic/spec/construct_by_tags.go
index fa9efac..afcd18b 100644
--- a/server/ctrlsubsonic/spec/construct_by_tags.go
+++ b/server/ctrlsubsonic/spec/construct_by_tags.go
@@ -1,9 +1,8 @@
package spec
import (
- "path"
+ "path/filepath"
"sort"
- "strings"
"go.senan.xyz/gonic/db"
)
@@ -12,10 +11,13 @@ func NewAlbumByTags(a *db.Album, artists []*db.Artist) *Album {
ret := &Album{
Created: a.CreatedAt,
ID: a.SID(),
+ Album: a.TagTitle,
Name: a.TagTitle,
+ Title: a.TagTitle,
Year: a.TagYear,
TrackCount: a.ChildCount,
Duration: a.Duration,
+ DisplayArtist: a.TagAlbumArtist,
AverageRating: formatRating(a.AverageRating),
}
if a.Cover != "" {
@@ -44,31 +46,32 @@ func NewAlbumByTags(a *db.Album, artists []*db.Artist) *Album {
ret.Genre = a.Genres[0].Name
}
for _, g := range a.Genres {
- ret.Genres = append(ret.Genres, g.Name)
+ ret.Genres = append(ret.Genres, &GenreRef{Name: g.Name})
}
return ret
}
func NewTrackByTags(t *db.Track, album *db.Album) *TrackChild {
ret := &TrackChild{
- ID: t.SID(),
- ContentType: t.MIME(),
- Suffix: formatExt(t.Ext()),
- ParentID: t.AlbumSID(),
- CreatedAt: t.CreatedAt,
- Size: t.Size,
- Title: t.TagTitle,
- Artist: t.TagTrackArtist,
- TrackNumber: t.TagTrackNumber,
- DiscNumber: t.TagDiscNumber,
- Path: path.Join(
+ ID: t.SID(),
+ ContentType: t.MIME(),
+ Suffix: formatExt(t.Ext()),
+ ParentID: t.AlbumSID(),
+ CreatedAt: t.CreatedAt,
+ Size: t.Size,
+ Title: t.TagTitle,
+ Artist: t.TagTrackArtist,
+ DisplayArtist: t.TagTrackArtist,
+ AlbumDisplayArtist: album.TagAlbumArtist,
+ TrackNumber: t.TagTrackNumber,
+ DiscNumber: t.TagDiscNumber,
+ Path: filepath.Join(
album.LeftPath,
album.RightPath,
t.Filename,
),
Album: album.TagTitle,
AlbumID: album.SID(),
- Genre: strings.Join(t.GenreStrings(), ", "),
Duration: t.Length,
Bitrate: t.Bitrate,
Type: "music",
@@ -90,6 +93,18 @@ func NewTrackByTags(t *db.Track, album *db.Album) *TrackChild {
})
ret.ArtistID = album.Artists[0].SID()
}
+ if len(t.Genres) > 0 {
+ ret.Genre = t.Genres[0].Name
+ }
+ for _, g := range t.Genres {
+ ret.Genres = append(ret.Genres, &GenreRef{Name: g.Name})
+ }
+ for _, a := range t.Artists {
+ ret.Artists = append(ret.Artists, &ArtistRef{ID: a.SID(), Name: a.Name})
+ }
+ for _, a := range album.Artists {
+ ret.AlbumArtists = append(ret.AlbumArtists, &ArtistRef{ID: a.SID(), Name: a.Name})
+ }
return ret
}
diff --git a/server/ctrlsubsonic/spec/construct_podcast.go b/server/ctrlsubsonic/spec/construct_podcast.go
index 5f50597..70e51ce 100644
--- a/server/ctrlsubsonic/spec/construct_podcast.go
+++ b/server/ctrlsubsonic/spec/construct_podcast.go
@@ -1,13 +1,13 @@
package spec
import (
- "jaytaylor.com/html2text"
"go.senan.xyz/gonic/db"
+ "jaytaylor.com/html2text"
)
func NewPodcastChannel(p *db.Podcast) *PodcastChannel {
desc, err := html2text.FromString(p.Description, html2text.Options{TextOnly: true})
- if (err != nil) {
+ if err != nil {
desc = ""
}
ret := &PodcastChannel{
@@ -26,31 +26,34 @@ func NewPodcastChannel(p *db.Podcast) *PodcastChannel {
return ret
}
-func NewPodcastEpisode(e *db.PodcastEpisode) *PodcastEpisode {
- if e == nil {
+func NewPodcastEpisode(pe *db.PodcastEpisode) *PodcastEpisode {
+ if pe == nil {
return nil
}
- desc, err := html2text.FromString(e.Description, html2text.Options{TextOnly: true})
- if (err != nil) {
+ desc, err := html2text.FromString(pe.Description, html2text.Options{TextOnly: true})
+ if err != nil {
desc = ""
}
- return &PodcastEpisode{
- ID: e.SID(),
- StreamID: e.SID(),
- ContentType: e.MIME(),
- ChannelID: e.PodcastSID(),
- Title: e.Title,
+ r := &PodcastEpisode{
+ ID: pe.SID(),
+ StreamID: pe.SID(),
+ ContentType: pe.MIME(),
+ ChannelID: pe.PodcastSID(),
+ Title: pe.Title,
Description: desc,
- Status: string(e.Status),
- CoverArt: e.PodcastSID(),
- PublishDate: *e.PublishDate,
+ Status: string(pe.Status),
+ CoverArt: pe.PodcastSID(),
+ PublishDate: *pe.PublishDate,
Genre: "Podcast",
- Duration: e.Length,
- Year: e.PublishDate.Year(),
- Suffix: formatExt(e.Ext()),
- BitRate: e.Bitrate,
+ Duration: pe.Length,
+ Year: pe.PublishDate.Year(),
+ Suffix: formatExt(pe.Ext()),
+ BitRate: pe.Bitrate,
IsDir: false,
- Path: e.Path,
- Size: e.Size,
+ Size: pe.Size,
}
+ if pe.Podcast != nil {
+ r.Path = pe.AbsPath()
+ }
+ return r
}
diff --git a/server/ctrlsubsonic/spec/spec.go b/server/ctrlsubsonic/spec/spec.go
index 6a500c8..9ed8677 100644
--- a/server/ctrlsubsonic/spec/spec.go
+++ b/server/ctrlsubsonic/spec/spec.go
@@ -26,8 +26,10 @@ type Response struct {
XMLNS string `xml:"xmlns,attr" json:"-"`
// https://opensubsonic.netlify.app/docs/responses/subsonic-response/
- Type string `xml:"type,attr" json:"type"`
- ServerVersion string `xml:"serverVersion,attr" json:"serverVersion"`
+ Type string `xml:"type,attr" json:"type"`
+ ServerVersion string `xml:"serverVersion,attr" json:"serverVersion"`
+ OpenSubsonic bool `xml:"openSubsonic,attr" json:"openSubsonic"`
+ OpenSubsonicExtensions *OpenSubsonicExtensions `xml:"openSubsonicExtensions" json:"openSubsonicExtensions,omitempty"`
Error *Error `xml:"error" json:"error,omitempty"`
Albums *Albums `xml:"albumList" json:"albumList,omitempty"`
@@ -50,6 +52,7 @@ type Response struct {
Playlist *Playlist `xml:"playlist" json:"playlist,omitempty"`
ArtistInfo *ArtistInfo `xml:"artistInfo" json:"artistInfo,omitempty"`
ArtistInfoTwo *ArtistInfo `xml:"artistInfo2" json:"artistInfo2,omitempty"`
+ AlbumInfo *AlbumInfo `xml:"albumInfo" json:"albumInfo,omitempty"`
Genres *Genres `xml:"genres" json:"genres,omitempty"`
PlayQueue *PlayQueue `xml:"playQueue" json:"playQueue,omitempty"`
JukeboxStatus *JukeboxStatus `xml:"jukeboxStatus" json:"jukeboxStatus,omitempty"`
@@ -73,6 +76,7 @@ func NewResponse() *Response {
Version: apiVersion,
Type: gonic.Name,
ServerVersion: gonic.Version,
+ OpenSubsonic: true,
}
}
@@ -94,17 +98,13 @@ type Error struct {
}
func NewError(code int, message string, a ...interface{}) *Response {
- return &Response{
- Status: "failed",
- XMLNS: xmlns,
- Version: apiVersion,
- Error: &Error{
- Code: code,
- Message: fmt.Sprintf(message, a...),
- },
- Type: gonic.Name,
- ServerVersion: gonic.Version,
+ r := NewResponse()
+ r.Status = "failed"
+ r.Error = &Error{
+ Code: code,
+ Message: fmt.Sprintf(message, a...),
}
+ return r
}
type Albums struct {
@@ -116,27 +116,37 @@ type ArtistRef struct {
Name string `xml:"name,attr" json:"name"`
}
+type GenreRef struct {
+ Name string `xml:"name,attr" json:"name"`
+}
+
+// https://opensubsonic.netlify.app/docs/responses/albumid3/
type Album struct {
- // common
- ID *specid.ID `xml:"id,attr,omitempty" json:"id"`
- CoverID *specid.ID `xml:"coverArt,attr,omitempty" json:"coverArt,omitempty"`
- ArtistID *specid.ID `xml:"artistId,attr,omitempty" json:"artistId,omitempty"`
- Artist string `xml:"artist,attr,omitempty" json:"artist,omitempty"`
- Artists []*ArtistRef `xml:"artists,omitempty" json:"artists,omitempty"`
- Created time.Time `xml:"created,attr,omitempty" json:"created,omitempty"`
- // browsing by folder (eg. getAlbumList)
+ ID *specid.ID `xml:"id,attr,omitempty" json:"id"`
+ Created time.Time `xml:"created,attr,omitempty" json:"created,omitempty"`
+
+ // legacy or single tag mode
+ ArtistID *specid.ID `xml:"artistId,attr,omitempty" json:"artistId,omitempty"`
+ Artist string `xml:"artist,attr,omitempty" json:"artist,omitempty"`
+
+ Artists []*ArtistRef `xml:"artists,omitempty" json:"artists,omitempty"`
+ DisplayArtist string `xml:"diplayArtist,attr,omitempty" json:"displayArtist,omitempty"`
+
+ // folder stuff
Title string `xml:"title,attr,omitempty" json:"title"`
Album string `xml:"album,attr,omitempty" json:"album"`
ParentID *specid.ID `xml:"parent,attr,omitempty" json:"parent,omitempty"`
IsDir bool `xml:"isDir,attr,omitempty" json:"isDir,omitempty"`
- // browsing by tags (eg. getAlbumList2)
+ CoverID *specid.ID `xml:"coverArt,attr,omitempty" json:"coverArt,omitempty"`
+
Name string `xml:"name,attr" json:"name"`
TrackCount int `xml:"songCount,attr" json:"songCount"`
Duration int `xml:"duration,attr" json:"duration"`
Genre string `xml:"genre,attr,omitempty" json:"genre,omitempty"`
- Genres []string `xml:"genres,omitempty" json:"genres,omitempty"`
+ Genres []*GenreRef `xml:"genres,omitempty" json:"genres,omitempty"`
Year int `xml:"year,attr,omitempty" json:"year,omitempty"`
Tracks []*TrackChild `xml:"song,omitempty" json:"song,omitempty"`
+
// star / rating
Starred *time.Time `xml:"starred,attr,omitempty" json:"starred,omitempty"`
UserRating int `xml:"userRating,attr,omitempty" json:"userRating,omitempty"`
@@ -151,35 +161,51 @@ type TracksByGenre struct {
List []*TrackChild `xml:"song" json:"song"`
}
+type TranscodeMeta struct {
+ TranscodedContentType string `xml:"transcodedContentType,attr,omitempty" json:"transcodedContentType,omitempty"`
+ TranscodedSuffix string `xml:"transcodedSuffix,attr,omitempty" json:"transcodedSuffix,omitempty"`
+}
+
+// https://opensubsonic.netlify.app/docs/responses/child/
type TrackChild struct {
- ID *specid.ID `xml:"id,attr,omitempty" json:"id,omitempty"`
- Album string `xml:"album,attr,omitempty" json:"album,omitempty"`
- AlbumID *specid.ID `xml:"albumId,attr,omitempty" json:"albumId,omitempty"`
- Artist string `xml:"artist,attr,omitempty" json:"artist,omitempty"`
- ArtistID *specid.ID `xml:"artistId,attr,omitempty" json:"artistId,omitempty"`
- Bitrate int `xml:"bitRate,attr,omitempty" json:"bitRate,omitempty"`
- ContentType string `xml:"contentType,attr,omitempty" json:"contentType,omitempty"`
- TranscodedContentType string `xml:"transcodedContentType,attr,omitempty" json:"transcodedContentType,omitempty"`
- CoverID *specid.ID `xml:"coverArt,attr,omitempty" json:"coverArt,omitempty"`
- CreatedAt time.Time `xml:"created,attr,omitempty" json:"created,omitempty"`
- Duration int `xml:"duration,attr,omitempty" json:"duration,omitempty"`
- Genre string `xml:"genre,attr,omitempty" json:"genre,omitempty"`
- IsDir bool `xml:"isDir,attr" json:"isDir"`
- IsVideo bool `xml:"isVideo,attr" json:"isVideo"`
- ParentID *specid.ID `xml:"parent,attr,omitempty" json:"parent,omitempty"`
- Path string `xml:"path,attr,omitempty" json:"path,omitempty"`
- Size int `xml:"size,attr,omitempty" json:"size,omitempty"`
- Suffix string `xml:"suffix,attr,omitempty" json:"suffix,omitempty"`
- TranscodedSuffix string `xml:"transcodedSuffix,attr,omitempty" json:"transcodedSuffix,omitempty"`
- Title string `xml:"title,attr" json:"title"`
- TrackNumber int `xml:"track,attr,omitempty" json:"track,omitempty"`
- DiscNumber int `xml:"discNumber,attr,omitempty" json:"discNumber,omitempty"`
- Type string `xml:"type,attr,omitempty" json:"type,omitempty"`
- Year int `xml:"year,attr,omitempty" json:"year,omitempty"`
+ ID *specid.ID `xml:"id,attr,omitempty" json:"id,omitempty"`
+ Album string `xml:"album,attr,omitempty" json:"album,omitempty"`
+ AlbumID *specid.ID `xml:"albumId,attr,omitempty" json:"albumId,omitempty"`
+
+ // legacy or single tag mode
+ Artist string `xml:"artist,attr,omitempty" json:"artist,omitempty"`
+ ArtistID *specid.ID `xml:"artistId,attr,omitempty" json:"artistId,omitempty"`
+
+ Artists []*ArtistRef `xml:"artists,omitempty" json:"artists,omitempty"`
+ DisplayArtist string `xml:"diplayArtist,attr,omitempty" json:"displayArtist,omitempty"`
+
+ AlbumArtists []*ArtistRef `xml:"albumArtists,omitempty" json:"albumArtists,omitempty"`
+ AlbumDisplayArtist string `xml:"diplayAlbumArtist,attr,omitempty" json:"displayAlbumArtist,omitempty"`
+
+ Bitrate int `xml:"bitRate,attr,omitempty" json:"bitRate,omitempty"`
+ ContentType string `xml:"contentType,attr,omitempty" json:"contentType,omitempty"`
+ CoverID *specid.ID `xml:"coverArt,attr,omitempty" json:"coverArt,omitempty"`
+ CreatedAt time.Time `xml:"created,attr,omitempty" json:"created,omitempty"`
+ Duration int `xml:"duration,attr,omitempty" json:"duration,omitempty"`
+ Genre string `xml:"genre,attr,omitempty" json:"genre,omitempty"`
+ Genres []*GenreRef `xml:"genres,omitempty" json:"genres,omitempty"`
+ IsDir bool `xml:"isDir,attr" json:"isDir"`
+ IsVideo bool `xml:"isVideo,attr" json:"isVideo"`
+ ParentID *specid.ID `xml:"parent,attr,omitempty" json:"parent,omitempty"`
+ Path string `xml:"path,attr,omitempty" json:"path,omitempty"`
+ Size int `xml:"size,attr,omitempty" json:"size,omitempty"`
+ Suffix string `xml:"suffix,attr,omitempty" json:"suffix,omitempty"`
+ Title string `xml:"title,attr" json:"title"`
+ TrackNumber int `xml:"track,attr,omitempty" json:"track,omitempty"`
+ DiscNumber int `xml:"discNumber,attr,omitempty" json:"discNumber,omitempty"`
+ Type string `xml:"type,attr,omitempty" json:"type,omitempty"`
+ Year int `xml:"year,attr,omitempty" json:"year,omitempty"`
// star / rating
Starred *time.Time `xml:"starred,attr,omitempty" json:"starred,omitempty"`
UserRating int `xml:"userRating,attr,omitempty" json:"userRating,omitempty"`
AverageRating string `xml:"averageRating,attr,omitempty" json:"averageRating,omitempty"`
+
+ TranscodeMeta
}
type Artists struct {
@@ -292,7 +318,13 @@ type ArtistInfo struct {
MediumImageURL string `xml:"mediumImageUrl" json:"mediumImageUrl"`
LargeImageURL string `xml:"largeImageUrl" json:"largeImageUrl"`
ArtistImageURL string `xml:"artistImageUrl" json:"artistImageUrl"` // not sure where this comes from but other clients seem to expect it
- Similar []*Artist `xml:"similarArtist,omitempty" json:"similarArtist,omitempty"`
+ Similar []*Artist `xml:"similarArtist,omitempty" json:"similarArtist,omitempty"`
+}
+
+type AlbumInfo struct {
+ Notes string `xml:"notes" json:"notes"`
+ MusicBrainzID string `xml:"musicBrainzId" json:"musicBrainzId"`
+ LastFMURL string `xml:"lastFmUrl" json:"lastFmUrl"`
}
type Genres struct {
@@ -300,9 +332,9 @@ type Genres struct {
}
type Genre struct {
- Name string `xml:",chardata" json:"value"`
- SongCount int `xml:"songCount,attr,omitempty" json:"songCount,omitempty"`
- AlbumCount int `xml:"albumCount,attr,omitempty" json:"albumCount,omitempty"`
+ Name string `xml:",chardata" json:"value"`
+ SongCount int `xml:"songCount,attr" json:"songCount"`
+ AlbumCount int `xml:"albumCount,attr" json:"albumCount"`
}
type PlayQueue struct {
@@ -420,6 +452,13 @@ type Lyrics struct {
Title string `xml:"title,attr,omitempty" json:"title,omitempty"`
}
+type OpenSubsonicExtension struct {
+ Name string `xml:"name,attr" json:"name"`
+ Versions []int `xml:"versions" json:"versions"`
+}
+
+type OpenSubsonicExtensions []OpenSubsonicExtension
+
func formatRating(rating float64) string {
if rating == 0 {
return ""
diff --git a/server/ctrlsubsonic/specid/ids.go b/server/ctrlsubsonic/specid/ids.go
index 75c6496..7bc0469 100644
--- a/server/ctrlsubsonic/specid/ids.go
+++ b/server/ctrlsubsonic/specid/ids.go
@@ -30,18 +30,17 @@ const (
separator = "-"
)
+//nolint:musttag
type ID struct {
Type IDT
Value int
}
func New(in string) (ID, error) {
- parts := strings.Split(in, separator)
- if len(parts) != 2 {
+ partType, partValue, ok := strings.Cut(in, separator)
+ if !ok {
return ID{}, ErrBadSeparator
}
- partType := parts[0]
- partValue := parts[1]
val, err := strconv.Atoi(partValue)
if err != nil {
return ID{}, fmt.Errorf("%q: %w", partValue, ErrNotAnInt)
diff --git a/server/ctrlsubsonic/specid/ids_test.go b/server/ctrlsubsonic/specid/ids_test.go
index fadd3ff..d3e5303 100644
--- a/server/ctrlsubsonic/specid/ids_test.go
+++ b/server/ctrlsubsonic/specid/ids_test.go
@@ -6,6 +6,8 @@ import (
)
func TestParseID(t *testing.T) {
+ t.Parallel()
+
tcases := []struct {
param string
expType IDT
@@ -20,9 +22,12 @@ func TestParseID(t *testing.T) {
{param: "1", expErr: ErrBadSeparator},
{param: "al-howdy", expErr: ErrNotAnInt},
}
+
for _, tcase := range tcases {
tcase := tcase // pin
t.Run(tcase.param, func(t *testing.T) {
+ t.Parallel()
+
act, err := New(tcase.param)
if !errors.Is(err, tcase.expErr) {
t.Fatalf("expected err %q, got %q", tcase.expErr, err)
diff --git a/server/ctrlsubsonic/specidpaths/specidpaths.go b/server/ctrlsubsonic/specidpaths/specidpaths.go
index 2ecf892..c054ee1 100644
--- a/server/ctrlsubsonic/specidpaths/specidpaths.go
+++ b/server/ctrlsubsonic/specidpaths/specidpaths.go
@@ -9,8 +9,10 @@ import (
"go.senan.xyz/gonic/server/ctrlsubsonic/specid"
)
-var ErrNotAbs = errors.New("not abs")
-var ErrNotFound = errors.New("not found")
+var (
+ ErrNotAbs = errors.New("not abs")
+ ErrNotFound = errors.New("not found")
+)
type Result interface {
SID() *specid.ID
@@ -18,21 +20,17 @@ type Result interface {
}
// Locate maps a specid to its location on the filesystem
-func Locate(dbc *db.DB, podcastsPath string, id specid.ID) (Result, error) {
+func Locate(dbc *db.DB, id specid.ID) (Result, error) {
switch id.Type {
case specid.Track:
var track db.Track
- if err := dbc.Preload("Album").Where("id=?", id.Value).Find(&track).Error; err == nil {
- return &track, nil
- }
+ return &track, dbc.Preload("Album").Where("id=?", id.Value).Find(&track).Error
case specid.PodcastEpisode:
var pe db.PodcastEpisode
- if err := dbc.Where("id=? AND status=?", id.Value, db.PodcastEpisodeStatusCompleted).Find(&pe).Error; err == nil {
- pe.AbsP = filepath.Join(podcastsPath, pe.Path)
- return &pe, err
- }
+ return &pe, dbc.Preload("Podcast").Where("id=? AND status=?", id.Value, db.PodcastEpisodeStatusCompleted).Find(&pe).Error
+ default:
+ return nil, ErrNotFound
}
- return nil, ErrNotFound
}
// Locate maps a location on the filesystem to a specid
@@ -42,9 +40,13 @@ func Lookup(dbc *db.DB, musicPaths []string, podcastsPath string, path string) (
}
if strings.HasPrefix(path, podcastsPath) {
- path, _ = filepath.Rel(podcastsPath, path)
+ podcastPath, episodeFilename := filepath.Split(path)
+ q := dbc.
+ Joins(`JOIN podcasts ON podcasts.id=podcast_episodes.podcast_id`).
+ Where(`podcasts.root_dir=? AND podcast_episodes.filename=?`, filepath.Clean(podcastPath), filepath.Clean(episodeFilename))
+
var pe db.PodcastEpisode
- if err := dbc.Where(`path=?`, path).First(&pe).Error; err == nil {
+ if err := q.First(&pe).Error; err == nil {
return &pe, nil
}
return nil, ErrNotFound
diff --git a/server/ctrlsubsonic/testdata/test_get_album_list_alpha_artist b/server/ctrlsubsonic/testdata/test_get_album_list_alpha_artist
index 568a446..ac0fcaa 100644
--- a/server/ctrlsubsonic/testdata/test_get_album_list_alpha_artist
+++ b/server/ctrlsubsonic/testdata/test_get_album_list_alpha_artist
@@ -4,122 +4,123 @@
"version": "1.15.0",
"type": "gonic",
"serverVersion": "",
+ "openSubsonic": true,
"albumList": {
"album": [
{
"id": "al-3",
- "coverArt": "al-3",
- "artist": "artist-0",
"created": "2019-11-30T00:00:00Z",
+ "artist": "artist-0",
"title": "album-0",
- "album": "",
+ "album": "album-0",
"parent": "al-2",
"isDir": true,
- "name": "",
+ "coverArt": "al-3",
+ "name": "album-0",
"songCount": 3,
"duration": 300
},
{
"id": "al-4",
- "coverArt": "al-4",
- "artist": "artist-0",
"created": "2019-11-30T00:00:00Z",
+ "artist": "artist-0",
"title": "album-1",
- "album": "",
+ "album": "album-1",
"parent": "al-2",
"isDir": true,
- "name": "",
+ "coverArt": "al-4",
+ "name": "album-1",
"songCount": 3,
"duration": 300
},
{
"id": "al-5",
- "coverArt": "al-5",
- "artist": "artist-0",
"created": "2019-11-30T00:00:00Z",
+ "artist": "artist-0",
"title": "album-2",
- "album": "",
+ "album": "album-2",
"parent": "al-2",
"isDir": true,
- "name": "",
+ "coverArt": "al-5",
+ "name": "album-2",
"songCount": 3,
"duration": 300
},
{
"id": "al-7",
- "coverArt": "al-7",
- "artist": "artist-1",
"created": "2019-11-30T00:00:00Z",
+ "artist": "artist-1",
"title": "album-0",
- "album": "",
+ "album": "album-0",
"parent": "al-6",
"isDir": true,
- "name": "",
+ "coverArt": "al-7",
+ "name": "album-0",
"songCount": 3,
"duration": 300
},
{
"id": "al-8",
- "coverArt": "al-8",
- "artist": "artist-1",
"created": "2019-11-30T00:00:00Z",
+ "artist": "artist-1",
"title": "album-1",
- "album": "",
+ "album": "album-1",
"parent": "al-6",
"isDir": true,
- "name": "",
+ "coverArt": "al-8",
+ "name": "album-1",
"songCount": 3,
"duration": 300
},
{
"id": "al-9",
- "coverArt": "al-9",
- "artist": "artist-1",
"created": "2019-11-30T00:00:00Z",
+ "artist": "artist-1",
"title": "album-2",
- "album": "",
+ "album": "album-2",
"parent": "al-6",
"isDir": true,
- "name": "",
+ "coverArt": "al-9",
+ "name": "album-2",
"songCount": 3,
"duration": 300
},
{
"id": "al-11",
- "coverArt": "al-11",
- "artist": "artist-2",
"created": "2019-11-30T00:00:00Z",
+ "artist": "artist-2",
"title": "album-0",
- "album": "",
+ "album": "album-0",
"parent": "al-10",
"isDir": true,
- "name": "",
+ "coverArt": "al-11",
+ "name": "album-0",
"songCount": 3,
"duration": 300
},
{
"id": "al-12",
- "coverArt": "al-12",
- "artist": "artist-2",
"created": "2019-11-30T00:00:00Z",
+ "artist": "artist-2",
"title": "album-1",
- "album": "",
+ "album": "album-1",
"parent": "al-10",
"isDir": true,
- "name": "",
+ "coverArt": "al-12",
+ "name": "album-1",
"songCount": 3,
"duration": 300
},
{
"id": "al-13",
- "coverArt": "al-13",
- "artist": "artist-2",
"created": "2019-11-30T00:00:00Z",
+ "artist": "artist-2",
"title": "album-2",
- "album": "",
+ "album": "album-2",
"parent": "al-10",
"isDir": true,
- "name": "",
+ "coverArt": "al-13",
+ "name": "album-2",
"songCount": 3,
"duration": 300
}
diff --git a/server/ctrlsubsonic/testdata/test_get_album_list_alpha_name b/server/ctrlsubsonic/testdata/test_get_album_list_alpha_name
index f55e489..42040ae 100644
--- a/server/ctrlsubsonic/testdata/test_get_album_list_alpha_name
+++ b/server/ctrlsubsonic/testdata/test_get_album_list_alpha_name
@@ -4,122 +4,123 @@
"version": "1.15.0",
"type": "gonic",
"serverVersion": "",
+ "openSubsonic": true,
"albumList": {
"album": [
{
"id": "al-3",
- "coverArt": "al-3",
- "artist": "artist-0",
"created": "2019-11-30T00:00:00Z",
+ "artist": "artist-0",
"title": "album-0",
- "album": "",
+ "album": "album-0",
"parent": "al-2",
"isDir": true,
- "name": "",
+ "coverArt": "al-3",
+ "name": "album-0",
"songCount": 3,
"duration": 300
},
{
"id": "al-7",
- "coverArt": "al-7",
- "artist": "artist-1",
"created": "2019-11-30T00:00:00Z",
+ "artist": "artist-1",
"title": "album-0",
- "album": "",
+ "album": "album-0",
"parent": "al-6",
"isDir": true,
- "name": "",
+ "coverArt": "al-7",
+ "name": "album-0",
"songCount": 3,
"duration": 300
},
{
"id": "al-11",
- "coverArt": "al-11",
- "artist": "artist-2",
"created": "2019-11-30T00:00:00Z",
+ "artist": "artist-2",
"title": "album-0",
- "album": "",
+ "album": "album-0",
"parent": "al-10",
"isDir": true,
- "name": "",
+ "coverArt": "al-11",
+ "name": "album-0",
"songCount": 3,
"duration": 300
},
{
"id": "al-4",
- "coverArt": "al-4",
- "artist": "artist-0",
"created": "2019-11-30T00:00:00Z",
+ "artist": "artist-0",
"title": "album-1",
- "album": "",
+ "album": "album-1",
"parent": "al-2",
"isDir": true,
- "name": "",
+ "coverArt": "al-4",
+ "name": "album-1",
"songCount": 3,
"duration": 300
},
{
"id": "al-8",
- "coverArt": "al-8",
- "artist": "artist-1",
"created": "2019-11-30T00:00:00Z",
+ "artist": "artist-1",
"title": "album-1",
- "album": "",
+ "album": "album-1",
"parent": "al-6",
"isDir": true,
- "name": "",
+ "coverArt": "al-8",
+ "name": "album-1",
"songCount": 3,
"duration": 300
},
{
"id": "al-12",
- "coverArt": "al-12",
- "artist": "artist-2",
"created": "2019-11-30T00:00:00Z",
+ "artist": "artist-2",
"title": "album-1",
- "album": "",
+ "album": "album-1",
"parent": "al-10",
"isDir": true,
- "name": "",
+ "coverArt": "al-12",
+ "name": "album-1",
"songCount": 3,
"duration": 300
},
{
"id": "al-5",
- "coverArt": "al-5",
- "artist": "artist-0",
"created": "2019-11-30T00:00:00Z",
+ "artist": "artist-0",
"title": "album-2",
- "album": "",
+ "album": "album-2",
"parent": "al-2",
"isDir": true,
- "name": "",
+ "coverArt": "al-5",
+ "name": "album-2",
"songCount": 3,
"duration": 300
},
{
"id": "al-9",
- "coverArt": "al-9",
- "artist": "artist-1",
"created": "2019-11-30T00:00:00Z",
+ "artist": "artist-1",
"title": "album-2",
- "album": "",
+ "album": "album-2",
"parent": "al-6",
"isDir": true,
- "name": "",
+ "coverArt": "al-9",
+ "name": "album-2",
"songCount": 3,
"duration": 300
},
{
"id": "al-13",
- "coverArt": "al-13",
- "artist": "artist-2",
"created": "2019-11-30T00:00:00Z",
+ "artist": "artist-2",
"title": "album-2",
- "album": "",
+ "album": "album-2",
"parent": "al-10",
"isDir": true,
- "name": "",
+ "coverArt": "al-13",
+ "name": "album-2",
"songCount": 3,
"duration": 300
}
diff --git a/server/ctrlsubsonic/testdata/test_get_album_list_newest b/server/ctrlsubsonic/testdata/test_get_album_list_newest
index 568a446..ac0fcaa 100644
--- a/server/ctrlsubsonic/testdata/test_get_album_list_newest
+++ b/server/ctrlsubsonic/testdata/test_get_album_list_newest
@@ -4,122 +4,123 @@
"version": "1.15.0",
"type": "gonic",
"serverVersion": "",
+ "openSubsonic": true,
"albumList": {
"album": [
{
"id": "al-3",
- "coverArt": "al-3",
- "artist": "artist-0",
"created": "2019-11-30T00:00:00Z",
+ "artist": "artist-0",
"title": "album-0",
- "album": "",
+ "album": "album-0",
"parent": "al-2",
"isDir": true,
- "name": "",
+ "coverArt": "al-3",
+ "name": "album-0",
"songCount": 3,
"duration": 300
},
{
"id": "al-4",
- "coverArt": "al-4",
- "artist": "artist-0",
"created": "2019-11-30T00:00:00Z",
+ "artist": "artist-0",
"title": "album-1",
- "album": "",
+ "album": "album-1",
"parent": "al-2",
"isDir": true,
- "name": "",
+ "coverArt": "al-4",
+ "name": "album-1",
"songCount": 3,
"duration": 300
},
{
"id": "al-5",
- "coverArt": "al-5",
- "artist": "artist-0",
"created": "2019-11-30T00:00:00Z",
+ "artist": "artist-0",
"title": "album-2",
- "album": "",
+ "album": "album-2",
"parent": "al-2",
"isDir": true,
- "name": "",
+ "coverArt": "al-5",
+ "name": "album-2",
"songCount": 3,
"duration": 300
},
{
"id": "al-7",
- "coverArt": "al-7",
- "artist": "artist-1",
"created": "2019-11-30T00:00:00Z",
+ "artist": "artist-1",
"title": "album-0",
- "album": "",
+ "album": "album-0",
"parent": "al-6",
"isDir": true,
- "name": "",
+ "coverArt": "al-7",
+ "name": "album-0",
"songCount": 3,
"duration": 300
},
{
"id": "al-8",
- "coverArt": "al-8",
- "artist": "artist-1",
"created": "2019-11-30T00:00:00Z",
+ "artist": "artist-1",
"title": "album-1",
- "album": "",
+ "album": "album-1",
"parent": "al-6",
"isDir": true,
- "name": "",
+ "coverArt": "al-8",
+ "name": "album-1",
"songCount": 3,
"duration": 300
},
{
"id": "al-9",
- "coverArt": "al-9",
- "artist": "artist-1",
"created": "2019-11-30T00:00:00Z",
+ "artist": "artist-1",
"title": "album-2",
- "album": "",
+ "album": "album-2",
"parent": "al-6",
"isDir": true,
- "name": "",
+ "coverArt": "al-9",
+ "name": "album-2",
"songCount": 3,
"duration": 300
},
{
"id": "al-11",
- "coverArt": "al-11",
- "artist": "artist-2",
"created": "2019-11-30T00:00:00Z",
+ "artist": "artist-2",
"title": "album-0",
- "album": "",
+ "album": "album-0",
"parent": "al-10",
"isDir": true,
- "name": "",
+ "coverArt": "al-11",
+ "name": "album-0",
"songCount": 3,
"duration": 300
},
{
"id": "al-12",
- "coverArt": "al-12",
- "artist": "artist-2",
"created": "2019-11-30T00:00:00Z",
+ "artist": "artist-2",
"title": "album-1",
- "album": "",
+ "album": "album-1",
"parent": "al-10",
"isDir": true,
- "name": "",
+ "coverArt": "al-12",
+ "name": "album-1",
"songCount": 3,
"duration": 300
},
{
"id": "al-13",
- "coverArt": "al-13",
- "artist": "artist-2",
"created": "2019-11-30T00:00:00Z",
+ "artist": "artist-2",
"title": "album-2",
- "album": "",
+ "album": "album-2",
"parent": "al-10",
"isDir": true,
- "name": "",
+ "coverArt": "al-13",
+ "name": "album-2",
"songCount": 3,
"duration": 300
}
diff --git a/server/ctrlsubsonic/testdata/test_get_album_list_random b/server/ctrlsubsonic/testdata/test_get_album_list_random
index 150e389..4595ab2 100644
--- a/server/ctrlsubsonic/testdata/test_get_album_list_random
+++ b/server/ctrlsubsonic/testdata/test_get_album_list_random
@@ -4,122 +4,123 @@
"version": "1.15.0",
"type": "gonic",
"serverVersion": "",
+ "openSubsonic": true,
"albumList": {
"album": [
{
- "id": "al-3",
- "coverArt": "al-3",
- "artist": "artist-0",
+ "id": "al-4",
"created": "2019-11-30T00:00:00Z",
- "title": "album-0",
- "album": "",
+ "artist": "artist-0",
+ "title": "album-1",
+ "album": "album-1",
"parent": "al-2",
"isDir": true,
- "name": "",
- "songCount": 3,
- "duration": 300
- },
- {
- "id": "al-13",
- "coverArt": "al-13",
- "artist": "artist-2",
- "created": "2019-11-30T00:00:00Z",
- "title": "album-2",
- "album": "",
- "parent": "al-10",
- "isDir": true,
- "name": "",
- "songCount": 3,
- "duration": 300
- },
- {
- "id": "al-7",
- "coverArt": "al-7",
- "artist": "artist-1",
- "created": "2019-11-30T00:00:00Z",
- "title": "album-0",
- "album": "",
- "parent": "al-6",
- "isDir": true,
- "name": "",
- "songCount": 3,
- "duration": 300
- },
- {
- "id": "al-5",
- "coverArt": "al-5",
- "artist": "artist-0",
- "created": "2019-11-30T00:00:00Z",
- "title": "album-2",
- "album": "",
- "parent": "al-2",
- "isDir": true,
- "name": "",
- "songCount": 3,
- "duration": 300
- },
- {
- "id": "al-12",
- "coverArt": "al-12",
- "artist": "artist-2",
- "created": "2019-11-30T00:00:00Z",
- "title": "album-1",
- "album": "",
- "parent": "al-10",
- "isDir": true,
- "name": "",
- "songCount": 3,
- "duration": 300
- },
- {
- "id": "al-8",
- "coverArt": "al-8",
- "artist": "artist-1",
- "created": "2019-11-30T00:00:00Z",
- "title": "album-1",
- "album": "",
- "parent": "al-6",
- "isDir": true,
- "name": "",
- "songCount": 3,
- "duration": 300
- },
- {
- "id": "al-9",
- "coverArt": "al-9",
- "artist": "artist-1",
- "created": "2019-11-30T00:00:00Z",
- "title": "album-2",
- "album": "",
- "parent": "al-6",
- "isDir": true,
- "name": "",
+ "coverArt": "al-4",
+ "name": "album-1",
"songCount": 3,
"duration": 300
},
{
"id": "al-11",
- "coverArt": "al-11",
- "artist": "artist-2",
"created": "2019-11-30T00:00:00Z",
+ "artist": "artist-2",
"title": "album-0",
- "album": "",
+ "album": "album-0",
"parent": "al-10",
"isDir": true,
- "name": "",
+ "coverArt": "al-11",
+ "name": "album-0",
"songCount": 3,
"duration": 300
},
{
- "id": "al-4",
- "coverArt": "al-4",
- "artist": "artist-0",
+ "id": "al-7",
"created": "2019-11-30T00:00:00Z",
+ "artist": "artist-1",
+ "title": "album-0",
+ "album": "album-0",
+ "parent": "al-6",
+ "isDir": true,
+ "coverArt": "al-7",
+ "name": "album-0",
+ "songCount": 3,
+ "duration": 300
+ },
+ {
+ "id": "al-8",
+ "created": "2019-11-30T00:00:00Z",
+ "artist": "artist-1",
"title": "album-1",
- "album": "",
+ "album": "album-1",
+ "parent": "al-6",
+ "isDir": true,
+ "coverArt": "al-8",
+ "name": "album-1",
+ "songCount": 3,
+ "duration": 300
+ },
+ {
+ "id": "al-9",
+ "created": "2019-11-30T00:00:00Z",
+ "artist": "artist-1",
+ "title": "album-2",
+ "album": "album-2",
+ "parent": "al-6",
+ "isDir": true,
+ "coverArt": "al-9",
+ "name": "album-2",
+ "songCount": 3,
+ "duration": 300
+ },
+ {
+ "id": "al-13",
+ "created": "2019-11-30T00:00:00Z",
+ "artist": "artist-2",
+ "title": "album-2",
+ "album": "album-2",
+ "parent": "al-10",
+ "isDir": true,
+ "coverArt": "al-13",
+ "name": "album-2",
+ "songCount": 3,
+ "duration": 300
+ },
+ {
+ "id": "al-3",
+ "created": "2019-11-30T00:00:00Z",
+ "artist": "artist-0",
+ "title": "album-0",
+ "album": "album-0",
"parent": "al-2",
"isDir": true,
- "name": "",
+ "coverArt": "al-3",
+ "name": "album-0",
+ "songCount": 3,
+ "duration": 300
+ },
+ {
+ "id": "al-5",
+ "created": "2019-11-30T00:00:00Z",
+ "artist": "artist-0",
+ "title": "album-2",
+ "album": "album-2",
+ "parent": "al-2",
+ "isDir": true,
+ "coverArt": "al-5",
+ "name": "album-2",
+ "songCount": 3,
+ "duration": 300
+ },
+ {
+ "id": "al-12",
+ "created": "2019-11-30T00:00:00Z",
+ "artist": "artist-2",
+ "title": "album-1",
+ "album": "album-1",
+ "parent": "al-10",
+ "isDir": true,
+ "coverArt": "al-12",
+ "name": "album-1",
"songCount": 3,
"duration": 300
}
diff --git a/server/ctrlsubsonic/testdata/test_get_album_list_two_alpha_artist b/server/ctrlsubsonic/testdata/test_get_album_list_two_alpha_artist
index f5573f7..35104eb 100644
--- a/server/ctrlsubsonic/testdata/test_get_album_list_two_alpha_artist
+++ b/server/ctrlsubsonic/testdata/test_get_album_list_two_alpha_artist
@@ -4,17 +4,19 @@
"version": "1.15.0",
"type": "gonic",
"serverVersion": "",
+ "openSubsonic": true,
"albumList2": {
"album": [
{
"id": "al-3",
- "coverArt": "al-3",
+ "created": "2019-11-30T00:00:00Z",
"artistId": "ar-1",
"artist": "artist-0",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
+ "displayArtist": "artist-0",
+ "title": "album-0",
+ "album": "album-0",
+ "coverArt": "al-3",
"name": "album-0",
"songCount": 3,
"duration": 300,
@@ -22,13 +24,14 @@
},
{
"id": "al-4",
- "coverArt": "al-4",
+ "created": "2019-11-30T00:00:00Z",
"artistId": "ar-1",
"artist": "artist-0",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
+ "displayArtist": "artist-0",
+ "title": "album-1",
+ "album": "album-1",
+ "coverArt": "al-4",
"name": "album-1",
"songCount": 3,
"duration": 300,
@@ -36,13 +39,14 @@
},
{
"id": "al-5",
- "coverArt": "al-5",
+ "created": "2019-11-30T00:00:00Z",
"artistId": "ar-1",
"artist": "artist-0",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
+ "displayArtist": "artist-0",
+ "title": "album-2",
+ "album": "album-2",
+ "coverArt": "al-5",
"name": "album-2",
"songCount": 3,
"duration": 300,
@@ -50,13 +54,14 @@
},
{
"id": "al-7",
- "coverArt": "al-7",
+ "created": "2019-11-30T00:00:00Z",
"artistId": "ar-2",
"artist": "artist-1",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
+ "displayArtist": "artist-1",
+ "title": "album-0",
+ "album": "album-0",
+ "coverArt": "al-7",
"name": "album-0",
"songCount": 3,
"duration": 300,
@@ -64,13 +69,14 @@
},
{
"id": "al-8",
- "coverArt": "al-8",
+ "created": "2019-11-30T00:00:00Z",
"artistId": "ar-2",
"artist": "artist-1",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
+ "displayArtist": "artist-1",
+ "title": "album-1",
+ "album": "album-1",
+ "coverArt": "al-8",
"name": "album-1",
"songCount": 3,
"duration": 300,
@@ -78,13 +84,14 @@
},
{
"id": "al-9",
- "coverArt": "al-9",
+ "created": "2019-11-30T00:00:00Z",
"artistId": "ar-2",
"artist": "artist-1",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
+ "displayArtist": "artist-1",
+ "title": "album-2",
+ "album": "album-2",
+ "coverArt": "al-9",
"name": "album-2",
"songCount": 3,
"duration": 300,
@@ -92,13 +99,14 @@
},
{
"id": "al-11",
- "coverArt": "al-11",
+ "created": "2019-11-30T00:00:00Z",
"artistId": "ar-3",
"artist": "artist-2",
"artists": [{ "id": "ar-3", "name": "artist-2" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
+ "displayArtist": "artist-2",
+ "title": "album-0",
+ "album": "album-0",
+ "coverArt": "al-11",
"name": "album-0",
"songCount": 3,
"duration": 300,
@@ -106,13 +114,14 @@
},
{
"id": "al-12",
- "coverArt": "al-12",
+ "created": "2019-11-30T00:00:00Z",
"artistId": "ar-3",
"artist": "artist-2",
"artists": [{ "id": "ar-3", "name": "artist-2" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
+ "displayArtist": "artist-2",
+ "title": "album-1",
+ "album": "album-1",
+ "coverArt": "al-12",
"name": "album-1",
"songCount": 3,
"duration": 300,
@@ -120,13 +129,14 @@
},
{
"id": "al-13",
- "coverArt": "al-13",
+ "created": "2019-11-30T00:00:00Z",
"artistId": "ar-3",
"artist": "artist-2",
"artists": [{ "id": "ar-3", "name": "artist-2" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
+ "displayArtist": "artist-2",
+ "title": "album-2",
+ "album": "album-2",
+ "coverArt": "al-13",
"name": "album-2",
"songCount": 3,
"duration": 300,
diff --git a/server/ctrlsubsonic/testdata/test_get_album_list_two_alpha_name b/server/ctrlsubsonic/testdata/test_get_album_list_two_alpha_name
index 44357c2..6a4aec2 100644
--- a/server/ctrlsubsonic/testdata/test_get_album_list_two_alpha_name
+++ b/server/ctrlsubsonic/testdata/test_get_album_list_two_alpha_name
@@ -4,17 +4,19 @@
"version": "1.15.0",
"type": "gonic",
"serverVersion": "",
+ "openSubsonic": true,
"albumList2": {
"album": [
{
"id": "al-3",
- "coverArt": "al-3",
+ "created": "2019-11-30T00:00:00Z",
"artistId": "ar-1",
"artist": "artist-0",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
+ "displayArtist": "artist-0",
+ "title": "album-0",
+ "album": "album-0",
+ "coverArt": "al-3",
"name": "album-0",
"songCount": 3,
"duration": 300,
@@ -22,13 +24,14 @@
},
{
"id": "al-7",
- "coverArt": "al-7",
+ "created": "2019-11-30T00:00:00Z",
"artistId": "ar-2",
"artist": "artist-1",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
+ "displayArtist": "artist-1",
+ "title": "album-0",
+ "album": "album-0",
+ "coverArt": "al-7",
"name": "album-0",
"songCount": 3,
"duration": 300,
@@ -36,13 +39,14 @@
},
{
"id": "al-11",
- "coverArt": "al-11",
+ "created": "2019-11-30T00:00:00Z",
"artistId": "ar-3",
"artist": "artist-2",
"artists": [{ "id": "ar-3", "name": "artist-2" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
+ "displayArtist": "artist-2",
+ "title": "album-0",
+ "album": "album-0",
+ "coverArt": "al-11",
"name": "album-0",
"songCount": 3,
"duration": 300,
@@ -50,13 +54,14 @@
},
{
"id": "al-4",
- "coverArt": "al-4",
+ "created": "2019-11-30T00:00:00Z",
"artistId": "ar-1",
"artist": "artist-0",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
+ "displayArtist": "artist-0",
+ "title": "album-1",
+ "album": "album-1",
+ "coverArt": "al-4",
"name": "album-1",
"songCount": 3,
"duration": 300,
@@ -64,13 +69,14 @@
},
{
"id": "al-8",
- "coverArt": "al-8",
+ "created": "2019-11-30T00:00:00Z",
"artistId": "ar-2",
"artist": "artist-1",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
+ "displayArtist": "artist-1",
+ "title": "album-1",
+ "album": "album-1",
+ "coverArt": "al-8",
"name": "album-1",
"songCount": 3,
"duration": 300,
@@ -78,13 +84,14 @@
},
{
"id": "al-12",
- "coverArt": "al-12",
+ "created": "2019-11-30T00:00:00Z",
"artistId": "ar-3",
"artist": "artist-2",
"artists": [{ "id": "ar-3", "name": "artist-2" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
+ "displayArtist": "artist-2",
+ "title": "album-1",
+ "album": "album-1",
+ "coverArt": "al-12",
"name": "album-1",
"songCount": 3,
"duration": 300,
@@ -92,13 +99,14 @@
},
{
"id": "al-5",
- "coverArt": "al-5",
+ "created": "2019-11-30T00:00:00Z",
"artistId": "ar-1",
"artist": "artist-0",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
+ "displayArtist": "artist-0",
+ "title": "album-2",
+ "album": "album-2",
+ "coverArt": "al-5",
"name": "album-2",
"songCount": 3,
"duration": 300,
@@ -106,13 +114,14 @@
},
{
"id": "al-9",
- "coverArt": "al-9",
+ "created": "2019-11-30T00:00:00Z",
"artistId": "ar-2",
"artist": "artist-1",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
+ "displayArtist": "artist-1",
+ "title": "album-2",
+ "album": "album-2",
+ "coverArt": "al-9",
"name": "album-2",
"songCount": 3,
"duration": 300,
@@ -120,13 +129,14 @@
},
{
"id": "al-13",
- "coverArt": "al-13",
+ "created": "2019-11-30T00:00:00Z",
"artistId": "ar-3",
"artist": "artist-2",
"artists": [{ "id": "ar-3", "name": "artist-2" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
+ "displayArtist": "artist-2",
+ "title": "album-2",
+ "album": "album-2",
+ "coverArt": "al-13",
"name": "album-2",
"songCount": 3,
"duration": 300,
diff --git a/server/ctrlsubsonic/testdata/test_get_album_list_two_newest b/server/ctrlsubsonic/testdata/test_get_album_list_two_newest
index f5573f7..35104eb 100644
--- a/server/ctrlsubsonic/testdata/test_get_album_list_two_newest
+++ b/server/ctrlsubsonic/testdata/test_get_album_list_two_newest
@@ -4,17 +4,19 @@
"version": "1.15.0",
"type": "gonic",
"serverVersion": "",
+ "openSubsonic": true,
"albumList2": {
"album": [
{
"id": "al-3",
- "coverArt": "al-3",
+ "created": "2019-11-30T00:00:00Z",
"artistId": "ar-1",
"artist": "artist-0",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
+ "displayArtist": "artist-0",
+ "title": "album-0",
+ "album": "album-0",
+ "coverArt": "al-3",
"name": "album-0",
"songCount": 3,
"duration": 300,
@@ -22,13 +24,14 @@
},
{
"id": "al-4",
- "coverArt": "al-4",
+ "created": "2019-11-30T00:00:00Z",
"artistId": "ar-1",
"artist": "artist-0",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
+ "displayArtist": "artist-0",
+ "title": "album-1",
+ "album": "album-1",
+ "coverArt": "al-4",
"name": "album-1",
"songCount": 3,
"duration": 300,
@@ -36,13 +39,14 @@
},
{
"id": "al-5",
- "coverArt": "al-5",
+ "created": "2019-11-30T00:00:00Z",
"artistId": "ar-1",
"artist": "artist-0",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
+ "displayArtist": "artist-0",
+ "title": "album-2",
+ "album": "album-2",
+ "coverArt": "al-5",
"name": "album-2",
"songCount": 3,
"duration": 300,
@@ -50,13 +54,14 @@
},
{
"id": "al-7",
- "coverArt": "al-7",
+ "created": "2019-11-30T00:00:00Z",
"artistId": "ar-2",
"artist": "artist-1",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
+ "displayArtist": "artist-1",
+ "title": "album-0",
+ "album": "album-0",
+ "coverArt": "al-7",
"name": "album-0",
"songCount": 3,
"duration": 300,
@@ -64,13 +69,14 @@
},
{
"id": "al-8",
- "coverArt": "al-8",
+ "created": "2019-11-30T00:00:00Z",
"artistId": "ar-2",
"artist": "artist-1",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
+ "displayArtist": "artist-1",
+ "title": "album-1",
+ "album": "album-1",
+ "coverArt": "al-8",
"name": "album-1",
"songCount": 3,
"duration": 300,
@@ -78,13 +84,14 @@
},
{
"id": "al-9",
- "coverArt": "al-9",
+ "created": "2019-11-30T00:00:00Z",
"artistId": "ar-2",
"artist": "artist-1",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
+ "displayArtist": "artist-1",
+ "title": "album-2",
+ "album": "album-2",
+ "coverArt": "al-9",
"name": "album-2",
"songCount": 3,
"duration": 300,
@@ -92,13 +99,14 @@
},
{
"id": "al-11",
- "coverArt": "al-11",
+ "created": "2019-11-30T00:00:00Z",
"artistId": "ar-3",
"artist": "artist-2",
"artists": [{ "id": "ar-3", "name": "artist-2" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
+ "displayArtist": "artist-2",
+ "title": "album-0",
+ "album": "album-0",
+ "coverArt": "al-11",
"name": "album-0",
"songCount": 3,
"duration": 300,
@@ -106,13 +114,14 @@
},
{
"id": "al-12",
- "coverArt": "al-12",
+ "created": "2019-11-30T00:00:00Z",
"artistId": "ar-3",
"artist": "artist-2",
"artists": [{ "id": "ar-3", "name": "artist-2" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
+ "displayArtist": "artist-2",
+ "title": "album-1",
+ "album": "album-1",
+ "coverArt": "al-12",
"name": "album-1",
"songCount": 3,
"duration": 300,
@@ -120,13 +129,14 @@
},
{
"id": "al-13",
- "coverArt": "al-13",
+ "created": "2019-11-30T00:00:00Z",
"artistId": "ar-3",
"artist": "artist-2",
"artists": [{ "id": "ar-3", "name": "artist-2" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
+ "displayArtist": "artist-2",
+ "title": "album-2",
+ "album": "album-2",
+ "coverArt": "al-13",
"name": "album-2",
"songCount": 3,
"duration": 300,
diff --git a/server/ctrlsubsonic/testdata/test_get_album_list_two_random b/server/ctrlsubsonic/testdata/test_get_album_list_two_random
index 49eea7e..360ed6d 100644
--- a/server/ctrlsubsonic/testdata/test_get_album_list_two_random
+++ b/server/ctrlsubsonic/testdata/test_get_album_list_two_random
@@ -4,101 +4,19 @@
"version": "1.15.0",
"type": "gonic",
"serverVersion": "",
+ "openSubsonic": true,
"albumList2": {
"album": [
- {
- "id": "al-8",
- "coverArt": "al-8",
- "artistId": "ar-2",
- "artist": "artist-1",
- "artists": [{ "id": "ar-2", "name": "artist-1" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
- "name": "album-1",
- "songCount": 3,
- "duration": 300,
- "year": 2021
- },
- {
- "id": "al-11",
- "coverArt": "al-11",
- "artistId": "ar-3",
- "artist": "artist-2",
- "artists": [{ "id": "ar-3", "name": "artist-2" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
- "name": "album-0",
- "songCount": 3,
- "duration": 300,
- "year": 2021
- },
{
"id": "al-5",
+ "created": "2019-11-30T00:00:00Z",
+ "artistId": "ar-1",
+ "artist": "artist-0",
+ "artists": [{ "id": "ar-1", "name": "artist-0" }],
+ "displayArtist": "artist-0",
+ "title": "album-2",
+ "album": "album-2",
"coverArt": "al-5",
- "artistId": "ar-1",
- "artist": "artist-0",
- "artists": [{ "id": "ar-1", "name": "artist-0" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
- "name": "album-2",
- "songCount": 3,
- "duration": 300,
- "year": 2021
- },
- {
- "id": "al-3",
- "coverArt": "al-3",
- "artistId": "ar-1",
- "artist": "artist-0",
- "artists": [{ "id": "ar-1", "name": "artist-0" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
- "name": "album-0",
- "songCount": 3,
- "duration": 300,
- "year": 2021
- },
- {
- "id": "al-9",
- "coverArt": "al-9",
- "artistId": "ar-2",
- "artist": "artist-1",
- "artists": [{ "id": "ar-2", "name": "artist-1" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
- "name": "album-2",
- "songCount": 3,
- "duration": 300,
- "year": 2021
- },
- {
- "id": "al-7",
- "coverArt": "al-7",
- "artistId": "ar-2",
- "artist": "artist-1",
- "artists": [{ "id": "ar-2", "name": "artist-1" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
- "name": "album-0",
- "songCount": 3,
- "duration": 300,
- "year": 2021
- },
- {
- "id": "al-13",
- "coverArt": "al-13",
- "artistId": "ar-3",
- "artist": "artist-2",
- "artists": [{ "id": "ar-3", "name": "artist-2" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
"name": "album-2",
"songCount": 3,
"duration": 300,
@@ -106,31 +24,123 @@
},
{
"id": "al-4",
- "coverArt": "al-4",
+ "created": "2019-11-30T00:00:00Z",
"artistId": "ar-1",
"artist": "artist-0",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
+ "displayArtist": "artist-0",
+ "title": "album-1",
+ "album": "album-1",
+ "coverArt": "al-4",
"name": "album-1",
"songCount": 3,
"duration": 300,
"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,
+ "year": 2021
+ },
{
"id": "al-12",
- "coverArt": "al-12",
+ "created": "2019-11-30T00:00:00Z",
"artistId": "ar-3",
"artist": "artist-2",
"artists": [{ "id": "ar-3", "name": "artist-2" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
+ "displayArtist": "artist-2",
+ "title": "album-1",
+ "album": "album-1",
+ "coverArt": "al-12",
"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
+ },
+ {
+ "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-11",
+ "created": "2019-11-30T00:00:00Z",
+ "artistId": "ar-3",
+ "artist": "artist-2",
+ "artists": [{ "id": "ar-3", "name": "artist-2" }],
+ "displayArtist": "artist-2",
+ "title": "album-0",
+ "album": "album-0",
+ "coverArt": "al-11",
+ "name": "album-0",
+ "songCount": 3,
+ "duration": 300,
+ "year": 2021
+ },
+ {
+ "id": "al-3",
+ "created": "2019-11-30T00:00:00Z",
+ "artistId": "ar-1",
+ "artist": "artist-0",
+ "artists": [{ "id": "ar-1", "name": "artist-0" }],
+ "displayArtist": "artist-0",
+ "title": "album-0",
+ "album": "album-0",
+ "coverArt": "al-3",
+ "name": "album-0",
+ "songCount": 3,
+ "duration": 300,
+ "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,
+ "year": 2021
}
]
}
diff --git a/server/ctrlsubsonic/testdata/test_get_album_with_cover b/server/ctrlsubsonic/testdata/test_get_album_with_cover
index f065f17..2e65ac7 100644
--- a/server/ctrlsubsonic/testdata/test_get_album_with_cover
+++ b/server/ctrlsubsonic/testdata/test_get_album_with_cover
@@ -4,20 +4,22 @@
"version": "1.15.0",
"type": "gonic",
"serverVersion": "",
+ "openSubsonic": true,
"album": {
"id": "al-3",
- "coverArt": "al-3",
+ "created": "2019-11-30T00:00:00Z",
"artistId": "ar-1",
"artist": "artist-0",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
+ "displayArtist": "artist-0",
+ "title": "album-0",
+ "album": "album-0",
+ "coverArt": "al-3",
"name": "album-0",
"songCount": 3,
"duration": 300,
"genre": "Unknown Genre",
- "genres": ["Unknown Genre"],
+ "genres": [{ "name": "Unknown Genre" }],
"year": 2021,
"song": [
{
@@ -26,8 +28,12 @@
"albumId": "al-3",
"artist": "artist-0",
"artistId": "ar-1",
+ "artists": [{ "id": "ar-1", "name": "artist-0" }],
+ "displayArtist": "artist-0",
+ "albumArtists": [{ "id": "ar-1", "name": "artist-0" }],
+ "displayAlbumArtist": "artist-0",
"bitRate": 100,
- "contentType": "audio/x-flac",
+ "contentType": "audio/flac",
"coverArt": "al-3",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
@@ -48,8 +54,12 @@
"albumId": "al-3",
"artist": "artist-0",
"artistId": "ar-1",
+ "artists": [{ "id": "ar-1", "name": "artist-0" }],
+ "displayArtist": "artist-0",
+ "albumArtists": [{ "id": "ar-1", "name": "artist-0" }],
+ "displayAlbumArtist": "artist-0",
"bitRate": 100,
- "contentType": "audio/x-flac",
+ "contentType": "audio/flac",
"coverArt": "al-3",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
@@ -70,8 +80,12 @@
"albumId": "al-3",
"artist": "artist-0",
"artistId": "ar-1",
+ "artists": [{ "id": "ar-1", "name": "artist-0" }],
+ "displayArtist": "artist-0",
+ "albumArtists": [{ "id": "ar-1", "name": "artist-0" }],
+ "displayAlbumArtist": "artist-0",
"bitRate": 100,
- "contentType": "audio/x-flac",
+ "contentType": "audio/flac",
"coverArt": "al-3",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
diff --git a/server/ctrlsubsonic/testdata/test_get_album_without_cover b/server/ctrlsubsonic/testdata/test_get_album_without_cover
index 8fc1464..6f85d4b 100644
--- a/server/ctrlsubsonic/testdata/test_get_album_without_cover
+++ b/server/ctrlsubsonic/testdata/test_get_album_without_cover
@@ -4,6 +4,7 @@
"version": "1.15.0",
"type": "gonic",
"serverVersion": "",
+ "openSubsonic": true,
"album": {
"id": "al-2",
"created": "2019-11-30T00:00:00Z",
diff --git a/server/ctrlsubsonic/testdata/test_get_artist_id_one b/server/ctrlsubsonic/testdata/test_get_artist_id_one
index 0bc3012..5c1fe45 100644
--- a/server/ctrlsubsonic/testdata/test_get_artist_id_one
+++ b/server/ctrlsubsonic/testdata/test_get_artist_id_one
@@ -4,6 +4,7 @@
"version": "1.15.0",
"type": "gonic",
"serverVersion": "",
+ "openSubsonic": true,
"artist": {
"id": "ar-1",
"name": "artist-0",
@@ -11,50 +12,53 @@
"album": [
{
"id": "al-3",
- "coverArt": "al-3",
+ "created": "2019-11-30T00:00:00Z",
"artistId": "ar-1",
"artist": "artist-0",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
+ "displayArtist": "artist-0",
+ "title": "album-0",
+ "album": "album-0",
+ "coverArt": "al-3",
"name": "album-0",
"songCount": 3,
"duration": 300,
"genre": "Unknown Genre",
- "genres": ["Unknown Genre"],
+ "genres": [{ "name": "Unknown Genre" }],
"year": 2021
},
{
"id": "al-4",
- "coverArt": "al-4",
+ "created": "2019-11-30T00:00:00Z",
"artistId": "ar-1",
"artist": "artist-0",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
+ "displayArtist": "artist-0",
+ "title": "album-1",
+ "album": "album-1",
+ "coverArt": "al-4",
"name": "album-1",
"songCount": 3,
"duration": 300,
"genre": "Unknown Genre",
- "genres": ["Unknown Genre"],
+ "genres": [{ "name": "Unknown Genre" }],
"year": 2021
},
{
"id": "al-5",
- "coverArt": "al-5",
+ "created": "2019-11-30T00:00:00Z",
"artistId": "ar-1",
"artist": "artist-0",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
+ "displayArtist": "artist-0",
+ "title": "album-2",
+ "album": "album-2",
+ "coverArt": "al-5",
"name": "album-2",
"songCount": 3,
"duration": 300,
"genre": "Unknown Genre",
- "genres": ["Unknown Genre"],
+ "genres": [{ "name": "Unknown Genre" }],
"year": 2021
}
]
diff --git a/server/ctrlsubsonic/testdata/test_get_artist_id_three b/server/ctrlsubsonic/testdata/test_get_artist_id_three
index 7667dde..c5542f3 100644
--- a/server/ctrlsubsonic/testdata/test_get_artist_id_three
+++ b/server/ctrlsubsonic/testdata/test_get_artist_id_three
@@ -4,6 +4,7 @@
"version": "1.15.0",
"type": "gonic",
"serverVersion": "",
+ "openSubsonic": true,
"artist": {
"id": "ar-3",
"name": "artist-2",
@@ -11,50 +12,53 @@
"album": [
{
"id": "al-11",
- "coverArt": "al-11",
+ "created": "2019-11-30T00:00:00Z",
"artistId": "ar-3",
"artist": "artist-2",
"artists": [{ "id": "ar-3", "name": "artist-2" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
+ "displayArtist": "artist-2",
+ "title": "album-0",
+ "album": "album-0",
+ "coverArt": "al-11",
"name": "album-0",
"songCount": 3,
"duration": 300,
"genre": "Unknown Genre",
- "genres": ["Unknown Genre"],
+ "genres": [{ "name": "Unknown Genre" }],
"year": 2021
},
{
"id": "al-12",
- "coverArt": "al-12",
+ "created": "2019-11-30T00:00:00Z",
"artistId": "ar-3",
"artist": "artist-2",
"artists": [{ "id": "ar-3", "name": "artist-2" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
+ "displayArtist": "artist-2",
+ "title": "album-1",
+ "album": "album-1",
+ "coverArt": "al-12",
"name": "album-1",
"songCount": 3,
"duration": 300,
"genre": "Unknown Genre",
- "genres": ["Unknown Genre"],
+ "genres": [{ "name": "Unknown Genre" }],
"year": 2021
},
{
"id": "al-13",
- "coverArt": "al-13",
+ "created": "2019-11-30T00:00:00Z",
"artistId": "ar-3",
"artist": "artist-2",
"artists": [{ "id": "ar-3", "name": "artist-2" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
+ "displayArtist": "artist-2",
+ "title": "album-2",
+ "album": "album-2",
+ "coverArt": "al-13",
"name": "album-2",
"songCount": 3,
"duration": 300,
"genre": "Unknown Genre",
- "genres": ["Unknown Genre"],
+ "genres": [{ "name": "Unknown Genre" }],
"year": 2021
}
]
diff --git a/server/ctrlsubsonic/testdata/test_get_artist_id_two b/server/ctrlsubsonic/testdata/test_get_artist_id_two
index 1722eb4..e8fb633 100644
--- a/server/ctrlsubsonic/testdata/test_get_artist_id_two
+++ b/server/ctrlsubsonic/testdata/test_get_artist_id_two
@@ -4,6 +4,7 @@
"version": "1.15.0",
"type": "gonic",
"serverVersion": "",
+ "openSubsonic": true,
"artist": {
"id": "ar-2",
"name": "artist-1",
@@ -11,50 +12,53 @@
"album": [
{
"id": "al-7",
- "coverArt": "al-7",
+ "created": "2019-11-30T00:00:00Z",
"artistId": "ar-2",
"artist": "artist-1",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
+ "displayArtist": "artist-1",
+ "title": "album-0",
+ "album": "album-0",
+ "coverArt": "al-7",
"name": "album-0",
"songCount": 3,
"duration": 300,
"genre": "Unknown Genre",
- "genres": ["Unknown Genre"],
+ "genres": [{ "name": "Unknown Genre" }],
"year": 2021
},
{
"id": "al-8",
- "coverArt": "al-8",
+ "created": "2019-11-30T00:00:00Z",
"artistId": "ar-2",
"artist": "artist-1",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
+ "displayArtist": "artist-1",
+ "title": "album-1",
+ "album": "album-1",
+ "coverArt": "al-8",
"name": "album-1",
"songCount": 3,
"duration": 300,
"genre": "Unknown Genre",
- "genres": ["Unknown Genre"],
+ "genres": [{ "name": "Unknown Genre" }],
"year": 2021
},
{
"id": "al-9",
- "coverArt": "al-9",
+ "created": "2019-11-30T00:00:00Z",
"artistId": "ar-2",
"artist": "artist-1",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
+ "displayArtist": "artist-1",
+ "title": "album-2",
+ "album": "album-2",
+ "coverArt": "al-9",
"name": "album-2",
"songCount": 3,
"duration": 300,
"genre": "Unknown Genre",
- "genres": ["Unknown Genre"],
+ "genres": [{ "name": "Unknown Genre" }],
"year": 2021
}
]
diff --git a/server/ctrlsubsonic/testdata/test_get_artists_no_args b/server/ctrlsubsonic/testdata/test_get_artists_no_args
index 88cfdfa..cf2dc18 100644
--- a/server/ctrlsubsonic/testdata/test_get_artists_no_args
+++ b/server/ctrlsubsonic/testdata/test_get_artists_no_args
@@ -4,6 +4,7 @@
"version": "1.15.0",
"type": "gonic",
"serverVersion": "",
+ "openSubsonic": true,
"artists": {
"ignoredArticles": "",
"index": [
diff --git a/server/ctrlsubsonic/testdata/test_get_artists_with_music_folder_1 b/server/ctrlsubsonic/testdata/test_get_artists_with_music_folder_1
index 0ee73fa..2d55d38 100644
--- a/server/ctrlsubsonic/testdata/test_get_artists_with_music_folder_1
+++ b/server/ctrlsubsonic/testdata/test_get_artists_with_music_folder_1
@@ -4,6 +4,7 @@
"version": "1.15.0",
"type": "gonic",
"serverVersion": "",
+ "openSubsonic": true,
"artists": {
"ignoredArticles": "",
"index": [
diff --git a/server/ctrlsubsonic/testdata/test_get_artists_with_music_folder_2 b/server/ctrlsubsonic/testdata/test_get_artists_with_music_folder_2
index 0ee73fa..2d55d38 100644
--- a/server/ctrlsubsonic/testdata/test_get_artists_with_music_folder_2
+++ b/server/ctrlsubsonic/testdata/test_get_artists_with_music_folder_2
@@ -4,6 +4,7 @@
"version": "1.15.0",
"type": "gonic",
"serverVersion": "",
+ "openSubsonic": true,
"artists": {
"ignoredArticles": "",
"index": [
diff --git a/server/ctrlsubsonic/testdata/test_get_indexes_no_args b/server/ctrlsubsonic/testdata/test_get_indexes_no_args
index e6bf358..4e36f0c 100644
--- a/server/ctrlsubsonic/testdata/test_get_indexes_no_args
+++ b/server/ctrlsubsonic/testdata/test_get_indexes_no_args
@@ -4,6 +4,7 @@
"version": "1.15.0",
"type": "gonic",
"serverVersion": "",
+ "openSubsonic": true,
"indexes": {
"lastModified": 0,
"ignoredArticles": "",
diff --git a/server/ctrlsubsonic/testdata/test_get_indexes_with_music_folder_1 b/server/ctrlsubsonic/testdata/test_get_indexes_with_music_folder_1
index 8b66d90..b8aaca7 100644
--- a/server/ctrlsubsonic/testdata/test_get_indexes_with_music_folder_1
+++ b/server/ctrlsubsonic/testdata/test_get_indexes_with_music_folder_1
@@ -4,6 +4,7 @@
"version": "1.15.0",
"type": "gonic",
"serverVersion": "",
+ "openSubsonic": true,
"indexes": {
"lastModified": 0,
"ignoredArticles": "",
diff --git a/server/ctrlsubsonic/testdata/test_get_indexes_with_music_folder_2 b/server/ctrlsubsonic/testdata/test_get_indexes_with_music_folder_2
index 2eea427..079c529 100644
--- a/server/ctrlsubsonic/testdata/test_get_indexes_with_music_folder_2
+++ b/server/ctrlsubsonic/testdata/test_get_indexes_with_music_folder_2
@@ -4,6 +4,7 @@
"version": "1.15.0",
"type": "gonic",
"serverVersion": "",
+ "openSubsonic": true,
"indexes": {
"lastModified": 0,
"ignoredArticles": "",
diff --git a/server/ctrlsubsonic/testdata/test_get_music_directory_with_tracks b/server/ctrlsubsonic/testdata/test_get_music_directory_with_tracks
index b443127..ddd2720 100644
--- a/server/ctrlsubsonic/testdata/test_get_music_directory_with_tracks
+++ b/server/ctrlsubsonic/testdata/test_get_music_directory_with_tracks
@@ -4,6 +4,7 @@
"version": "1.15.0",
"type": "gonic",
"serverVersion": "",
+ "openSubsonic": true,
"directory": {
"id": "al-3",
"parent": "al-2",
@@ -13,8 +14,9 @@
"id": "tr-1",
"album": "album-0",
"artist": "artist-0",
+ "artists": [{ "id": "ar-1", "name": "artist-0" }],
"bitRate": 100,
- "contentType": "audio/x-flac",
+ "contentType": "audio/flac",
"coverArt": "al-3",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
@@ -33,8 +35,9 @@
"id": "tr-2",
"album": "album-0",
"artist": "artist-0",
+ "artists": [{ "id": "ar-1", "name": "artist-0" }],
"bitRate": 100,
- "contentType": "audio/x-flac",
+ "contentType": "audio/flac",
"coverArt": "al-3",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
@@ -53,8 +56,9 @@
"id": "tr-3",
"album": "album-0",
"artist": "artist-0",
+ "artists": [{ "id": "ar-1", "name": "artist-0" }],
"bitRate": 100,
- "contentType": "audio/x-flac",
+ "contentType": "audio/flac",
"coverArt": "al-3",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
diff --git a/server/ctrlsubsonic/testdata/test_get_music_directory_without_tracks b/server/ctrlsubsonic/testdata/test_get_music_directory_without_tracks
index 1e38de8..050e23b 100644
--- a/server/ctrlsubsonic/testdata/test_get_music_directory_without_tracks
+++ b/server/ctrlsubsonic/testdata/test_get_music_directory_without_tracks
@@ -4,6 +4,7 @@
"version": "1.15.0",
"type": "gonic",
"serverVersion": "",
+ "openSubsonic": true,
"directory": {
"id": "al-2",
"parent": "al-1",
diff --git a/server/ctrlsubsonic/testdata/test_search_three_q_alb b/server/ctrlsubsonic/testdata/test_search_three_q_alb
index 1db3507..7ffb5dd 100644
--- a/server/ctrlsubsonic/testdata/test_search_three_q_alb
+++ b/server/ctrlsubsonic/testdata/test_search_three_q_alb
@@ -4,150 +4,160 @@
"version": "1.15.0",
"type": "gonic",
"serverVersion": "",
+ "openSubsonic": true,
"searchResult3": {
"album": [
{
"id": "al-3",
- "coverArt": "al-3",
+ "created": "2019-11-30T00:00:00Z",
"artistId": "ar-1",
"artist": "artist-0",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
+ "displayArtist": "artist-0",
+ "title": "album-0",
+ "album": "album-0",
+ "coverArt": "al-3",
"name": "album-0",
"songCount": 0,
"duration": 0,
"genre": "Unknown Genre",
- "genres": ["Unknown Genre"],
+ "genres": [{ "name": "Unknown Genre" }],
"year": 2021
},
{
"id": "al-4",
- "coverArt": "al-4",
+ "created": "2019-11-30T00:00:00Z",
"artistId": "ar-1",
"artist": "artist-0",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
+ "displayArtist": "artist-0",
+ "title": "album-1",
+ "album": "album-1",
+ "coverArt": "al-4",
"name": "album-1",
"songCount": 0,
"duration": 0,
"genre": "Unknown Genre",
- "genres": ["Unknown Genre"],
+ "genres": [{ "name": "Unknown Genre" }],
"year": 2021
},
{
"id": "al-5",
- "coverArt": "al-5",
+ "created": "2019-11-30T00:00:00Z",
"artistId": "ar-1",
"artist": "artist-0",
"artists": [{ "id": "ar-1", "name": "artist-0" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
+ "displayArtist": "artist-0",
+ "title": "album-2",
+ "album": "album-2",
+ "coverArt": "al-5",
"name": "album-2",
"songCount": 0,
"duration": 0,
"genre": "Unknown Genre",
- "genres": ["Unknown Genre"],
+ "genres": [{ "name": "Unknown Genre" }],
"year": 2021
},
{
"id": "al-7",
- "coverArt": "al-7",
+ "created": "2019-11-30T00:00:00Z",
"artistId": "ar-2",
"artist": "artist-1",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
+ "displayArtist": "artist-1",
+ "title": "album-0",
+ "album": "album-0",
+ "coverArt": "al-7",
"name": "album-0",
"songCount": 0,
"duration": 0,
"genre": "Unknown Genre",
- "genres": ["Unknown Genre"],
+ "genres": [{ "name": "Unknown Genre" }],
"year": 2021
},
{
"id": "al-8",
- "coverArt": "al-8",
+ "created": "2019-11-30T00:00:00Z",
"artistId": "ar-2",
"artist": "artist-1",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
+ "displayArtist": "artist-1",
+ "title": "album-1",
+ "album": "album-1",
+ "coverArt": "al-8",
"name": "album-1",
"songCount": 0,
"duration": 0,
"genre": "Unknown Genre",
- "genres": ["Unknown Genre"],
+ "genres": [{ "name": "Unknown Genre" }],
"year": 2021
},
{
"id": "al-9",
- "coverArt": "al-9",
+ "created": "2019-11-30T00:00:00Z",
"artistId": "ar-2",
"artist": "artist-1",
"artists": [{ "id": "ar-2", "name": "artist-1" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
+ "displayArtist": "artist-1",
+ "title": "album-2",
+ "album": "album-2",
+ "coverArt": "al-9",
"name": "album-2",
"songCount": 0,
"duration": 0,
"genre": "Unknown Genre",
- "genres": ["Unknown Genre"],
+ "genres": [{ "name": "Unknown Genre" }],
"year": 2021
},
{
"id": "al-11",
- "coverArt": "al-11",
+ "created": "2019-11-30T00:00:00Z",
"artistId": "ar-3",
"artist": "artist-2",
"artists": [{ "id": "ar-3", "name": "artist-2" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
+ "displayArtist": "artist-2",
+ "title": "album-0",
+ "album": "album-0",
+ "coverArt": "al-11",
"name": "album-0",
"songCount": 0,
"duration": 0,
"genre": "Unknown Genre",
- "genres": ["Unknown Genre"],
+ "genres": [{ "name": "Unknown Genre" }],
"year": 2021
},
{
"id": "al-12",
- "coverArt": "al-12",
+ "created": "2019-11-30T00:00:00Z",
"artistId": "ar-3",
"artist": "artist-2",
"artists": [{ "id": "ar-3", "name": "artist-2" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
+ "displayArtist": "artist-2",
+ "title": "album-1",
+ "album": "album-1",
+ "coverArt": "al-12",
"name": "album-1",
"songCount": 0,
"duration": 0,
"genre": "Unknown Genre",
- "genres": ["Unknown Genre"],
+ "genres": [{ "name": "Unknown Genre" }],
"year": 2021
},
{
"id": "al-13",
- "coverArt": "al-13",
+ "created": "2019-11-30T00:00:00Z",
"artistId": "ar-3",
"artist": "artist-2",
"artists": [{ "id": "ar-3", "name": "artist-2" }],
- "created": "2019-11-30T00:00:00Z",
- "title": "",
- "album": "",
+ "displayArtist": "artist-2",
+ "title": "album-2",
+ "album": "album-2",
+ "coverArt": "al-13",
"name": "album-2",
"songCount": 0,
"duration": 0,
"genre": "Unknown Genre",
- "genres": ["Unknown Genre"],
+ "genres": [{ "name": "Unknown Genre" }],
"year": 2021
}
]
diff --git a/server/ctrlsubsonic/testdata/test_search_three_q_art b/server/ctrlsubsonic/testdata/test_search_three_q_art
index 33a55f6..49ad17d 100644
--- a/server/ctrlsubsonic/testdata/test_search_three_q_art
+++ b/server/ctrlsubsonic/testdata/test_search_three_q_art
@@ -4,6 +4,7 @@
"version": "1.15.0",
"type": "gonic",
"serverVersion": "",
+ "openSubsonic": true,
"searchResult3": {
"artist": [
{ "id": "ar-1", "name": "artist-0", "albumCount": 3 },
diff --git a/server/ctrlsubsonic/testdata/test_search_three_q_tra b/server/ctrlsubsonic/testdata/test_search_three_q_tra
index d085a10..6c50e10 100644
--- a/server/ctrlsubsonic/testdata/test_search_three_q_tra
+++ b/server/ctrlsubsonic/testdata/test_search_three_q_tra
@@ -4,6 +4,7 @@
"version": "1.15.0",
"type": "gonic",
"serverVersion": "",
+ "openSubsonic": true,
"searchResult3": {
"song": [
{
@@ -12,12 +13,17 @@
"albumId": "al-3",
"artist": "artist-0",
"artistId": "ar-1",
+ "artists": [{ "id": "ar-1", "name": "artist-0" }],
+ "displayArtist": "artist-0",
+ "albumArtists": [{ "id": "ar-1", "name": "artist-0" }],
+ "displayAlbumArtist": "artist-0",
"bitRate": 100,
- "contentType": "audio/x-flac",
+ "contentType": "audio/flac",
"coverArt": "al-3",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
"genre": "Unknown Genre",
+ "genres": [{ "name": "Unknown Genre" }],
"isDir": false,
"isVideo": false,
"parent": "al-3",
@@ -35,12 +41,17 @@
"albumId": "al-3",
"artist": "artist-0",
"artistId": "ar-1",
+ "artists": [{ "id": "ar-1", "name": "artist-0" }],
+ "displayArtist": "artist-0",
+ "albumArtists": [{ "id": "ar-1", "name": "artist-0" }],
+ "displayAlbumArtist": "artist-0",
"bitRate": 100,
- "contentType": "audio/x-flac",
+ "contentType": "audio/flac",
"coverArt": "al-3",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
"genre": "Unknown Genre",
+ "genres": [{ "name": "Unknown Genre" }],
"isDir": false,
"isVideo": false,
"parent": "al-3",
@@ -58,12 +69,17 @@
"albumId": "al-3",
"artist": "artist-0",
"artistId": "ar-1",
+ "artists": [{ "id": "ar-1", "name": "artist-0" }],
+ "displayArtist": "artist-0",
+ "albumArtists": [{ "id": "ar-1", "name": "artist-0" }],
+ "displayAlbumArtist": "artist-0",
"bitRate": 100,
- "contentType": "audio/x-flac",
+ "contentType": "audio/flac",
"coverArt": "al-3",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
"genre": "Unknown Genre",
+ "genres": [{ "name": "Unknown Genre" }],
"isDir": false,
"isVideo": false,
"parent": "al-3",
@@ -81,12 +97,17 @@
"albumId": "al-4",
"artist": "artist-0",
"artistId": "ar-1",
+ "artists": [{ "id": "ar-1", "name": "artist-0" }],
+ "displayArtist": "artist-0",
+ "albumArtists": [{ "id": "ar-1", "name": "artist-0" }],
+ "displayAlbumArtist": "artist-0",
"bitRate": 100,
- "contentType": "audio/x-flac",
+ "contentType": "audio/flac",
"coverArt": "al-4",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
"genre": "Unknown Genre",
+ "genres": [{ "name": "Unknown Genre" }],
"isDir": false,
"isVideo": false,
"parent": "al-4",
@@ -104,12 +125,17 @@
"albumId": "al-4",
"artist": "artist-0",
"artistId": "ar-1",
+ "artists": [{ "id": "ar-1", "name": "artist-0" }],
+ "displayArtist": "artist-0",
+ "albumArtists": [{ "id": "ar-1", "name": "artist-0" }],
+ "displayAlbumArtist": "artist-0",
"bitRate": 100,
- "contentType": "audio/x-flac",
+ "contentType": "audio/flac",
"coverArt": "al-4",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
"genre": "Unknown Genre",
+ "genres": [{ "name": "Unknown Genre" }],
"isDir": false,
"isVideo": false,
"parent": "al-4",
@@ -127,12 +153,17 @@
"albumId": "al-4",
"artist": "artist-0",
"artistId": "ar-1",
+ "artists": [{ "id": "ar-1", "name": "artist-0" }],
+ "displayArtist": "artist-0",
+ "albumArtists": [{ "id": "ar-1", "name": "artist-0" }],
+ "displayAlbumArtist": "artist-0",
"bitRate": 100,
- "contentType": "audio/x-flac",
+ "contentType": "audio/flac",
"coverArt": "al-4",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
"genre": "Unknown Genre",
+ "genres": [{ "name": "Unknown Genre" }],
"isDir": false,
"isVideo": false,
"parent": "al-4",
@@ -150,12 +181,17 @@
"albumId": "al-5",
"artist": "artist-0",
"artistId": "ar-1",
+ "artists": [{ "id": "ar-1", "name": "artist-0" }],
+ "displayArtist": "artist-0",
+ "albumArtists": [{ "id": "ar-1", "name": "artist-0" }],
+ "displayAlbumArtist": "artist-0",
"bitRate": 100,
- "contentType": "audio/x-flac",
+ "contentType": "audio/flac",
"coverArt": "al-5",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
"genre": "Unknown Genre",
+ "genres": [{ "name": "Unknown Genre" }],
"isDir": false,
"isVideo": false,
"parent": "al-5",
@@ -173,12 +209,17 @@
"albumId": "al-5",
"artist": "artist-0",
"artistId": "ar-1",
+ "artists": [{ "id": "ar-1", "name": "artist-0" }],
+ "displayArtist": "artist-0",
+ "albumArtists": [{ "id": "ar-1", "name": "artist-0" }],
+ "displayAlbumArtist": "artist-0",
"bitRate": 100,
- "contentType": "audio/x-flac",
+ "contentType": "audio/flac",
"coverArt": "al-5",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
"genre": "Unknown Genre",
+ "genres": [{ "name": "Unknown Genre" }],
"isDir": false,
"isVideo": false,
"parent": "al-5",
@@ -196,12 +237,17 @@
"albumId": "al-5",
"artist": "artist-0",
"artistId": "ar-1",
+ "artists": [{ "id": "ar-1", "name": "artist-0" }],
+ "displayArtist": "artist-0",
+ "albumArtists": [{ "id": "ar-1", "name": "artist-0" }],
+ "displayAlbumArtist": "artist-0",
"bitRate": 100,
- "contentType": "audio/x-flac",
+ "contentType": "audio/flac",
"coverArt": "al-5",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
"genre": "Unknown Genre",
+ "genres": [{ "name": "Unknown Genre" }],
"isDir": false,
"isVideo": false,
"parent": "al-5",
@@ -219,12 +265,17 @@
"albumId": "al-7",
"artist": "artist-1",
"artistId": "ar-2",
+ "artists": [{ "id": "ar-2", "name": "artist-1" }],
+ "displayArtist": "artist-1",
+ "albumArtists": [{ "id": "ar-2", "name": "artist-1" }],
+ "displayAlbumArtist": "artist-1",
"bitRate": 100,
- "contentType": "audio/x-flac",
+ "contentType": "audio/flac",
"coverArt": "al-7",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
"genre": "Unknown Genre",
+ "genres": [{ "name": "Unknown Genre" }],
"isDir": false,
"isVideo": false,
"parent": "al-7",
@@ -242,12 +293,17 @@
"albumId": "al-7",
"artist": "artist-1",
"artistId": "ar-2",
+ "artists": [{ "id": "ar-2", "name": "artist-1" }],
+ "displayArtist": "artist-1",
+ "albumArtists": [{ "id": "ar-2", "name": "artist-1" }],
+ "displayAlbumArtist": "artist-1",
"bitRate": 100,
- "contentType": "audio/x-flac",
+ "contentType": "audio/flac",
"coverArt": "al-7",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
"genre": "Unknown Genre",
+ "genres": [{ "name": "Unknown Genre" }],
"isDir": false,
"isVideo": false,
"parent": "al-7",
@@ -265,12 +321,17 @@
"albumId": "al-7",
"artist": "artist-1",
"artistId": "ar-2",
+ "artists": [{ "id": "ar-2", "name": "artist-1" }],
+ "displayArtist": "artist-1",
+ "albumArtists": [{ "id": "ar-2", "name": "artist-1" }],
+ "displayAlbumArtist": "artist-1",
"bitRate": 100,
- "contentType": "audio/x-flac",
+ "contentType": "audio/flac",
"coverArt": "al-7",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
"genre": "Unknown Genre",
+ "genres": [{ "name": "Unknown Genre" }],
"isDir": false,
"isVideo": false,
"parent": "al-7",
@@ -288,12 +349,17 @@
"albumId": "al-8",
"artist": "artist-1",
"artistId": "ar-2",
+ "artists": [{ "id": "ar-2", "name": "artist-1" }],
+ "displayArtist": "artist-1",
+ "albumArtists": [{ "id": "ar-2", "name": "artist-1" }],
+ "displayAlbumArtist": "artist-1",
"bitRate": 100,
- "contentType": "audio/x-flac",
+ "contentType": "audio/flac",
"coverArt": "al-8",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
"genre": "Unknown Genre",
+ "genres": [{ "name": "Unknown Genre" }],
"isDir": false,
"isVideo": false,
"parent": "al-8",
@@ -311,12 +377,17 @@
"albumId": "al-8",
"artist": "artist-1",
"artistId": "ar-2",
+ "artists": [{ "id": "ar-2", "name": "artist-1" }],
+ "displayArtist": "artist-1",
+ "albumArtists": [{ "id": "ar-2", "name": "artist-1" }],
+ "displayAlbumArtist": "artist-1",
"bitRate": 100,
- "contentType": "audio/x-flac",
+ "contentType": "audio/flac",
"coverArt": "al-8",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
"genre": "Unknown Genre",
+ "genres": [{ "name": "Unknown Genre" }],
"isDir": false,
"isVideo": false,
"parent": "al-8",
@@ -334,12 +405,17 @@
"albumId": "al-8",
"artist": "artist-1",
"artistId": "ar-2",
+ "artists": [{ "id": "ar-2", "name": "artist-1" }],
+ "displayArtist": "artist-1",
+ "albumArtists": [{ "id": "ar-2", "name": "artist-1" }],
+ "displayAlbumArtist": "artist-1",
"bitRate": 100,
- "contentType": "audio/x-flac",
+ "contentType": "audio/flac",
"coverArt": "al-8",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
"genre": "Unknown Genre",
+ "genres": [{ "name": "Unknown Genre" }],
"isDir": false,
"isVideo": false,
"parent": "al-8",
@@ -357,12 +433,17 @@
"albumId": "al-9",
"artist": "artist-1",
"artistId": "ar-2",
+ "artists": [{ "id": "ar-2", "name": "artist-1" }],
+ "displayArtist": "artist-1",
+ "albumArtists": [{ "id": "ar-2", "name": "artist-1" }],
+ "displayAlbumArtist": "artist-1",
"bitRate": 100,
- "contentType": "audio/x-flac",
+ "contentType": "audio/flac",
"coverArt": "al-9",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
"genre": "Unknown Genre",
+ "genres": [{ "name": "Unknown Genre" }],
"isDir": false,
"isVideo": false,
"parent": "al-9",
@@ -380,12 +461,17 @@
"albumId": "al-9",
"artist": "artist-1",
"artistId": "ar-2",
+ "artists": [{ "id": "ar-2", "name": "artist-1" }],
+ "displayArtist": "artist-1",
+ "albumArtists": [{ "id": "ar-2", "name": "artist-1" }],
+ "displayAlbumArtist": "artist-1",
"bitRate": 100,
- "contentType": "audio/x-flac",
+ "contentType": "audio/flac",
"coverArt": "al-9",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
"genre": "Unknown Genre",
+ "genres": [{ "name": "Unknown Genre" }],
"isDir": false,
"isVideo": false,
"parent": "al-9",
@@ -403,12 +489,17 @@
"albumId": "al-9",
"artist": "artist-1",
"artistId": "ar-2",
+ "artists": [{ "id": "ar-2", "name": "artist-1" }],
+ "displayArtist": "artist-1",
+ "albumArtists": [{ "id": "ar-2", "name": "artist-1" }],
+ "displayAlbumArtist": "artist-1",
"bitRate": 100,
- "contentType": "audio/x-flac",
+ "contentType": "audio/flac",
"coverArt": "al-9",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
"genre": "Unknown Genre",
+ "genres": [{ "name": "Unknown Genre" }],
"isDir": false,
"isVideo": false,
"parent": "al-9",
@@ -426,12 +517,17 @@
"albumId": "al-11",
"artist": "artist-2",
"artistId": "ar-3",
+ "artists": [{ "id": "ar-3", "name": "artist-2" }],
+ "displayArtist": "artist-2",
+ "albumArtists": [{ "id": "ar-3", "name": "artist-2" }],
+ "displayAlbumArtist": "artist-2",
"bitRate": 100,
- "contentType": "audio/x-flac",
+ "contentType": "audio/flac",
"coverArt": "al-11",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
"genre": "Unknown Genre",
+ "genres": [{ "name": "Unknown Genre" }],
"isDir": false,
"isVideo": false,
"parent": "al-11",
@@ -449,12 +545,17 @@
"albumId": "al-11",
"artist": "artist-2",
"artistId": "ar-3",
+ "artists": [{ "id": "ar-3", "name": "artist-2" }],
+ "displayArtist": "artist-2",
+ "albumArtists": [{ "id": "ar-3", "name": "artist-2" }],
+ "displayAlbumArtist": "artist-2",
"bitRate": 100,
- "contentType": "audio/x-flac",
+ "contentType": "audio/flac",
"coverArt": "al-11",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
"genre": "Unknown Genre",
+ "genres": [{ "name": "Unknown Genre" }],
"isDir": false,
"isVideo": false,
"parent": "al-11",
diff --git a/server/ctrlsubsonic/testdata/test_search_two_q_alb b/server/ctrlsubsonic/testdata/test_search_two_q_alb
index 99c49df..4703917 100644
--- a/server/ctrlsubsonic/testdata/test_search_two_q_alb
+++ b/server/ctrlsubsonic/testdata/test_search_two_q_alb
@@ -4,6 +4,7 @@
"version": "1.15.0",
"type": "gonic",
"serverVersion": "",
+ "openSubsonic": true,
"searchResult2": {
"album": [
{
diff --git a/server/ctrlsubsonic/testdata/test_search_two_q_art b/server/ctrlsubsonic/testdata/test_search_two_q_art
index ce0edb6..1422196 100644
--- a/server/ctrlsubsonic/testdata/test_search_two_q_art
+++ b/server/ctrlsubsonic/testdata/test_search_two_q_art
@@ -4,6 +4,7 @@
"version": "1.15.0",
"type": "gonic",
"serverVersion": "",
+ "openSubsonic": true,
"searchResult2": {
"artist": [
{ "id": "al-2", "parent": "al-1", "name": "artist-0" },
diff --git a/server/ctrlsubsonic/testdata/test_search_two_q_tra b/server/ctrlsubsonic/testdata/test_search_two_q_tra
index 0457901..18e27d8 100644
--- a/server/ctrlsubsonic/testdata/test_search_two_q_tra
+++ b/server/ctrlsubsonic/testdata/test_search_two_q_tra
@@ -4,14 +4,16 @@
"version": "1.15.0",
"type": "gonic",
"serverVersion": "",
+ "openSubsonic": true,
"searchResult2": {
"song": [
{
"id": "tr-1",
"album": "album-0",
"artist": "artist-0",
+ "artists": [{ "id": "ar-1", "name": "artist-0" }],
"bitRate": 100,
- "contentType": "audio/x-flac",
+ "contentType": "audio/flac",
"coverArt": "al-3",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
@@ -30,8 +32,9 @@
"id": "tr-2",
"album": "album-0",
"artist": "artist-0",
+ "artists": [{ "id": "ar-1", "name": "artist-0" }],
"bitRate": 100,
- "contentType": "audio/x-flac",
+ "contentType": "audio/flac",
"coverArt": "al-3",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
@@ -50,8 +53,9 @@
"id": "tr-3",
"album": "album-0",
"artist": "artist-0",
+ "artists": [{ "id": "ar-1", "name": "artist-0" }],
"bitRate": 100,
- "contentType": "audio/x-flac",
+ "contentType": "audio/flac",
"coverArt": "al-3",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
@@ -70,8 +74,9 @@
"id": "tr-4",
"album": "album-1",
"artist": "artist-0",
+ "artists": [{ "id": "ar-1", "name": "artist-0" }],
"bitRate": 100,
- "contentType": "audio/x-flac",
+ "contentType": "audio/flac",
"coverArt": "al-4",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
@@ -90,8 +95,9 @@
"id": "tr-5",
"album": "album-1",
"artist": "artist-0",
+ "artists": [{ "id": "ar-1", "name": "artist-0" }],
"bitRate": 100,
- "contentType": "audio/x-flac",
+ "contentType": "audio/flac",
"coverArt": "al-4",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
@@ -110,8 +116,9 @@
"id": "tr-6",
"album": "album-1",
"artist": "artist-0",
+ "artists": [{ "id": "ar-1", "name": "artist-0" }],
"bitRate": 100,
- "contentType": "audio/x-flac",
+ "contentType": "audio/flac",
"coverArt": "al-4",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
@@ -130,8 +137,9 @@
"id": "tr-7",
"album": "album-2",
"artist": "artist-0",
+ "artists": [{ "id": "ar-1", "name": "artist-0" }],
"bitRate": 100,
- "contentType": "audio/x-flac",
+ "contentType": "audio/flac",
"coverArt": "al-5",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
@@ -150,8 +158,9 @@
"id": "tr-8",
"album": "album-2",
"artist": "artist-0",
+ "artists": [{ "id": "ar-1", "name": "artist-0" }],
"bitRate": 100,
- "contentType": "audio/x-flac",
+ "contentType": "audio/flac",
"coverArt": "al-5",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
@@ -170,8 +179,9 @@
"id": "tr-9",
"album": "album-2",
"artist": "artist-0",
+ "artists": [{ "id": "ar-1", "name": "artist-0" }],
"bitRate": 100,
- "contentType": "audio/x-flac",
+ "contentType": "audio/flac",
"coverArt": "al-5",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
@@ -190,8 +200,9 @@
"id": "tr-10",
"album": "album-0",
"artist": "artist-1",
+ "artists": [{ "id": "ar-2", "name": "artist-1" }],
"bitRate": 100,
- "contentType": "audio/x-flac",
+ "contentType": "audio/flac",
"coverArt": "al-7",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
@@ -210,8 +221,9 @@
"id": "tr-11",
"album": "album-0",
"artist": "artist-1",
+ "artists": [{ "id": "ar-2", "name": "artist-1" }],
"bitRate": 100,
- "contentType": "audio/x-flac",
+ "contentType": "audio/flac",
"coverArt": "al-7",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
@@ -230,8 +242,9 @@
"id": "tr-12",
"album": "album-0",
"artist": "artist-1",
+ "artists": [{ "id": "ar-2", "name": "artist-1" }],
"bitRate": 100,
- "contentType": "audio/x-flac",
+ "contentType": "audio/flac",
"coverArt": "al-7",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
@@ -250,8 +263,9 @@
"id": "tr-13",
"album": "album-1",
"artist": "artist-1",
+ "artists": [{ "id": "ar-2", "name": "artist-1" }],
"bitRate": 100,
- "contentType": "audio/x-flac",
+ "contentType": "audio/flac",
"coverArt": "al-8",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
@@ -270,8 +284,9 @@
"id": "tr-14",
"album": "album-1",
"artist": "artist-1",
+ "artists": [{ "id": "ar-2", "name": "artist-1" }],
"bitRate": 100,
- "contentType": "audio/x-flac",
+ "contentType": "audio/flac",
"coverArt": "al-8",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
@@ -290,8 +305,9 @@
"id": "tr-15",
"album": "album-1",
"artist": "artist-1",
+ "artists": [{ "id": "ar-2", "name": "artist-1" }],
"bitRate": 100,
- "contentType": "audio/x-flac",
+ "contentType": "audio/flac",
"coverArt": "al-8",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
@@ -310,8 +326,9 @@
"id": "tr-16",
"album": "album-2",
"artist": "artist-1",
+ "artists": [{ "id": "ar-2", "name": "artist-1" }],
"bitRate": 100,
- "contentType": "audio/x-flac",
+ "contentType": "audio/flac",
"coverArt": "al-9",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
@@ -330,8 +347,9 @@
"id": "tr-17",
"album": "album-2",
"artist": "artist-1",
+ "artists": [{ "id": "ar-2", "name": "artist-1" }],
"bitRate": 100,
- "contentType": "audio/x-flac",
+ "contentType": "audio/flac",
"coverArt": "al-9",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
@@ -350,8 +368,9 @@
"id": "tr-18",
"album": "album-2",
"artist": "artist-1",
+ "artists": [{ "id": "ar-2", "name": "artist-1" }],
"bitRate": 100,
- "contentType": "audio/x-flac",
+ "contentType": "audio/flac",
"coverArt": "al-9",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
@@ -370,8 +389,9 @@
"id": "tr-19",
"album": "album-0",
"artist": "artist-2",
+ "artists": [{ "id": "ar-3", "name": "artist-2" }],
"bitRate": 100,
- "contentType": "audio/x-flac",
+ "contentType": "audio/flac",
"coverArt": "al-11",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
@@ -390,8 +410,9 @@
"id": "tr-20",
"album": "album-0",
"artist": "artist-2",
+ "artists": [{ "id": "ar-3", "name": "artist-2" }],
"bitRate": 100,
- "contentType": "audio/x-flac",
+ "contentType": "audio/flac",
"coverArt": "al-11",
"created": "2019-11-30T00:00:00Z",
"duration": 100,
diff --git a/tags/tagcommon/tagcommmon.go b/tags/tagcommon/tagcommmon.go
new file mode 100644
index 0000000..f856013
--- /dev/null
+++ b/tags/tagcommon/tagcommmon.go
@@ -0,0 +1,105 @@
+package tagcommon
+
+import (
+ "errors"
+)
+
+var ErrUnsupported = errors.New("filetype unsupported")
+
+type Reader interface {
+ CanRead(absPath string) bool
+ Read(absPath string) (Info, error)
+}
+
+type Info interface {
+ Title() string
+ BrainzID() string
+ Artist() string
+ Artists() []string
+ Album() string
+ AlbumArtist() string
+ AlbumArtists() []string
+ AlbumBrainzID() string
+ Genre() string
+ Genres() []string
+ TrackNumber() int
+ DiscNumber() int
+ Length() int
+ Bitrate() int
+ Year() int
+}
+
+const (
+ FallbackAlbum = "Unknown Album"
+ FallbackArtist = "Unknown Artist"
+ FallbackGenre = "Unknown Genre"
+)
+
+func MustAlbum(p Info) string {
+ if r := p.Album(); r != "" {
+ return r
+ }
+ return FallbackAlbum
+}
+
+func MustArtist(p Info) string {
+ if r := p.Artist(); r != "" {
+ return r
+ }
+ return FallbackArtist
+}
+
+func MustArtists(p Info) []string {
+ if r := p.Artists(); len(r) > 0 {
+ return r
+ }
+ return []string{MustArtist(p)}
+}
+
+func MustAlbumArtist(p Info) string {
+ if r := p.AlbumArtist(); r != "" {
+ return r
+ }
+ return MustArtist(p)
+}
+
+func MustAlbumArtists(p Info) []string {
+ if r := p.AlbumArtists(); len(r) > 0 {
+ return r
+ }
+ return []string{MustAlbumArtist(p)}
+}
+
+func MustGenre(p Info) string {
+ if r := p.Genre(); r != "" {
+ return r
+ }
+ return FallbackGenre
+}
+
+func MustGenres(p Info) []string {
+ if r := p.Genres(); len(r) > 0 {
+ return r
+ }
+ return []string{MustGenre(p)}
+}
+
+type ChainReader []Reader
+
+func (cr ChainReader) CanRead(absPath string) bool {
+ for _, reader := range cr {
+ if reader.CanRead(absPath) {
+ return true
+ }
+ }
+ return false
+}
+
+func (cr ChainReader) Read(absPath string) (Info, error) {
+ for _, reader := range cr {
+ if reader.CanRead(absPath) {
+ return reader.Read(absPath)
+ }
+ }
+ return nil, ErrUnsupported
+}
diff --git a/tags/taglib/taglib.go b/tags/taglib/taglib.go
new file mode 100644
index 0000000..ff66016
--- /dev/null
+++ b/tags/taglib/taglib.go
@@ -0,0 +1,83 @@
+package taglib
+
+import (
+ "path/filepath"
+ "strconv"
+ "strings"
+
+ "github.com/sentriz/audiotags"
+ "go.senan.xyz/gonic/tags/tagcommon"
+)
+
+type TagLib struct{}
+
+func (TagLib) CanRead(absPath string) bool {
+ switch ext := filepath.Ext(absPath); ext {
+ case ".mp3", ".flac", ".aac", ".m4a", ".m4b", ".ogg", ".opus", ".wma", ".wav", ".wv":
+ return true
+ }
+ return false
+}
+
+func (TagLib) Read(absPath string) (tagcommon.Info, error) {
+ raw, props, err := audiotags.Read(absPath)
+ return &info{raw, props}, err
+}
+
+type info struct {
+ raw map[string][]string
+ props *audiotags.AudioProperties
+}
+
+// https://picard-docs.musicbrainz.org/downloads/MusicBrainz_Picard_Tag_Map.html
+
+func (i *info) Title() string { return first(find(i.raw, "title")) }
+func (i *info) BrainzID() string { return first(find(i.raw, "musicbrainz_trackid")) } // musicbrainz recording ID
+func (i *info) Artist() string { return first(find(i.raw, "artist")) }
+func (i *info) Artists() []string { return find(i.raw, "artists") }
+func (i *info) Album() string { return first(find(i.raw, "album")) }
+func (i *info) AlbumArtist() string { return first(find(i.raw, "albumartist", "album artist")) }
+func (i *info) AlbumArtists() []string { return find(i.raw, "albumartists", "album_artists") }
+func (i *info) AlbumBrainzID() string { return first(find(i.raw, "musicbrainz_albumid")) } // musicbrainz release ID
+func (i *info) Genre() string { return first(find(i.raw, "genre")) }
+func (i *info) Genres() []string { return find(i.raw, "genres") }
+func (i *info) TrackNumber() int { return intSep("/", first(find(i.raw, "tracknumber"))) } // eg. 5/12
+func (i *info) DiscNumber() int { return intSep("/", first(find(i.raw, "discnumber"))) } // eg. 1/2
+func (i *info) Year() int { return intSep("-", first(find(i.raw, "originaldate", "date", "year"))) } // eg. 2023-12-01
+func (i *info) Length() int { return i.props.Length }
+func (i *info) Bitrate() int { return i.props.Bitrate }
+
+func first[T comparable](is []T) T {
+ var z T
+ for _, i := range is {
+ if i != z {
+ return i
+ }
+ }
+ return z
+}
+
+func find(m map[string][]string, keys ...string) []string {
+ for _, k := range keys {
+ if r := filterStr(m[k]); len(r) > 0 {
+ return r
+ }
+ }
+ return nil
+}
+
+func filterStr(ss []string) []string {
+ var r []string
+ for _, s := range ss {
+ if strings.TrimSpace(s) != "" {
+ r = append(r, s)
+ }
+ }
+ return r
+}
+
+func intSep(sep, in string) int {
+ start, _, _ := strings.Cut(in, sep)
+ out, _ := strconv.Atoi(start)
+ return out
+}
diff --git a/transcode/testdata/5s.flac b/transcode/testdata/5s.flac
new file mode 100644
index 0000000..75b894e
Binary files /dev/null and b/transcode/testdata/5s.flac differ
diff --git a/transcode/transcode.go b/transcode/transcode.go
index 3037f0b..d5b9fe1 100644
--- a/transcode/transcode.go
+++ b/transcode/transcode.go
@@ -20,7 +20,7 @@ type Transcoder interface {
var UserProfiles = map[string]Profile{
"mp3": MP3,
- "mp3_320": MP3320,
+ "mp3_320": MP3320,
"mp3_rg": MP3RG,
"opus_car": OpusRGLoud,
"opus": Opus,
@@ -45,7 +45,9 @@ var (
Opus128RG = NewProfile("audio/ogg", "opus", 128, `ffmpeg -v 0 -i -ss -map 0:a:0 -vn -b:a -c:a libopus -vbr on -af "volume=replaygain=track:replaygain_preamp=6dB:replaygain_noclip=0, alimiter=level=disabled, asidedata=mode=delete:type=REPLAYGAIN" -metadata replaygain_album_gain= -metadata replaygain_album_peak= -metadata replaygain_track_gain= -metadata replaygain_track_peak= -metadata r128_album_gain= -metadata r128_track_gain= -f opus -`)
Opus128RGLoud = NewProfile("audio/ogg", "opus", 128, `ffmpeg -v 0 -i -ss -map 0:a:0 -vn -b:a -c:a libopus -vbr on -af "aresample=96000:resampler=soxr, volume=replaygain=track:replaygain_preamp=15dB:replaygain_noclip=0, alimiter=level=disabled, asidedata=mode=delete:type=REPLAYGAIN" -metadata replaygain_album_gain= -metadata replaygain_album_peak= -metadata replaygain_track_gain= -metadata replaygain_track_peak= -metadata r128_album_gain= -metadata r128_track_gain= -f opus -`)
- Opus192 = NewProfile("audio/ogg", "opus", 192, `ffmpeg -v 0 -i -ss -map 0:a:0 -vn -b:a -c:a libopus -vbr on -f opus -`)
+ Opus192 = NewProfile("audio/ogg", "opus", 192, `ffmpeg -v 0 -i -ss -map 0:a:0 -vn -b:a -c:a libopus -vbr on -f opus -`)
+
+ PCM16le = NewProfile("audio/wav", "wav", 0, `ffmpeg -v 0 -i -ss -c:a pcm_s16le -ac 2 -ar 48000 -f s16le -`)
)
type BitRate uint // kilobits/s
diff --git a/transcode/transcode_test.go b/transcode/transcode_test.go
new file mode 100644
index 0000000..eecced2
--- /dev/null
+++ b/transcode/transcode_test.go
@@ -0,0 +1,143 @@
+package transcode_test
+
+import (
+ "bytes"
+ "context"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/require"
+ "go.senan.xyz/gonic/transcode"
+)
+
+var testProfile = transcode.PCM16le
+
+const (
+ // assuming above profile is 48kHz 16bit stereo
+ sampleRate = 48_000
+ bytesPerSample = 2
+ numChannels = 2
+)
+
+const bytesPerSec = sampleRate * bytesPerSample * numChannels
+
+func TestMain(m *testing.M) {
+ if _, err := exec.LookPath("ffmpeg"); err != nil {
+ return // no ffmpeg, skip these tests
+ }
+ os.Exit(m.Run())
+}
+
+// TestTranscode starts a web server that transcodes a 5s FLAC file to PCM audio. A client
+// consumes the result over a 5 second period.
+func TestTranscode(t *testing.T) {
+ t.Parallel()
+
+ testFile := "testdata/5s.flac"
+ testFileLen := 5
+
+ tr := transcode.NewFFmpegTranscoder()
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ require.NoError(t, tr.Transcode(r.Context(), testProfile, testFile, w))
+ w.(http.Flusher).Flush()
+ }))
+ defer server.Close()
+
+ resp, err := server.Client().Get(server.URL)
+ require.NoError(t, err)
+ defer resp.Body.Close()
+
+ var buf bytes.Buffer
+ for {
+ n, err := io.Copy(&buf, io.LimitReader(resp.Body, bytesPerSec))
+ require.NoError(t, err)
+ if n == 0 {
+ break
+ }
+ time.Sleep(1 * time.Second)
+ }
+
+ // we should have 5 seconds of PCM data
+ require.Equal(t, testFileLen*bytesPerSec, buf.Len())
+}
+
+// TestTranscodeWithSeek starts a web server that transcodes a 5s FLAC file to PCM audio, but with a 2 second offset.
+// A client consumes the result over a 3 second period.
+func TestTranscodeWithSeek(t *testing.T) {
+ t.Parallel()
+
+ testFile := "testdata/5s.flac"
+ testFileLen := 5
+
+ seekSecs := 2
+ profile := transcode.WithSeek(testProfile, time.Duration(seekSecs)*time.Second)
+
+ tr := transcode.NewFFmpegTranscoder()
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ require.NoError(t, tr.Transcode(r.Context(), profile, testFile, w))
+ w.(http.Flusher).Flush()
+ }))
+ defer server.Close()
+
+ resp, err := server.Client().Get(server.URL)
+ require.NoError(t, err)
+ defer resp.Body.Close()
+
+ var buf bytes.Buffer
+ for {
+ n, err := io.Copy(&buf, io.LimitReader(resp.Body, bytesPerSec))
+ require.NoError(t, err)
+ if n == 0 {
+ break
+ }
+ time.Sleep(1 * time.Second)
+ }
+
+ // since we seeked 2 seconds, we should have 5-2 = 3 seconds of PCM data
+ require.Equal(t, (testFileLen-seekSecs)*bytesPerSec, buf.Len())
+}
+
+func TestCachingParallelism(t *testing.T) {
+ t.Parallel()
+
+ var realTranscodeCount atomic.Uint64
+ transcoder := callbackTranscoder{
+ transcoder: transcode.NewFFmpegTranscoder(),
+ callback: func() { realTranscodeCount.Add(1) },
+ }
+
+ cacheTranscoder := transcode.NewCachingTranscoder(transcoder, t.TempDir())
+
+ var wg sync.WaitGroup
+ for i := 0; i < 5; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+
+ var buf bytes.Buffer
+ require.NoError(t, cacheTranscoder.Transcode(context.Background(), transcode.PCM16le, "testdata/5s.flac", &buf))
+ require.Equal(t, 5*bytesPerSec, buf.Len())
+ }()
+ }
+
+ wg.Wait()
+
+ require.Equal(t, 1, int(realTranscodeCount.Load()))
+}
+
+type callbackTranscoder struct {
+ transcoder transcode.Transcoder
+ callback func()
+}
+
+func (ct callbackTranscoder) Transcode(ctx context.Context, profile transcode.Profile, in string, out io.Writer) error {
+ ct.callback()
+ return ct.transcoder.Transcode(ctx, profile, in, out)
+}
diff --git a/transcode/transcoder_caching.go b/transcode/transcoder_caching.go
index 8695e7a..d402652 100644
--- a/transcode/transcoder_caching.go
+++ b/transcode/transcoder_caching.go
@@ -7,13 +7,15 @@ import (
"io"
"os"
"path/filepath"
+ "sync"
)
-const perm = 0644
+const perm = 0o644
type CachingTranscoder struct {
cachePath string
transcoder Transcoder
+ locks keyedMutex
}
var _ Transcoder = (*CachingTranscoder)(nil)
@@ -23,7 +25,12 @@ func NewCachingTranscoder(t Transcoder, cachePath string) *CachingTranscoder {
}
func (t *CachingTranscoder) Transcode(ctx context.Context, profile Profile, in string, out io.Writer) error {
- if err := os.MkdirAll(t.cachePath, perm^0111); err != nil {
+ // don't try cache partial transcodes
+ if profile.Seek() > 0 {
+ return t.transcoder.Transcode(ctx, profile, in, out)
+ }
+
+ if err := os.MkdirAll(t.cachePath, perm^0o111); err != nil {
return fmt.Errorf("make cache path: %w", err)
}
@@ -33,9 +40,11 @@ func (t *CachingTranscoder) Transcode(ctx context.Context, profile Profile, in s
}
key := cacheKey(name, args)
- path := filepath.Join(t.cachePath, key)
+ unlock := t.locks.Lock(key)
+ defer unlock()
- cf, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0644)
+ path := filepath.Join(t.cachePath, key)
+ cf, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0o644)
if err != nil {
return fmt.Errorf("open cache file: %w", err)
}
@@ -46,7 +55,8 @@ func (t *CachingTranscoder) Transcode(ctx context.Context, profile Profile, in s
return nil
}
- if err := t.transcoder.Transcode(ctx, profile, in, io.MultiWriter(out, cf)); err != nil {
+ dest := io.MultiWriter(out, cf)
+ if err := t.transcoder.Transcode(ctx, profile, in, dest); err != nil {
os.Remove(path)
return fmt.Errorf("internal transcode: %w", err)
}
@@ -64,3 +74,15 @@ func cacheKey(cmd string, args []string) string {
}
return fmt.Sprintf("%x", sum.Sum(nil))
}
+
+type keyedMutex struct {
+ sync.Map
+}
+
+func (km *keyedMutex) Lock(key string) func() {
+ value, _ := km.LoadOrStore(key, &sync.Mutex{})
+ mu := value.(*sync.Mutex)
+ mu.Lock()
+ // TODO: remove key entry from map to save some space?
+ return mu.Unlock
+}
diff --git a/transcode/transcoder_ffmpeg.go b/transcode/transcoder_ffmpeg.go
index f0a471b..f71b13e 100644
--- a/transcode/transcoder_ffmpeg.go
+++ b/transcode/transcoder_ffmpeg.go
@@ -16,8 +16,10 @@ func NewFFmpegTranscoder() *FFmpegTranscoder {
return &FFmpegTranscoder{}
}
-var ErrFFmpegKilled = fmt.Errorf("ffmpeg was killed early")
-var ErrFFmpegExit = fmt.Errorf("ffmpeg exited with non 0 status code")
+var (
+ ErrFFmpegKilled = fmt.Errorf("ffmpeg was killed early")
+ ErrFFmpegExit = fmt.Errorf("ffmpeg exited with non 0 status code")
+)
func (*FFmpegTranscoder) Transcode(ctx context.Context, profile Profile, in string, out io.Writer) error {
name, args, err := parseProfile(profile, in)
@@ -36,7 +38,7 @@ func (*FFmpegTranscoder) Transcode(ctx context.Context, profile Profile, in stri
switch err := cmd.Wait(); {
case errors.As(err, &exitErr):
- return fmt.Errorf("waiting cmd: %v: %w", err, ErrFFmpegKilled)
+ return fmt.Errorf("waiting cmd: %w: %w", err, ErrFFmpegKilled)
case err != nil:
return fmt.Errorf("waiting cmd: %w", err)
}
diff --git a/version.go b/version.go
index b23a444..06c99af 100644
--- a/version.go
+++ b/version.go
@@ -10,5 +10,7 @@ import (
var version string
var Version = strings.TrimSpace(version)
-const Name = "gonic"
-const NameUpper = "GONIC"
+const (
+ Name = "gonic"
+ NameUpper = "GONIC"
+)
diff --git a/version.txt b/version.txt
index 4312e0d..2a0970c 100644
--- a/version.txt
+++ b/version.txt
@@ -1 +1 @@
-0.15.2
+0.16.1